Wednesday, October 7, 2009

MAC-Based Authentication for Web Sites using C#

using SHDocVw;
using mshtml;

String url = "YourWebSite.com/login.aspx";
IHTMLElementCollection htmlCollection;
HTMLDocument html;
HTMLInputElement htmlInput;
object obj = null;
InternetExplorer ie=new InternetExplorer();
ie.Navigate(url,ref obj,ref obj,ref obj,ref obj);
while (ie.Busy)
{
Application.DoEvents();
}
html =(HTMLDocument)ie.Document;
ie.Visible = true;
htmlCollection= html.getElementsByTagName("input");

foreach(HTMLInputElement input in htmlCollection)
{
if (input.name == "txtUserName") //txtUserName is your login.aspx page text control
input.innerText = "mylogin"; // assign username in login.aspx page
if (input.name == "txtPassword") //txtPassword is your login.aspx page text control
input.innerText = "mypassword"; //assign password in login.aspx page
if (input.name == "txtMACAddress") //txtMACAddress is your login.aspx text control
input.innerText = "00:00:11:22:33:55"; //assign macAddress in login page
}
while (ie.Busy)
{
Application.DoEvents();
}
htmlCollection = html.getElementsByTagName("input");
foreach (HTMLButtonElement btn in htmlCollection)
{
if (btn.name == "btnLogin")
btn.click();

}
while (ie.Busy)
{
Application.DoEvents();
}


Note: Add "following reference in your Application
1) Add Reference --> Browse --> .System32(search inside windows folder) -->SHDocVw.exe
2) Add Reference --> .Net --> Microsoft.mshtml
Note: To get MAC address of machine please ref Article "http://code4developer.blogspot.com/2009/09/get-mac-address-of-client-machine-using.html"

How to get executable file information in C#

using System.IO;

string executableName = Application.ExecutablePath;
MessageBox.Show(executableName);
FileInfo executableFileInfo = new FileInfo(executableName);
string executableDirectoryName = executableFileInfo.DirectoryName;
MessageBox.Show(executableDirectoryName);

Friday, September 18, 2009

Get MAC address of client machine using C#

using System.Management;

String query = "select MacAddress FROM Win32_NetworkAdapter";
ObjectQuery objQuery = new ObjectQuery(query);
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(objQuery);
string macAddress = string.Empty;
foreach (ManagementObject obj in moSearcher.Get())
{
if(macAddress==string.Empty){
macAddress = obj["MACAddress"].ToString();
obj.Dispose();
}
}
MessageBox.Show(macAddress.ToString());

Note: Add System.Management in reference
(
Solution Explorer --> Add Reference --> .NET --> System.Management )

Sunday, August 30, 2009

Maximum length of a query string

Maximum length of Query string is based on the browser not depend upon the Asp.Net.

Maximum length of a query string in IE is 2083 characters

Opera supports - 4050 characters.

Netscape 6 supports - 2000 characters.

Tuesday, June 30, 2009

Assigning null value to datetime in C#

 DateTime? currentTime=new DateTime();  
currentTime= null;

Note: Put question mark (?) after type to assign nullable value,

Friday, June 26, 2009

Get application version in C#

 using System.Reflection;  
Assembly.GetExecutingAssembly().GetName().Version

Monday, June 15, 2009

Difference between Codebehind="Default.aspx.cs" and Src="Default.aspx.cs"

CODE:
1:  CodeBehind is relevant to Visual Studio.NET only.

Difference between Response.Write() and Response.Output.Write()

CODE:
1:  Response.Output.Write() allows you to write formatted output.
2: For Ex:
3: using System.Security.Principal;
4: Response.Write ("Process running <br />");
5: Response.Output.Write("Process running as {0}",WindowsIdentity.GetCurrent().Name);

ASP .Net Page Life Cycle

CODE:
1:  Init() - when the page is instantiated
2: Load() - when the page is loaded into server memory
3: PreRender() - the brief moment before the page is displayed to the user as HTML
4: Unload() - when page finishes loading.

Wednesday, June 10, 2009

How to get the host name and IP address of local machine using C#.

How to get the host name and IP address of local machine using C#?Here is a example to get host name and IP address of local machine.
CODE:
1 : using System.Net;
2 : string strHostName = Dns.GetHostName();
3 : IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
4 : IPAddress[] ipAddress= ipEntry.AddressList;
5 : MessageBox.Show("Local machine host name="+strHostName.ToString());
6 : MessageBox.Show("IP address="+ipAddress[0].ToString());

How to check internet connection in C#

A simple example, for check internet connection is avilable or not
CODE:
1 :  Using System.Net ;
2 :  try{
3 :  HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create("abc.com");
4 :  HttpWebResponse webRes= (HttpWebResponse)webReq.GetResponse();
5 :  if (HttpStatusCode.OK == webRes.StatusCode)
6 :  {
7 :  webRes.Close();
8 :  // write code here...........
9 :  }
10 :  }
11 :  catch (Exception ex)
12 :  {
13 :  MessageBox.Show("Unable to connect");
14 :  }

Friday, June 5, 2009

Convert Image into jpeg format

CODE:
1 : using System.IO;
2 : using System.Drawing;
3 : using System.Drawing.Imaging;
4 : using System.Reflection;
5 : using System.Drawing.Drawing2D;
6 : public class _Library
7 : {
8 : public string w;
9 : public string h;
10 : public _Library()
11 : {
12 : }
13 : /* for uploading Image */
14 : public String UploadFile(FileUpload Fileobject,String Path)
15 : {
16 : String FileName = "";
17 : String[] getformat;
18 : String imgformat1 = "", imgformat2 = "";
19 : if (Fileobject.HasFile)
20 : {
21 : FileName = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + "_" + Fileobject.FileName.Replace(' ','-').ToLower();
22 : Fileobject.SaveAs(@"" + Path + "" + FileName);
23 : getformat =FileName.ToString().Split('.');
24 : imgformat1 = getformat[0].ToString();
25 : imgformat2 = getformat[1].ToString();
26 : if (imgformat2.ToString().Equals("jpg"))
27 : {
28 : }
29 : else
30 : {
31 : FileName = ConvertIntoJPEG(Path + "" + FileName);
32 : }
33 : }
34 : return FileName;
35 : }
36 : public void UploadFile(FileUpload Fileobject, String NewFilePath, String NewFileName)
37 : {
38 : String FileName = "";
39 : if (Fileobject.HasFile)
40 : {
41 : //FileName = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + "_" + Fileobject.FileName.Replace(' ', '-').ToLower();
42 : Fileobject.SaveAs(@"" + NewFilePath + "" + NewFileName);
43 : FileName = ConvertIntoJPEG(NewFilePath + "" + NewFileName);
44 : }
45 : }
46 : public bool ThumbnailCallback()
47 : {
48 : return false;
49 : }
50 : public void ImageResizeHigherSide(String Source_Desti,int image_higher_size)
51 : {
52 : String source = Source_Desti;
53 : String desti = Source_Desti + "._tmpfile";
54 : String Del_abspath = source;
55 : Bitmap myBitmap = new Bitmap(source);
56 : int higher_size = image_higher_size;
57 : int h_w_n_h = 0;
58 : int n_w = 0;
59 : int n_h = 0;
60 : int o_w = myBitmap.Width;
61 : int o_h = myBitmap.Height;
62 : if (o_w > higher_size || o_h > higher_size)
63 : {
64 : if (o_w > o_h)
65 : {
66 : n_w = higher_size;
67 : n_h = o_h * higher_size / o_w;
68 : }
69 : else
70 : {
71 : n_h = higher_size;
72 : n_w = o_w * higher_size / o_h;
73 : }
74 : try
75 : {
76 : //getting higher size of image
77 : if (o_w > o_h) h_w_n_h = o_w;
78 : else h_w_n_h = o_h;
79 : if (image_higher_size > h_w_n_h)
80 : {
81 : n_h = o_h;
82 : n_w = o_w;
83 : }
84 : System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(this.ThumbnailCallback);
85 : System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(n_w, n_h, myCallback, IntPtr.Zero);
86 : ////myBitmap.SetResolution(100, 100);
87 : Graphics myresizer;
88 : myresizer = Graphics.FromImage(myThumbnail);
89 : myresizer.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
90 : myresizer.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
91 : myresizer.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
92 : myresizer.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
93 : //////myresizer.DrawImage(myBitmap, new Rectangle(0, 0, n_w, n_h), 0, 0, n_w, n_h, GraphicsUnit.Pixel);
94 : myresizer.DrawImage(myBitmap, 0, 0, n_w, n_h);
95 : // myBitmap.Save(desti, ImageFormat.Jpeg);
96 : myThumbnail.Save(desti, ImageFormat.Jpeg);
97 : myresizer.Dispose();
98 : myThumbnail.Dispose();
99 : myBitmap.Dispose();
100 : File.Delete(source);
101 : File.Move(desti,desti.Replace("._tmpfile", ""));
102 : File.Delete(desti);
103 : }
104 : catch (Exception ex){}
105 : }
106 : }
107 : private String ConvertIntoJPEG(String Source_Desti)
108 : {
109 : String source = Source_Desti;
110 : String ext = source.Substring(source.LastIndexOf('.'));
111 : String desti = source;
112 : desti = desti.Replace(ext, ".jpg");
113 : desti = desti + "._tmpfile";
114 : String nJpegFileName = "";
115 : String Del_abspath = source;
116 : Bitmap myBitmap = new Bitmap(source);
117 : int o_w = myBitmap.Width;
118 : int o_h = myBitmap.Height;
119 : try
120 : {
121 : System.Drawing.Image.GetThumbnailImageAbort myCallback =
122 : new System.Drawing.Image.GetThumbnailImageAbort(this.ThumbnailCallback);
123 : System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(o_w, o_h, myCallback, IntPtr.Zero);
124 : Graphics myresizer;
125 : myresizer = Graphics.FromImage(myThumbnail);
126 : myresizer.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
127 : myresizer.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
128 : myresizer.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
129 : myresizer.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
130 : //////myresizer.DrawImage(myBitmap, new Rectangle(0, 0, n_w, n_h), 0, 0, n_w, n_h, GraphicsUnit.Pixel);
131 : myresizer.DrawImage(myBitmap, 0, 0, o_w, o_h);
132 : myThumbnail.Save(desti, ImageFormat.Jpeg);
133 : myThumbnail.Dispose();
134 : myBitmap.Dispose();
135 : File.Delete(source);
136 : File.Move(desti, desti.Replace("._tmpfile", ""));
137 : File.Delete(desti);
138 : }
139 : catch (Exception ex)
140 : {
141 : }
142 : desti = desti.Replace("._tmpfile", "");
143 : nJpegFileName = desti.Substring(desti.LastIndexOf("\\") + 1);
144 : return nJpegFileName;
145 : }
146 : /* For deleting Image from Folder*/
147 : public void DeleteFile(String Del_abspath)
148 : {
149 : if (Del_abspath != null)
150 : {
151 : try
152 : {
153 : String delpath = Del_abspath.Replace('\\', '/');
154 : File.Delete(delpath);
155 : }
156 : catch (Exception ex) { }
157 : }
158 : }
159 : }

Tuesday, May 12, 2009

Adding TimeSpan value in DataTime

DateTime today = DateTime.Now;
TimeSpan duration = new TimeSpan(days,hours,minutes, seconds);
DateTime result= today.Add(duration);

Convert string to DateTime in C#

DateTime date=DateTime.Parse('5/12/2009 12:26:32 PM');

Read a XML document with C#

using system.xml;

string price="";
string author="";

// initialize dom module
XmlDocument xmldoc = new XmlDocument();
// load xml
xmldoc.Load(books.xml);
XmlNodeList records = xmldoc.GetElementsByTagName("book");
foreach (XmlElement xe in records)
{
XmlElement elmt = (XmlElement)xe;
price= elmt.GetElementsByTagName("price")[0].InnerText;
author= elmt.GetElementsByTagName("author")[0].InnerText;

MessageBox.Show("Author="+author+"==> Price="+price);
}

books.xml

< books >
< book >
< author > abc < /author >
< price > 30 < /price >
< /book >
< book >
< author > xyz< /author >
< price > 100< /price >
</ book >

< books >

OUT PUT

Author=abc ==> Price=30
Author=xyz==> Price=100




Delegate in c#

// Declare the Delegate
public delegate void delegateName();

// Create the object of Delegate
delegateName dn= new Uploaddelegate(callme);


public static void callme
()
{
// code to do here
}

Thursday, April 30, 2009

File upload using FTP

using system.net;
using system.io;

FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://myDoc.com/xyz.pdf"); /
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;

//Load the file
FileStream stream = File.OpenRead(filePath); //c:/myDoc/xyz.pdf
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();

//Upload file
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
btnUpload.UseWaitCursor = false;