Tuesday, June 29, 2010

How to: List all files in a Drive using C#

The code below shows how to use the System.IO.DirectoryInfo function to retreive all the files in the specified location, it also show how to get the extension and other information. Here in this code sample checking for DriveType CD Rom and files in that CD Drive.

Here is a sample code snippet for doing this. Have fun!

System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
string strDriverLetter = "";
bool boolDriveIsReady = false;
foreach (System.IO.DriveInfo drive in drives)
{
    if (drive.DriveType == System.IO.DriveType.CDRom)
    {
        Console.WriteLine("Drive Name: " + drive.Name);
        strDriverLetter = drive.Name;
        boolDriveIsReady = drive.IsReady;
        break;
    }
}
if (boolDriveIsReady == true)
{
    boolDriveIsReady = false;
    DirectoryInfo di = new DirectoryInfo(strDriverLetter);
    FileInfo[] exFiles = di.GetFiles("*.exe");
    foreach (FileInfo fi in exFiles)
    {
        Console.WriteLine("File Name: " + fi.Name + "Extension "+ fi.Extension);
        if (fi.Name.ToUpper().Equals("LAUNCH.EXE"))
        {                        
            boolDriveIsReady = true;
            break;
        }
    }
}

Friday, June 25, 2010

How to: Running Windows service at a specified time period.

I am writing an Notification service, for that i need to send reminders based on a time period. This is how I did. Here i am Configuring notification time and service interval time in app.config. For me, notification time is the time when to execute the logic and service interval time will tell the timer when to stop and start. If we want we can make this data driven as well. I have added a timer control. Here is the sample code snippet here for this.

public partial class Service1 : ServiceBase
{
    private System.Timers.Timer timer = null;
    private NotificationClass nc = new NotificationClass();
    private string notificationTime = ConfigurationManager.AppSettings["notificationTime"];
    // Default time to start and stop the timer.
    private string serviceInterval = ConfigurationManager.AppSettings["serviceInterval"];
    public Service1()
    {
        InitializeComponent();
        timer = new System.Timers.Timer(Convert.ToDouble(serviceInterval));
        timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    }
    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        // Compare this notification time with your time...
        if (DateTime.Now.ToShortTimeString() == notificationTime)
        {
            this.timer.Enabled = false;
            this.timer.AutoReset = false;
            // Do the logic
            nc.BirthdayReminder();
            this.timer.Start();
        }
    }
    protected override void OnStart(string[] args)
    {
        // TODO: Add code here to start your service.
        timer.AutoReset = true;
        timer.Enabled = true;
        timer.Start();
    }
    protected override void OnStop()
    {
        // TODO: Add code here to perform any tear-down necessary to stop your service.
        timer.AutoReset = false;
        timer.Enabled = false;
    }
}

Thursday, June 24, 2010

Dynamically Loading Master Pages

Master Pages give you the ability to define a master page layout and look that is used throughout a site to give a consistent look & feel to all pages. Any updates or changes to the look & feel of the site is done in only one place - the Master Page. Something that might be useful is the ability to dynamically load a master page at runtime, for example based on user preferences or to implement a simple skinning ability for a site framework that might host multiple different sites.

The master page can be selected for a page easily at design-time. But assigning a master page at run-time can only be done in the OnPreInit event since the rendering of the page with the master page occurs prior to the Init event. However, in the case where you want to load the master page dynamically, for example from a database entry based on a user's preference or something, you don't want to add code to the OnPreInit event on every page in the site. It is easy enough to add that code to a base page class that you can inherit from for you pages in the site.

public class DynamicPage : System.Web.UI.Page
{
protected override void OnPreInit(EventArgs e)
{
string masterfile = getMasterPageFromDatabase();
if (!masterfile.Equals(string.Empty))
{
base.MasterPageFile = masterfile;
}
base.OnPreInit(e);
}
}


Now, all you have to do is inherit from that class for all the pages in the site. You can just add it into the web.config and all pages will automatically inherit from it. Doesn't matter if it is a page in the project that you have already, or a new page you add later, it will know to inherit from the DynamicPage class. You add the following to the web.config:



<system.web>
<pages pageBaseType="DynamicPage" />
<!-- ...rest of system.web items... -->
</system.web>

Wednesday, June 23, 2010

How to: Adding Uninstall start menu item to your .NET deployment project

Its pretty simple. Follow the steps to achieve this.

  • Add the following code snippet  to your projects main method before InitializeComponent();
    string[] arguments = Environment.GetCommandLineArgs();
    foreach (string argument in arguments)
    {
       string[] parameters = argument.Split('=');
       if (parameters[0].ToLower() == "/u")
       {
         string productCode = parameters[1];
         string path = Environment.GetFolderPath(Environment.SpecialFolder.System);
         Process proc = new Process();
         proc.StartInfo.FileName = string.Concat(path, "\\msiexec.exe");
         proc.StartInfo.Arguments = string.Concat(" /i ", productCode);
         proc.Start();
       }
    }



    • Now go to your deployment project and go to the file system editor and right click on File System on Target Machine and Add Special Folder with name User's Programs Menu.


    • Add an additional shortcut to your primary output project and name it Uninstall.


    • Right Click  Shortcut to Set the Arguments property to /u=[ProductCode].


    • Now Build your Deployment setup project. Your are ready to go.


    Deployment project will replace [ProductCode] in the Arguments property with the actual installer project's ProductCode GUID value. Your program will see the /u={Actual ProductCode} argument and pass it to msiexec.exe. If you want the product to remove only, replace the "/i " with "/x ".

    Tuesday, June 22, 2010

    How to: Check whether SQL login exists?

    Try some thing like this.

    DECLARE @SqlStatement NVARCHAR(4000)
    DECLARE @loginName VARCHAR (100)
    SELECT @loginName = 'nagasai'
    IF NOT EXISTS (SELECT loginname FROM master.dbo.syslogins WHERE NAME = @loginName)
    BEGIN
    SET @SqlStatement = 'CREATE LOGIN [' + @loginName + '] WITH PASSWORD=N''angel83'',DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]'
    EXEC sp_executesql @SqlStatement
    END
    ELSE
    BEGIN
    PRINT 'login name ' + @loginName + ' already exists'
    END