Saturday, March 28, 2009

Calendar Using JavaScript with MastePage

Many people using master page might wonder why calendar control is not opening if they are using master page in their normal aspx page., If you add and call the JavaScript cleaner control similar to the normal aspx page calendar won’t be displayed in the page using master page….so I just posting this article to show you how this works….
There is no extra or special coding for this…
First, add JavaScript/CSS reference in MASTER page like below,
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Maste Page</title>
    <script src="\calendar\calendar.js" type="text/javascript"></script>
    <link href="\calendar\Calendar.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>
Then call the JavaScript function to show the calendar based on the JavaScript you are using. Here my function is
showCalendar(<TextBox Name>,<Date Format>)
instead of passing control name we are passing ID of the control. This is the only change you have to remember…
<asp:TextBox ID="txtDateCreated" runat="server"></asp:TextBox><input id="DateCreated" onclick="return showCalendar('ctl00_ContentPlaceHolder1_txtDateCreated', '%m/%d/%Y',true);" type="image" src="calendar/calendar.gif">
Execute the code…see that wonderful calendar.

Monday, March 23, 2009

How to return values from JavaScript function to the C# page load

Add the JavaScript function just below the HTML <title> tag. This function should have __doPostBack to return value.
   1:     <script language="javascript">
   2:          function RetVal()
   3:          {
   4:              var testVar = 'abc'
   5:              __doPostBack('Test',testVar);
   6:          }
   7:      </script>

Add a label to display the values from JavaScript function.
Add a text box to page and set the AutoPostBack property to true. One control with AutoPostBack property set to true is required in the page to get the value from JavaScript function using __doPostBack.
In Page_Load write the following code.
   1:  protected void Page_Load(object sender, EventArgs e)
   2:  {
   3:    if (IsPostBack)
   4:    {
   5:      string arg = Request.Form["__EVENTTARGET"];
   6:      string val = Request.Form["__EVENTARGUMENT"];
   7:      if (arg == "Test")
   8:      {
   9:       Label1.Text = val;
  10:      }
  11:    }
  12:     else
  13:     {
  14:      string script;
  15:      script = @"<SCRIPT language='javascript'> RetVal
           ();" + "</SCRIPT>";
  16:      Page.RegisterStartupScript("Test", script);
  17:     }
  18:    }

Page.RegisterStartupScript: Allows ASP.NET server controls to emit client-side script blocks in the Page, now this method is obsolete, in ASP.NET 2.0 it gives you an error - or more correctly warnings telling you that both functions are obsolete.
'System.Web.UI.Page.IsStartupScriptRegistered(string)' is obsolete: 'The recommended alternative is ClientScript.IsStartupScriptRegistered(string key).
"The __EVENTTARGET hidden variable will tell the server ,which control actually does the server side event firing so that the framework can fire the server side event for that control."
The __ EVENTARGUMENT variable is used to provide additional event information if needed by the application, which can be accessed in the server
Execute the code and see the result…

Tuesday, March 3, 2009

List all the Stored Procedures Associated with a specific Table

DECLARE @TABLENAME VARCHAR(50)
SET @TABLENAME='<table name>'    --Pass the Table Name here
SELECT @TableName as [Table Name],A.Name AS [SP Name],B.Text as [SP Text] from SYSOBJECTS A
INNER JOIN SYSCOMMENTS B
ON A.ID=B.ID 
WHERE B.TEXT LIKE '%'+@TableName+'%'
and A.TYPE='P'
Same way we can use this to find out View, Trigger etc..
V: View
TR: Trigger

See the out put…

SQL query to fetch all the tables and column names from the database

select table_name, column_name, data_type, character_maximum_length, is_nullable 
from information_schema.columns 
where table_name in (select name from sysobjects where xtype='U') order by table_name

Here xtype='U' means user table.

Some of the other options you can use are,
C: Check constraint
D: Default constraint
F: Foreign Key constraint
L: Log
P: Stored procedure
PK: Primary Key constraint
RF: Replication Filter stored procedure
S: System table
TR: Trigger
U: User table
UQ: Unique constraint
V: View
X: Extended stored procedure
Press F5 and see the result!!!!!!

Tuesday, February 24, 2009

How to download file from FTP server using C#

Add below namespaces,
using System.Net;
using System.IO;
using System.Text;

Create a button and add the below code under button click
//fileName = Name of the file to be downloaded from FTP server.
        string fileName = "test.txt";

        //filePath = The full path where the file is to be created. Here i put local system path.
        string filePath = "C:\\FTP";
        
        string ftpServerIP = "<IP Address>";
        string ftpUserID = "<User ID>";
        string ftpPassword = "<Password>";
        FtpWebRequest reqFTP;
        try
        {
            FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream ftpStream = response.GetResponseStream();
            long cl = response.ContentLength;
            int bufferSize = 2048;
            int readCount;
            byte[] buffer = new byte[bufferSize];
            readCount = ftpStream.Read(buffer, 0, bufferSize);
            while (readCount > 0)
            {
                outputStream.Write(buffer, 0, readCount);
                readCount = ftpStream.Read(buffer, 0, bufferSize);
            }
            ftpStream.Close();
            outputStream.Close();
            response.Close();
        }
        catch (Exception ex)
        {
           string errMsg= (ex.Message);
        }

Execute the code and see the C:\FTP folder for the file….

Monday, February 23, 2009

How to upload file to FTP server using C#

Add below namespaces,
using System.Net;
using System.IO;

Create a button and add the below code under button click
        string filename = "c:\\test.txt";
        string ftpServerIP = "<IP address>";
        string ftpUserID = "<userid>";
        string ftpPassword = "<Password>";

        FileInfo fileInf = new FileInfo(filename);

     string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

        FtpWebRequest reqFTP;

        // Create FtpWebRequest object
        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));

        //Provide ftp userid and password
        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

        // By default KeepAlive is true, where the control connection is not closed
        // after a command is executed.
        reqFTP.KeepAlive = false;

        //Specify the command to be executed. Here we use upload file command
        reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

        //data transfer type we use here is binary
        reqFTP.UseBinary = true;

        // Notify the server about the size of the uploaded file
        reqFTP.ContentLength = fileInf.Length;

        // The buffer size is set to 2kb
        int buffLength = 2048;

        byte[] buff = new byte[buffLength];

        int contentLen;

        // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
        FileStream fs = fileInf.OpenRead();

        try
        {

            // Stream to which the file to be upload is written
            Stream strm = reqFTP.GetRequestStream();

            // Read from the file stream 2kb at a time
            contentLen = fs.Read(buff, 0, buffLength);

            // Till Stream content ends
            while (contentLen != 0)
            {

                // Write Content from the file stream to the FTP Upload Stream
                strm.Write(buff, 0, contentLen);
                contentLen = fs.Read(buff, 0, buffLength);
            }

            // Close the file stream and the Request Stream
            strm.Close();
            fs.Close();
        }
        catch (Exception ex)
        {
            string ErrMsg = ex.Message;
        }
Execute the code and check the FTP server for the file.

Friday, February 20, 2009

SQL Query to list all Users or Login Names from the database

This will be very useful when you want to know who all are having access to the database.
Execute the below stored procedure,
sp_helpuser 
out put of this stored procedure will be
UserName, GroupName, LoginName, DefDBName, UserID, SID

Wednesday, February 11, 2009

SQL Query to find out a particular field name across all tables in a Database

SELECT name FROM sysobjects WHERE id IN 
(SELECT id FROM syscolumns WHERE name = '<colname>')
another simple query to return all the column names.

select table_name,column_name from information_schema.columns where column_name like '%xyz%'

Thursday, February 5, 2009

How to record voice from microphone using C#

   1:  using System;
   2:  using System.Data;
   3:  using System.Configuration;
   4:  using System.Web;
   5:  using System.Web.Security;
   6:  using System.Web.UI;
   7:  using System.Web.UI.WebControls;
   8:  using System.Web.UI.WebControls.WebParts;
   9:  using System.Web.UI.HtmlControls;
  10:   
  11:  //add below namespaces
  12:  using Microsoft.VisualBasic.Devices;
  13:  using Microsoft.VisualBasic;
  14:  using System.Runtime.InteropServices;
  15:   
  16:  //Add reference to "Microsoft.VisualBasic" which is
       available in .NET tab
  17:   
  18:  public partial class _Default : System.Web.UI.Page 
  19:  {
  20:     protected void Page_Load(object sender, EventArgs e)
  21:      {
  22:   
  23:      }
  24:      //Add the below API. winmm.dll is a module for the Windows Multimedia API, which contains low-level audio and joystick functions
  25: [DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
  26:      
  27:      //The mciSendString function sends a command
           string to an MCI device. 
  28:      //MCI devices are drivers that provide Windows- 
           based programs 
  29:      //device-independent capabilities for controlling
           multimedia hardware and software.
  30:      private static extern int mciSendString
  31:          (string lpstrCommand, string 
      lpstrReturnString, int uReturnLength, int hwndCallback);
  32:   
  33:      protected void  btnRecord_Click(object sender,
           EventArgs e)
  34:  {
  35:      mciSendString("open new Type waveaudio Alias
          TestSoundRecord", "", 0, 0);
  36:      mciSendString("record TestSoundRecord", "", 0, 0);
  37:  }
  38:  protected void  btnStopSave_Click(object sender,
       EventArgs e)
  39:  {
  40:      mciSendString("save TestSoundRecord
           c:\\recorded.wav", "", 0, 0);
  41:      mciSendString("close TestSoundRecord ", "", 0, 0);
  42:      Computer c = new Computer(); 
  43:      c.Audio.Stop();
  44:  }
  45: protected void btnRead_Click(object sender, EventArgs e)
  46:  {
  47:      Computer computer = new Computer(); 
  48:      computer.Audio.Play("C:\\recorded.wav",
           AudioPlayMode.Background);
  49:  }
  50:  }

recorded.wav will be a continuous file. you can create new file each time you click stop and save.

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>