Wednesday, January 14, 2009

How to Print Web Page Controls Using C# 2.0

Create a web form like below. Put all the controls inside one Panel.
print
On click event of the “Print Page” button write below code.
   1:  //Write the below code for click event of the "Print Page" button
   2:      protected void btnPrintPage_Click(object sender,
           EventArgs e)
   3:      {
   4:          Session["ctrl"] = Panel1;
   5:          Control ctrl = (Control)Session["ctrl"];
   6:          PrintWebControl(ctrl);
   7:      }

Use the below namespace
using System.IO;

Create the function PrintWebControl which is calling from the click event of the “Page Print” button.
   1:  public static void PrintWebControl(Control ControlToPrint)
   2:      {
   3:          StringWriter stringWrite = new StringWriter();
   4:          System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
   5:          if (ControlToPrint is WebControl)
   6:          {
   7:              Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ControlToPrint).Width = w;
   8:          }
   9:          Page pg = new Page();
  10:          pg.EnableEventValidation = false;
  11:          HtmlForm frm = new HtmlForm();
  12:          pg.Controls.Add(frm);
  13:          frm.Attributes.Add("runat", "server");
  14:          frm.Controls.Add(ControlToPrint);
  15:          pg.DesignerInitialize();
  16:          pg.RenderControl(htmlWrite);
  17:          string strHTML = stringWrite.ToString();
  18:          HttpContext.Current.Response.Clear();
  19:          HttpContext.Current.Response.Write(strHTML);
  20:          HttpContext.Current.Response.Write("<script>window.print();</script>");
  21:          HttpContext.Current.Response.End();
  22:      }

Done!!!! Execute it…Enjoy printing controls….

Tuesday, January 13, 2009

How to create Windows Service Using C#

Step1.
To create a new Window Service, pick Windows Service option from your Visual C# Projects, give your service a name, and click OK.
This action will add WinService1.cs class to your project.
Set your ServiceName to your own name so it would be easier to recognize your service during testing OR you can set this property programmatically using this line this.ServiceName = "MyWinService";
Step 2. Add functionality to your service
The default code of WebService1.cs added will have two overridden functions OnStart and OnStop. The OnStart function executes when you start your service and the OnStop function gets execute when you stop a service. I write some text to a text file when you start and stop the service.
   1:  protected override void OnStart(string[] args) 
   2:  { 
   3:  FileStream fs = new FileStream(@"c:\temp\mcWindowsService.txt" , 
   4:  FileMode.OpenOrCreate, FileAccess.Write); 
   5:  StreamWriter m_streamWriter = new StreamWriter(fs); 
   6:  m_streamWriter.BaseStream.Seek(0, SeekOrigin.End); 
   7:  m_streamWriter.WriteLine(" mcWindowsService: Service Started \n"); 
   8:  m_streamWriter.Flush();
   9:  m_streamWriter.Close(); 
  10:  } 
  11:  /// <summary> 
  12:  /// Stop this service. 
  13:  /// </summary> 
  14:  protected override void OnStop() 
  15:  { 
  16:  FileStream fs = new FileStream(@"c:\temp\mcWindowsService.txt" , 
  17:  FileMode.OpenOrCreate, FileAccess.Write); 
  18:  StreamWriter m_streamWriter = new StreamWriter(fs); 
  19:  m_streamWriter.BaseStream.Seek(0, SeekOrigin.End); 
  20:  m_streamWriter.WriteLine(" mcWindowsService: Service Stopped \n"); m_streamWriter.Flush();
  21:  m_streamWriter.Close(); 
  22:  } 

Step 2.5.
a) Return to Design view for WinService1.
b) Click the background of the designer to select the service itself, rather than any of its contents.
c) Right click on the Designed Windows and in the Properties window, click the Add Installer link in the gray area beneath the list of properties.
d) By default, a component class containing two installers is added to your project. The component is named ProjectInstaller, and the installers it contains are the installer for your service and the installer for the service's associated process.
e) Access Design view for ProjectInstaller, and click ServiceInstaller1. In the Properties window, set the ServiceName property to MyNewService. Set the StartType property to Automatic.
f) In the designer, select ServiceProcessInstaller1 (for a Visual Basic project), or serviceProcessInstaller1 (for a Visual C# project). Set the Account property to LocalService. This will cause the service to be installed and to run on a local service account.
After the above procedure, try registering using InstallUtil utilities.
Step 3: Install and Run the Service
Build of this application makes one exe, MyWinService.exe. You need to call installutil to
egister this service from command line.
installutil C:\mcWebService\bin\Debug\mcWebService.exe
You use /u option to uninstall the service.
installutil /u C:\mcWebService\bin\Debug\mcWebService.exe
Run the application
Step 4: Start and Stop the Service
You need to go to the Computer Management to start and stop the service. You can use Manage menu item by right clicking on My Computer. 
Under Services and Applications, you will see the service MyWinService. Start and Stop menu item starts and stops the service.
Go to your temp directory and see if text file is there with contents or not.
That's it.

Friday, January 9, 2009

How to write Event viewer log using C#

Call the below function, this will create and write into the event viewer.
   1:  private void LogErrorToEventLog() 
   2:  { 
   3:  string sSource; 
   4:  string sLog; 
   5:  string strEvent="Error Occured";
   6:  sSource = "test"; 
   7:  sLog = "Application"; 
   8:  if (!EventLog.SourceExists(sSource)) 
            EventLog.CreateEventSource(sSource,sLog); 
   9:  EventLog.WriteEntry(sSource, 
       strEvent,EventLogEntryType.Error, 234); 
  10:  } 

Send mail from outlook using C#

 
Copy the below code and paste it as "OutlookMail.cs".
 
Using System;
Namespace OutLookMail
 
Public class OutlookMail
Private Outlook.Application objApp;
Private Outlook._NameSpace objNameSpace;
Private Outlook.MAPIFolder oOutboxFolder;
 
Public OutlookMail()
objApp = new Outlook.Application();
objNameSpace= objApp.GetNamespace("MAPI");
objNameSpace.Logon(null,null,true,true);
objOutbox = objNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderOutbox);
 
Public void SendMailOutlook(string toEmailId, string ccEmailId, string strAttachment, string StrSubject, string StrBody)
Outlook._MailItem objMail = (Outlook._MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem); 
ObjMail.To = toEmailId;
ObjMail.CC = ccEmailId;
ObjMail.Subject = StrSubject;
if (strAttachment!="")
ObjMail.StrAttachmentments.Add(strAttachment,1,1,"Email Test from Outlook using VB.NET");
ObjMail.Body = StrBody;
ObjMail.Send();
Don't forget to add reference to outlook 11.0 or higher which ever you are using.
Happy mailing!!!!!!!

When to Use Delegates Instead of Interfaces (C# )


Both delegates and interfaces allow a class designer to separate type declarations and implementation. A given interface can be inherited and implemented by any class or struct; a delegate can created for a method on any class, as long as the method fits the method signature for the delegate. An interface reference or a delegate can be used by an object with no knowledge of the class that implements the interface or delegate method. Given these similarities, when should a class designer use a delegate and when should they use an interface?
Use a delegate when:
•    An eventing design pattern is used.
•    It is desirable to encapsulate a static method.
•    The caller has no need access other properties, methods, or interfaces on the object implementing the method.
•    Easy composition is desired.
•    A class may need more than one implementation of the method.
Use an interface when:
•    There are a group of related methods that may be called.
•    A class only needs one implementation of the method.
•    The class using the interface will want to cast that interface to other interface or class types.
•    The method being implemented is linked to the type or identity of the class: for example, comparison methods.
One good example of using a single-method interface instead of a delegate is IComparable or IComparable. IComparable declares the CompareTo method, which returns an integer specifying a less than, equal to, or greater than relationship between two objects of the same type. IComparable can be used as the basis of a sort algorithm, and while using a delegate comparison method as the basis of a sort algorithm would be valid, it is not ideal. Because the ability to compare belongs to the class, and the comparison algorithm doesn’t change at run-time, a single-method interface is ideal.

Thursday, January 8, 2009

Advantages of Using Globally Unique Identifier (GUID) as a Primary Key.

Advantages of Using Globally Unique Identifier (GUID) as a Primary Key Advantages:
 
■ If you use an auto-number Id column and if many people are creating new DataRow objects, it will be difficult for you to merge data later because there may be many duplicate keys.

■ The Guid data type is a “surrogate” key, meaning that its only purpose is to define uniqueness of the row and aid in connecting multiple tables together via relationships. This means that there is no reason for a user to see and change this value, which simplifies maintenance of the DataSet. If you allow the user to change the primary key on a row, you have to propogate the change down to all of the related tables. For example, changing the CompanyId value requires the update of the Company Id value in the Employee table.

■ The use of the Guid can simplify the joining of tables, which is better than the scenarios where you use compound keys that are based on the actual data. Compound keys typically result in smaller data footprints because the key is based on actual data, whereas joining tables is usually more difficult because compound joins are required. Remember that if you are using compound keys that are based on the actual data, you inevitably need to deal with recursive updates.

Advantages of JQuery? or Why we Use JQuery?

The first thing that most Javascript programmers end up doing is adding some code to their program, similar to this:
window.onload = function(){ alert("welcome"); }
Inside of which is the code that you want to run right when the page is loaded. Problematically, however, the Javascript code isn't run until all images are finished downloading (this includes banner ads). The reason for using “window.onload” in the first place is due to the fact that the HTML 'document' isn't finished loading yet, when you first try to run your code.
To circumvent both problems, here comes jQuery...Write Less, Do More, JavaScript Library.
   1:  <HTML>
   2:  <head>
   3:   
   4:  <!--download jquery.js and use the same version.
       here i used "jquery-1.2.6.min.js"-->
   5:  <script type="text/javascript" 
       src="jquery-1.2.6.min.js"></script>
   6:   
   7:  <script type="text/javascript">
   8:   
   9:  //Mandatory function to start jquery on load.
  10:  $(document).ready( function() {
  11:   
  12:  //below line will apply style to all paragraph so 
       this should come first. 
  13:  //Try moving this line below the paragraph by id tag
       style and see the difference.
  14:  $("p").css( {color: "yellow", background: "green"} ); 
  15:   
  16:   
  17:  //Firsr and second are the name of the paragraph.
  18:  $("#First").css( {color: "red",
       background: "yellow"} );  
  19:  $("#Second").css( {color: "white",
       background: "black"} );  
  20:   
  21:  //another function to play around the anchor <a> tag
  22:     $("a").click(function(event)
  23:      {
  24:        alert("Welcome to asheej.blogspot.com");
  25:   
  26:  //comment the above single line and uncomment below
       three line and see what JQyery can do.
  27:   
  28:  //      alert("As you can see, the link no longer took
       you to jquery.com");
  29:  //      event.preventDefault();
  30:  //        $(this).hide("slow");
  31:   
  32:       }
  33:       );
  34:   
  35:  });
  36:  </script>
  37:   
  38:  <head/>  
  39:   
  40:  <BODY>  
  41:   
  42:      <DIV style="border: 3px solid Green;">  
  43:      <A href= "http://asheej.blogspot.com/">Google</a>  
  44:      </DIV>  
  45:   
  46:      <P id="First">This is First paragraph</p>  
  47:      <P id="Second">This is Second paragraph</p>  
  48:      <P>This is Third paragraph</p>  
  49:      <P>This is Fourth paragraph</p>  
  50:   
  51:  </BODY>  
  52:  </HTML>