Tuesday, May 19, 2009

Create an ODBC DSN entry using c# (for MySQL)

Hello friends,

I came across a very useful article by Neil Barnwell

I have used the same with some minor modifications.
__________________________________________________________________
Here is the Call to the function :
__________________________________________________________________
string serverName = "000.00.00.00";
string DSNName = "MyDSNName";
string driverName = "MySQL ODBC 5.1 Driver";
string databaseName = "MyDatabaseName";
string description = "Sample DSN";
string User = "Myusername";
string Password = "Mypwd";

ODBCManager.CreateUSERDSN(DSNName, description, serverName, driverName, false, databaseName, User, Password);

__________________________________________________________________
Now, create a class called ODBCManager.
__________________________________________________________________
public static class ODBCManager
{

private const string ODBC_INI_REG_PATH = "SOFTWARE\\ODBC\\ODBC.INI\\";
private const string ODBCINST_INI_REG_PATH = "SOFTWARE\\ODBC\\ODBCINST.INI\\";


///
/// Creates a new DSN entry with the specified values. If the DSN exists, the values are updated.
///
/// Name of the DSN for use by client applications
/// Description of the DSN that appears in the ODBC control panel applet
/// Network name or IP address of database server
/// Name of the driver to use
/// True to use NT authentication, false to require applications to supply username/password in the connection string
/// Name of the datbase to connect to


public static void CreateSystemDSN(string dsnName, string description, string server, string driverName, bool trustedConnection, string database,string User,string Password)
{

// Lookup driver path from driver name
RegistryKey driverKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + driverName);
if (driverKey == null) throw new Exception(string.Format("ODBC Registry key for driver '{0}' does not exist", driverName));
string driverPath = driverKey.GetValue("Driver").ToString();

// Add value to odbc data sources
RegistryKey datasourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + "ODBC Data Sources");
if (datasourcesKey == null) throw new Exception("ODBC Registry key for datasources does not exist");
datasourcesKey.SetValue(dsnName, driverName);

// Create new key in odbc.ini with dsn name and add values
RegistryKey dsnKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + dsnName);
if (dsnKey == null) throw new Exception("ODBC Registry key for DSN was not created");
dsnKey.SetValue("Database", database);
dsnKey.SetValue("Description", description);
dsnKey.SetValue("Driver", driverPath);
dsnKey.SetValue("Server", server);
dsnKey.SetValue("Database", database);
dsnKey.SetValue("User", User);
dsnKey.SetValue("Password", Password);

dsnKey.SetValue("Trusted_Connection", trustedConnection ? "Yes" : "No");

}


public static void CreateUSERDSN(string dsnName, string description, string server, string driverName, bool trustedConnection, string database, string User, string Password)
{

// Lookup driver path from driver name for HKEY_CURRENT_USER
RegistryKey driverKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + driverName);

if (driverKey == null) throw new Exception(string.Format("ODBC Registry key for driver '{0}' does not exist", driverName));
string driverPath = driverKey.GetValue("Driver").ToString();

// Add value to odbc data sources
RegistryKey datasourcesKey = Registry.CurrentUser.CreateSubKey(ODBC_INI_REG_PATH + "ODBC Data Sources");
if (datasourcesKey == null) throw new Exception("ODBC Registry key for datasources does not exist");
datasourcesKey.SetValue(dsnName, driverName);

// Create new key in odbc.ini with dsn name and add values
RegistryKey dsnKey = Registry.CurrentUser.CreateSubKey(ODBC_INI_REG_PATH + dsnName);
if (dsnKey == null) throw new Exception("ODBC Registry key for DSN was not created");
dsnKey.SetValue("Database", database);
dsnKey.SetValue("Description", description);
dsnKey.SetValue("Driver", driverPath);
dsnKey.SetValue("Server", server);
dsnKey.SetValue("Database", database);
dsnKey.SetValue("User", User);
dsnKey.SetValue("Password", Password);

dsnKey.SetValue("Trusted_Connection", trustedConnection ? "Yes" : "No");

}

///
/// Removes a DSN entry
///
/// Name of the DSN to remove.
public static void RemoveDSN(string dsnName)
{

// Remove DSN key
Registry.LocalMachine.DeleteSubKeyTree(ODBC_INI_REG_PATH + dsnName);

// Remove DSN name from values list in ODBC Data Sources key
RegistryKey datasourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + "ODBC Data Sources");
if (datasourcesKey == null) throw new Exception("ODBC Registry key for datasources does not exist");
datasourcesKey.DeleteValue(dsnName);

}

///
/// Checks the registry to see if a DSN exists with the specified name
///
public static bool DSNExists(string dsnName)
{

bool retval = false;
string DSNPath ="";
try
{
RegistryKey dsnKey = Registry.CurrentUser.CreateSubKey(ODBC_INI_REG_PATH,RegistryKeyPermissionCheck.ReadSubTree);
if (dsnKey.OpenSubKey(dsnName) != null)
{
DSNPath = dsnKey.OpenSubKey(dsnName).Name;
if (DSNPath.Equals(dsnKey.Name + @"\" + dsnName))
{
retval = true;
}
}

}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return retval;

}

///
/// Returns an array of driver names installed on the system
///

public static string[] GetInstalledDrivers()
{

RegistryKey driversKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + "ODBC Drivers");
if (driversKey == null) throw new Exception("ODBC Registry key for drivers does not exist");

string [] driverNames = driversKey.GetValueNames();

List ret = new List();

foreach (string driverName in driverNames)
{
if (driverName != "(Default)")
{
ret.Add(driverName);
}
}

return ret.ToArray();

}

}
__________________________________________________________________
courtesy:http://stackoverflow.com/questions/334939/how-do-i-create-an-odbc-dsn-entry-using-c.

Enjoy Guys,
Swapnil Shejul

Wednesday, May 13, 2009

Export DatagridView contents to Excel File

Hi Friends,

I read about a simple article on how to Export DatagridView contents to Excel File.
With due credit to author(I lost the link), I am posting it for you all.
______________________________________________________________
Call to the function:

string ExcelFileName = @"C:\TestingExcelFolder\" + "Testing.xls";
this.export_datagridview_to_excel(ref dGViewTesting, ExcelFileName);
______________________________________________________________
Function definition :

public void export_datagridview_to_excel(ref DataGridView dgv, string excel_file)
{
if(!System.IO.Directory.Exists(@"C:\TestingExcelFolder"))
{
System.IO.Directory.CreateDirectory(@"C:\TestingExcelFolder");
}
if (!System.IO.File.Exists(excel_file))
{
System.IO.FileStream fs = System.IO.File.Create(excel_file);
fs.Dispose();
}

int cols;
//--open file
StreamWriter wr = new StreamWriter(excel_file);
//--determine the number of columns and write columns to file
cols = dgv.Columns.Count;
wr.WriteLine("\t Heading\t");
wr.WriteLine();
for (int i = 0; i < cols; i++)
{
wr.Write(dgv.Columns[i].HeaderText.ToString().ToUpper() + "\t");
}

wr.WriteLine();
//--write rows to excel file
for (int i = 0; i <= (dgv.Rows.Count - 1); i++)
{
for (int j = 0; j < cols; j++)
{
if (dgv.Rows[i].Cells[j].Value != null)
wr.Write(dgv.Rows[i].Cells[j].Value + "\t");
else
{ wr.Write("\t"); }
}

wr.WriteLine();
}
//--close file
wr.Close();
}
______________________________________________________________

Let's Make Things Simple :-)

Sunday, May 10, 2009

Establish connection to MySQL database hosted on LINUX machine through Windows Client

I am going to explain stepwise how to access a MySQL database on LINUX machine through Windows.

1. Install mysql-connector-odbc-5.1.5-win32.msi setup on your machine.
2. Add a Data Source Name (DSN) using ODBC DataSource Administrator.
3.Goto Control Panel-->Administrative tools.
4.Select Data Sources (ODBC).
5.It will open up ODBC DataSource Administrator window.
6.Click Add-->Select MySQL ODBC 5.1 Driver from the list.Click Finish.
7.Specify the following connection parammeters,
______________________________________________
Data Source Name:Your new DNS name.
Description: any
Server:
IP Address of the LINUX machine.
Port: 3306 by default.
User
:LINUX Server's mysql username.
Password:
LINUX Server's mysql username.
DataBase:
MySQL Database name.

Test the connection and if successful click OK.
______________________________________________

Now specify the connection string in your application.

string odbc_connectionstr = "DSN=Mysource;Server=100.200.3.50;Database=mydbname;User=myusername;Password=mypassword;Port=3306";
________________________________________________
Also, Include Namespace in your application:
using System.Data.Odbc;
________________________________________________

Regards,
Good Luck Guys....stay connected !!!



Thursday, May 7, 2009

Resize an Image having its source set to URL on Web

Call to function:


bool iscreated = this.getImageByUrl(result.Url, imgdirectory + @"\"+ Myimage.Title);
if (iscreated == true)
{
//-------------------
try
{
string CPath = imgdirectory + @"\" + Myimage.Title;
FileStream s = File.Open(CPath, FileMode.Open, FileAccess.Read);
Image temp = Image.FromStream(s);
Image resizedimage = temp.GetThumbnailImage(110, 90, new
System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), System.IntPtr.Zero);
s.Close();
pictureBoxGoogleImage.Image = resizedimage;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

}

public bool ThumbnailCallback()
{
return true;
}

public bool getImageByUrl(string url, string filename)
{

WebResponse response = null;
Stream remoteStream = null;
StreamReader readStream = null;
try
{
WebRequest request = WebRequest.Create(url);
if (request != null)
{
response = request.GetResponse();
if (response != null)
{
remoteStream = response.GetResponseStream();
readStream = new StreamReader(remoteStream);
System.Drawing.Image img = System.Drawing.Image.FromStream(remoteStream);
if (img == null)
return false;
// YOUR CODE HERE: make manipulations with the image object
// save image to disk
///img.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);


img.Save(filename);
img.Dispose();
}
}
}
catch (Exception ex)
{ }
finally
{
if (response != null) response.Close();
if (remoteStream != null) remoteStream.Close();
if (readStream != null) readStream.Close();
}

return true;
}