Monday, August 3, 2009

simply Delegates

namespace mynamespace
{
public partial class Testclass
{
//delegate declaration
public delegate void mydelegate(string email, string eName);

//method to use with the delagate
public void methodfordelegate(string email, string eName)
{
try
{
loadContactPage(email, eName);
}
catch (Exception ex)
{
Messagebox.Show(ex.ToString());
}
}

//delegate object declaration
static mydelegate OBJmydelegate;

//----------------------------------------------------------------------
public void initializedelegate()
{
OBJmydelegate = new mydelegate(methodfordelegate);
}

public static void UseOfDelegate(string email, string eName)
{
try
{
OBJmydelegate.Invoke(email, eName);
}
catch (Exception ex)
{
Messagebox.Show(ex.ToString());
}
}

}
}

how to convert web page to pdf

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.xml;
using System.Xml;
using iTextSharp.text.html.simpleparser;
public partial class Pdf : System.Web.UI.Page
{
protected override void Render(HtmlTextWriter writer)
{
MemoryStream mem = new MemoryStream();
StreamWriter twr = new StreamWriter(mem);
HtmlTextWriter myWriter = new HtmlTextWriter(twr);
base.Render(myWriter);
myWriter.Flush();
myWriter.Dispose();
StreamReader strmRdr = new StreamReader(mem);
strmRdr.BaseStream.Position = 0;
string pageContent = strmRdr.ReadToEnd();
strmRdr.Dispose();
mem.Dispose();
writer.Write(pageContent);
CreatePDFDocument(pageContent);


}
public void CreatePDFDocument(string strHtml)
{

string strFileName = HttpContext.Current.Server.MapPath("test.pdf");
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
StringReader se = new StringReader(strHtml);
HTMLWorker obj = new HTMLWorker(document);
document.Open();
obj.Parse(se);
document.Close();
ShowPdf(strFileName);



}
public void ShowPdf(string strFileName)
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
Response.ContentType = "application/pdf";
Response.WriteFile(strFileName);
Response.Flush();
Response.Clear();
}
}

courtesy: http://aspdotnetcodebook.blogspot.com/2009/04/how-to-convert-web-page-to-pdf.html

Tuesday, June 23, 2009

Convert datetime to formatted string

Hi Friendz,

Often we feel the need to convert a datetime value to a formatted string.

For E.g.:suppose I have a datetime value 3 hours past current time. while displaying it to user in a more user Friendly way,I want to display it something like this. "3 hours Ago".

I have written an if else statement which does this job.


private string manageTime(string dtconvert)
{
TimeSpan ts;
ts = DateTime.Now.Subtract(Convert.ToDateTime(dtconvert));
//------------------------------------------------------------------------
string temp = (ts.Days > 0) ? ((ts.Days > 364) ? (((ts.Days / 365) == 1) ? Convert.ToString(ts.Days / 365) + " year ago" : Convert.ToString(ts.Days / 365) + " years ago")
: (ts.Days > 29) ? (((ts.Days / 30) == 1) ? Convert.ToString(ts.Days / 30) + " month ago" : Convert.ToString(ts.Days / 30) + " months ago")
: (ts.Days == 1 ? Convert.ToString(ts.Days) + " day ago" : Convert.ToString(ts.Days) + " days ago"))
: ((ts.Hours > 0) ? ((ts.Hours == 1) ? Convert.ToString(ts.Hours) + " hour ago" : Convert.ToString(ts.Hours) + " hours ago")
: ((ts.Minutes > 0) ? ((ts.Minutes == 1) ? Convert.ToString(ts.Minutes) + " min ago" : Convert.ToString(ts.Minutes) + " mins ago")
: ((ts.Seconds == 1) ? Convert.ToString(ts.Seconds) + " sec ago" : Convert.ToString(ts.Seconds) + " secs ago")));
return temp;
}

Hope you will like it !!!

Till my next post,Good bye ....Take Care :-)

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;
}

Thursday, March 12, 2009

In-Memory Dataset operation (Add/Mod/Del) using C#

DataSet dstestoperation = new DataSet();
DataTable dtTestTab = new DataTable();
DataView dvTest;
private FileInfo fitest = new FileInfo(@"c:\MyXML\PicturePath.xml");
private FileInfo fitestschema = new FileInfo(@"c:\MyXML\PicturePath.xsd");

private void DeleteFromTestDataset()
{
DataRow[] dtTestTabrowcollection = (DataRow[])dtTestTab.Select("PictureEmail = '" + txtEmailid.Text + "'");
if (dtTestTabrowcollection.Length > 0)
{
foreach (DataRow myrow in dtTestTabrowcollection)
{
myrow.Delete();
}
}
getcount();
}
private void AddtoTestDataset()
{
DataRow myrow = dtTestTab.NewRow();
myrow["PictureEntryid"] = "A00";
myrow["PictureEmail"] = txtEmailid.Text;
myrow["PictureName"] = "cartoons";
myrow["PictureIcon"] = @"C:\Documents and Settings\My Documents\My Pictures\swaps_"+DateTime.Now.Minute.ToString() + ".jpg";
myrow["PicturePhone"] = "+111-111-1111";
dtTestTab.Rows.Add(myrow);
getcount();
}
private void ModifyTestDataset()
{
DataRow[] dtTestTabrowcollection = (DataRow[])dtTestTab.Select("PictureEmail = '" + txtEmailid.Text + "'");
if (dtTestTabrowcollection.Length > 0)
{
foreach (DataRow myrow in dtTestTabrowcollection)
{
myrow["PictureName"] = "MyPictures";
}
}
getcount();
}
private int testDuplicate()
{
DataRow[] dtTestTabrowcollection = (DataRow[])dtTestTab.Select("Pictureid = '" + txtid.Text + "'");
return (dtTestTabrowcollection.Length - 1);
}
private int TitleCase()
{
System.Globalization.CultureInfo mycultureinfo = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Globalization.TextInfo mytextinfo = mycultureinfo.TextInfo;
txtEmailid.Text = mytextinfo.ToTitleCase(txtEmailid.Text);
}


private void btnSave_Click(object sender, EventArgs e)
{
dtTestTab.AcceptChanges();
dstestoperation.WriteXml(fitest.FullName, XmlWriteMode.IgnoreSchema);
btnSave.Enabled = false;
}

How to convert strings to title (proper) case by using C#

Convert a String to Title Case

The String class does not include a method that converts a string to title case. The ToTitleCase method resides in the TextInfo class, which is a member of the System.Globalization namespace. Unlike the ToUpper and ToLower methods of the String class, the ToTitleCase method is not a static method and requires an instance of the class.

When you use the TextInfo class, you must specify cultural information. In most situations, you can default to the culture that is currently in use. Culture information is a property of the thread on which the code is running. To obtain the culture information, you must gain access to the current thread and retrieve the CurrentCulture property from that thread. Once you accomplish this, you can create the TextInfo object. For example:

CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;



The TextInfo class also includes the ToUpper and ToLower methods. Use these methods of TextInfo if you need to specify culture options.

Console.WriteLine(textInfo.ToTitleCase(title));
Console.WriteLine(textInfo.ToLower(title));
Console.WriteLine(textInfo.ToUpper(title));


If you need to create or manipulate strings that have specific culture settings, you can use one of the overloaded constructors of the TextInfo class to create strings with any of the available culture options.

Courtesy: http://support.microsoft.com/kb/312890

Saturday, March 7, 2009

How can we check that our internet connection is working or not.

private void Form1_Load(object sender, EventArgs e)
{
try
{
this.testconnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

private void testconnection()
{
if (this.IsConnectionAvailable())
MessageBox.Show("Internet available");
else
MessageBox.Show("No Internet");
}

public bool IsConnectionAvailable()
{
System.Net.WebRequest objWebReq = System.Net.WebRequest.Create("http://www.microsoft.com/");
System.Net.WebResponse objResp = default(System.Net.WebResponse);
try
{
objResp = objWebReq.GetResponse();
objResp.Close();
objWebReq = null;
IsConnected = true;
return true;
}

catch (Exception ex)
{
objResp = null;
objWebReq = null;
IsConnected = false;
return false;
}
}

Courtesy: http://www.devasp.net/net/articles/display/639.html
-----------------------------------------------------------------------------------
private bool CheckInternetAvailability()
{
try
{
System.Net.IPHostEntry ipaddress = System.Net.Dns.GetHostByName("www.google.com");
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
}

Courtesy: http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=13045

Tuesday, February 17, 2009

Selecting a text pattern in the RichTextBox

Hi Friends,

There are lots of methods to select a Text pattern inside the RichTextbox body.
But When we put this RichTextbox inside a particular container(Eg:DataRepeater) we don't get the desired results.

This is due to the redraw and rendering of the DataRepeater.

For this I have a small solution.Here is the piece of Code for you;


private void Pattern_SelectionSenderDate(ref RichTextBox RTF_Box)
{
try
{
RTF_Box.DeselectAll();
RTF_Box.Refresh();
string strtempRTF_BoxText = RTF_Box.Text;
RTF_Box.Clear();

RTF_Box.Text = strtempRTF_BoxText;
int pos = 0;
string searchQuery = txtbxSearchBox.Text;
while (searchQuery.Length > 0)
{
pos = RTF_Box.Text.ToLower().ToString().IndexOf(searchQuery.ToLower(), pos);
if (pos == -1)
{
break;
}
RTF_Box.Select(pos, searchQuery.Length);
RTF_Box.SelectionColor = Color.FromArgb(153, 153, 153);
RTF_Box.SelectionBackColor = Color.Yellow;
RTF_Box.SelectionFont = new Font("Lucida Sans", (float)8.25,
System.Drawing.FontStyle.Bold);
pos = pos + 1;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}


Hope you like it.
Note: If you want to make this recipe more crispy,suggestions are always welcome :-)