Warning: mssql_connect() [function.mssql-connect]: Unable to connect to se
Soure: http://ar2.php.net/function.mssql-connect
dkman one two three at hotmail dot com
27-Nov-2007 05:01
Using: Apache 2.2
PHP 5.2.5
SQL 2005 (on a separate pc)
Getting error:
Call to undefined function: mysql_connect()...
Fixed by:
copy ntwdblib.dll from php to apache\bin
copy php_mssql.dll from php\ext to apache\bin
Then I received a timeout error, but at least it tried to connect:
Warning: mssql_connect() [function.mssql-connect]: Unable to connect to server...
Fixed by:
Following a prior suggestion I downloaded a new version of ntwdblib.dll from Webzila (with one L). You need to enable Javascript and click on downloads, then search.
Put the new ntwdblib.dll (2000.80.194.0) in the apache\bin directory
Restart the apache service
Then I was able to connect!
SQL Notes:
SQL should be in mixed mode (authentication)
I enabled named pipes as others described:
1) On the SQL Server go into "SQL Server configuration Manager" from the start menu.
2) Click SQL Server 2005 Network Configuration
3) Click Protocols for [YOUR SQL]
4) Enable Named Pipes
PHP Notes:
Edit the INI file to uncomment extension=php_mssql.dll
The default for secure is mssql.secure_connection = Off, I left this alone.
domingo, 25 de mayo de 2008
lunes, 5 de mayo de 2008
Prevenir Resize y Minimización de Ventana -
La propiedad que permite prohibir la opción de minimizar y modificar el tamaño de la pantalla es FormBorderStyle.
Las opciones posibles están en este post de msdn:
http://msdn.microsoft.com/es-es/library/hw8kes41(VS.80).aspx
Las opciones posibles están en este post de msdn:
http://msdn.microsoft.com/es-es/library/hw8kes41(VS.80).aspx
Etiquetas:
.NET,
C#,
prevent resizing,
resizing,
Winforms
viernes, 29 de febrero de 2008
Crystal Reports en WinForms - Exportar a pdf un reporte con C#.NET
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
namespace ClockManager
{
public partial class Reports : Form
{
#region Propiedades
public string filePath = "";
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
#endregion
#region Metodos
public Reports()
{
InitializeComponent();
}
public void SaveFile()
{
if (filePath.Trim() == "")
return;
//
TuNameSpace.RPT_FECHA_HORA_X_ID rpt = new TuNameSpace.RPT_FECHA_HORA_X_ID();
ReportDocument myReport = new ReportDocument();
//Le paso un parametro al reporte [esto es opcional]
rpt.SetParameterValue("@ID", "25832556");
//Defino los parametros de conexion
string UserID = "usuario1";
string Password = "123456";
string ServerName = "MiPc\\SQLEXPRESS";
string DatabaseName = "MIBASE";
//Seteo los parametros de conexion
rpt.SetDatabaseLogon(UserID, Password, ServerName, DatabaseName);
try
{
//Exporto el archivo
rpt.ExportToDisk(ExportFormatType.PortableDocFormat, this.filePath);
MessageBox.Show("OK!");
}
catch (Exception ex)
{
string a = ex.Message;
}
}
#endregion
private void Reports_Load(object sender, EventArgs e)
{
//Seteo algunas propiedades del SaveFileDialog
this.saveFileDialog1.AddExtension = true;
this.saveFileDialog1.AutoUpgradeEnabled = true;
this.saveFileDialog1.CheckFileExists = false;
this.saveFileDialog1.CheckPathExists = false;
this.saveFileDialog1.DefaultExt = ".pdf";
this.saveFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.saveFileDialog1_FileOk);
saveFileDialog1.ShowDialog();
}
#region Eventos
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
this.filePath = saveFileDialog1.FileName;
SaveFile();
}
#endregion
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
namespace ClockManager
{
public partial class Reports : Form
{
#region Propiedades
public string filePath = "";
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
#endregion
#region Metodos
public Reports()
{
InitializeComponent();
}
public void SaveFile()
{
if (filePath.Trim() == "")
return;
//
TuNameSpace.RPT_FECHA_HORA_X_ID rpt = new TuNameSpace.RPT_FECHA_HORA_X_ID();
ReportDocument myReport = new ReportDocument();
//Le paso un parametro al reporte [esto es opcional]
rpt.SetParameterValue("@ID", "25832556");
//Defino los parametros de conexion
string UserID = "usuario1";
string Password = "123456";
string ServerName = "MiPc\\SQLEXPRESS";
string DatabaseName = "MIBASE";
//Seteo los parametros de conexion
rpt.SetDatabaseLogon(UserID, Password, ServerName, DatabaseName);
try
{
//Exporto el archivo
rpt.ExportToDisk(ExportFormatType.PortableDocFormat, this.filePath);
MessageBox.Show("OK!");
}
catch (Exception ex)
{
string a = ex.Message;
}
}
#endregion
private void Reports_Load(object sender, EventArgs e)
{
//Seteo algunas propiedades del SaveFileDialog
this.saveFileDialog1.AddExtension = true;
this.saveFileDialog1.AutoUpgradeEnabled = true;
this.saveFileDialog1.CheckFileExists = false;
this.saveFileDialog1.CheckPathExists = false;
this.saveFileDialog1.DefaultExt = ".pdf";
this.saveFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.saveFileDialog1_FileOk);
saveFileDialog1.ShowDialog();
}
#region Eventos
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
this.filePath = saveFileDialog1.FileName;
SaveFile();
}
#endregion
}
}
T-SQL - Función para saber si un numero es par
CREATE FUNCTION DBO.ISPAR
(@ID SMALLINT)
RETURNS CHAR(1)
AS
BEGIN
DECLARE @RESULT CHAR(1)
SET @RESULT = CASE WHEN ABS(@ID) % 2 = 1
THEN
'I' --IMPAR
ELSE
'P' --PAR
END
RETURN @RESULT
END
(@ID SMALLINT)
RETURNS CHAR(1)
AS
BEGIN
DECLARE @RESULT CHAR(1)
SET @RESULT = CASE WHEN ABS(@ID) % 2 = 1
THEN
'I' --IMPAR
ELSE
'P' --PAR
END
RETURN @RESULT
END
martes, 26 de febrero de 2008
FillSortGridControl
///
/// Crea los items del combo que permite la seleccion del campo por el
/// cual se desea ordena r la grilla.
/// [Las columnas del tipo Template no estan soportadas]
///
/// param name="gridControl">Grilla que contiene las columnas
/// param name="sortControl">Combo que permite la seleccion de ordenado de la grilla
public void FillSortGridControl(GridView gridControl, DropDownList sortControl)
{
sortControl.Items.Clear();
foreach (DataControlField gridColumn in gridControl.Columns)
{
string text = gridColumn.HeaderText; ;
string value = "";
switch (gridColumn.GetType().ToString())
{
case ("System.Web.UI.WebControls.BoundField"):
value = ((BoundField)gridColumn).DataField;
break;
case ("System.Web.UI.WebControls.HyperLinkField"):
value = ((HyperLinkField)gridColumn).DataTextField;
break;
case ("System.Web.UI.WebControls.TemplateField"):
//value = ((TemplateField)gridColumn).ItemTemplate;
break;
}
if (text != "" && value != "")
{
sortControl.Items.Add(new ListItem(text + " asc", value + " asc"));
sortControl.Items.Add(new ListItem(text + " desc", value + " desc"));
}
}
}
/// Crea los items del combo que permite la seleccion del campo por el
/// cual se desea ordena r la grilla.
/// [Las columnas del tipo Template no estan soportadas]
///
/// param name="gridControl">Grilla que contiene las columnas
/// param name="sortControl">Combo que permite la seleccion de ordenado de la grilla
public void FillSortGridControl(GridView gridControl, DropDownList sortControl)
{
sortControl.Items.Clear();
foreach (DataControlField gridColumn in gridControl.Columns)
{
string text = gridColumn.HeaderText; ;
string value = "";
switch (gridColumn.GetType().ToString())
{
case ("System.Web.UI.WebControls.BoundField"):
value = ((BoundField)gridColumn).DataField;
break;
case ("System.Web.UI.WebControls.HyperLinkField"):
value = ((HyperLinkField)gridColumn).DataTextField;
break;
case ("System.Web.UI.WebControls.TemplateField"):
//value = ((TemplateField)gridColumn).ItemTemplate;
break;
}
if (text != "" && value != "")
{
sortControl.Items.Add(new ListItem(text + " asc", value + " asc"));
sortControl.Items.Add(new ListItem(text + " desc", value + " desc"));
}
}
}
Metodo ShowMessage en ASP.NET
///
/// Muestra un mensaje del lado del cliente generado con una instruccion
/// alert() en javascript
///
/// param name="sender"> La clase (generalmente el formulario que muestra el mensaje) donde se debe mostrar el mensaje.
/// param name="message">Mensaje que desea mostrar.
public void ShowMessage(System.Web.UI.Page sender, string message)
{
string msg = "alert('" + message + "');";
sender.ClientScript.RegisterStartupScript(base.GetType(), "jsValMot", msg, true);
}
/// Muestra un mensaje del lado del cliente generado con una instruccion
/// alert() en javascript
///
/// param name="sender"> La clase (generalmente el formulario que muestra el mensaje) donde se debe mostrar el mensaje.
/// param name="message">Mensaje que desea mostrar.
public void ShowMessage(System.Web.UI.Page sender, string message)
{
string msg = "alert('" + message + "');";
sender.ClientScript.RegisterStartupScript(base.GetType(), "jsValMot", msg, true);
}
Validar campos vacios,
///
/// Para validar que los campos no están vacios
///
/// param name="a">Array de string de parametros
public bool Validar(string[] a)
{
foreach (string s in a)
{
if (s == "")
{
return false;
}
}
return true;
}
string[] a = new string[] { txtUsuario.Text.Trim(), txtPass.Text.Trim() };
if (!Validar(a))
{
MessageBox.Show("Todos los campos son obligatorios.");
return;
}
/// Para validar que los campos no están vacios
///
/// param name="a">Array de string de parametros
public bool Validar(string[] a)
{
foreach (string s in a)
{
if (s == "")
{
return false;
}
}
return true;
}
string[] a = new string[] { txtUsuario.Text.Trim(), txtPass.Text.Trim() };
if (!Validar(a))
{
MessageBox.Show("Todos los campos son obligatorios.");
return;
}
Etiquetas:
Validación,
Validar campos vacios,
Validation
Arma llamadas a Stored Procedures
///
/// Basicamente es para no tener que agregar las comas y las comillas
/// a los parametros cada vez que quiero llamar un Stored Procedure.
///
/// param name="sp">Nombre del Stored Procedure a ejecutar
/// param name="param">Array de string de parametros para pasar al StoredProcedure
public string BuildQueryFromString(string sp, string[] param)
{
string query = sp + " '";
int i = 0;
foreach (string p in param)
{
if (i < param.Length - 1)
query += p + "', '";
else
query += p + "'";
i++;
}
return query;
}
/// Basicamente es para no tener que agregar las comas y las comillas
/// a los parametros cada vez que quiero llamar un Stored Procedure.
///
/// param name="sp">Nombre del Stored Procedure a ejecutar
/// param name="param">Array de string de parametros para pasar al StoredProcedure
public string BuildQueryFromString(string sp, string[] param)
{
string query = sp + " '";
int i = 0;
foreach (string p in param)
{
if (i < param.Length - 1)
query += p + "', '";
else
query += p + "'";
i++;
}
return query;
}
SqlServerCe - SQL Server Compact Edition (Winforms)
/*
Clase tipo capa de datos para Sql Server Compact Edition.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SqlServerCe;
class DBPortable
{
private static string dbName = "MyDB";
private static string pass = "123456";
private static string connString = "Data Source =\"|DataDirectory|\\" + dbName + ".sdf\"; Password =\"" + pass + "\";";
private SqlCeConnection conn = new SqlCeConnection(connString);
public DBPortable()
{
if (!HaveDB())
{
CreateDB();
CreateSchema();
}
}
private bool HaveDB()
{
if (System.IO.File.Exists(conn.Database))
{
return true;
}
else
{
return false;
}
}
private void CreateDB()
{
using (SqlCeEngine sqlCeEngine = new SqlCeEngine(connString))
{
sqlCeEngine.CreateDatabase();
}
}
public string BuildQueryFromString(string sp, string[] param)
{
string query = sp + " '";
int i = 0;
foreach (string p in param)
{
if (i < param.Length - 1)
query += p + "', '";
else
query += p + "'";
i++;
}
return query;
}
public DataSet ExecQuery(string iQuery)
{
DataSet ds = new DataSet();
SqlCeDataAdapter adapter = new SqlCeDataAdapter();
try
{
SqlCeCommand command = new SqlCeCommand(iQuery, this.conn);
adapter.SelectCommand = command;
this.conn.Open();
command.Connection = this.conn;
adapter.Fill(ds);
}
catch (SqlCeException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
this.conn.Close();
}
return ds;
}
public DataSet ExecSP(string sp, string[] param)
{
string iQuery = BuildQueryFromString(sp, param);
DataSet ds = new DataSet();
SqlCeDataAdapter adapter = new SqlCeDataAdapter();
try
{
SqlCeCommand command = new SqlCeCommand(iQuery, this.conn);
adapter.SelectCommand = command;
this.conn.Open();
command.Connection = this.conn;
adapter.Fill(ds);
}
catch(SqlCeException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
this.conn.Close();
}
return ds;
}
private void CreateSchema()
{
string q = "CREATE TABLE TablaDePrueba(ID int NULL, FechaHora DATETIME NULL, ESTADO NCHAR(1))";
this.ExecuteNonQuery(q);
}
private int ExecuteNonQuery(string query)
{
int RowsAffected = 0;
SqlCeCommand objCom = new SqlCeCommand();
objCom.CommandText = query;
try
{
this.conn.Open();
objCom.Connection = this.conn;
RowsAffected = objCom.ExecuteNonQuery();
}
catch (SqlCeException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
this.conn.Close();
}
return RowsAffected;
}
Clase tipo capa de datos para Sql Server Compact Edition.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SqlServerCe;
class DBPortable
{
private static string dbName = "MyDB";
private static string pass = "123456";
private static string connString = "Data Source =\"|DataDirectory|\\" + dbName + ".sdf\"; Password =\"" + pass + "\";";
private SqlCeConnection conn = new SqlCeConnection(connString);
public DBPortable()
{
if (!HaveDB())
{
CreateDB();
CreateSchema();
}
}
private bool HaveDB()
{
if (System.IO.File.Exists(conn.Database))
{
return true;
}
else
{
return false;
}
}
private void CreateDB()
{
using (SqlCeEngine sqlCeEngine = new SqlCeEngine(connString))
{
sqlCeEngine.CreateDatabase();
}
}
public string BuildQueryFromString(string sp, string[] param)
{
string query = sp + " '";
int i = 0;
foreach (string p in param)
{
if (i < param.Length - 1)
query += p + "', '";
else
query += p + "'";
i++;
}
return query;
}
public DataSet ExecQuery(string iQuery)
{
DataSet ds = new DataSet();
SqlCeDataAdapter adapter = new SqlCeDataAdapter();
try
{
SqlCeCommand command = new SqlCeCommand(iQuery, this.conn);
adapter.SelectCommand = command;
this.conn.Open();
command.Connection = this.conn;
adapter.Fill(ds);
}
catch (SqlCeException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
this.conn.Close();
}
return ds;
}
public DataSet ExecSP(string sp, string[] param)
{
string iQuery = BuildQueryFromString(sp, param);
DataSet ds = new DataSet();
SqlCeDataAdapter adapter = new SqlCeDataAdapter();
try
{
SqlCeCommand command = new SqlCeCommand(iQuery, this.conn);
adapter.SelectCommand = command;
this.conn.Open();
command.Connection = this.conn;
adapter.Fill(ds);
}
catch(SqlCeException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
this.conn.Close();
}
return ds;
}
private void CreateSchema()
{
string q = "CREATE TABLE TablaDePrueba(ID int NULL, FechaHora DATETIME NULL, ESTADO NCHAR(1))";
this.ExecuteNonQuery(q);
}
private int ExecuteNonQuery(string query)
{
int RowsAffected = 0;
SqlCeCommand objCom = new SqlCeCommand();
objCom.CommandText = query;
try
{
this.conn.Open();
objCom.Connection = this.conn;
RowsAffected = objCom.ExecuteNonQuery();
}
catch (SqlCeException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
this.conn.Close();
}
return RowsAffected;
}
Método para encriptar a MD5
public string md5(string strPlainText)
{
byte[] hashedDataBytes;
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Security.Cryptography.MD5CryptoServiceProvider md5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();
hashedDataBytes = md5Hasher.ComputeHash(encoder.GetBytes(strPlainText));
string a = "";
foreach (byte b in hashedDataBytes)
{
a += b.ToString();
}
return a;
}
{
byte[] hashedDataBytes;
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Security.Cryptography.MD5CryptoServiceProvider md5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();
hashedDataBytes = md5Hasher.ComputeHash(encoder.GetBytes(strPlainText));
string a = "";
foreach (byte b in hashedDataBytes)
{
a += b.ToString();
}
return a;
}
Suscribirse a:
Entradas (Atom)