Friday, December 26, 2008

How to List Installed Softwares on a machine using VBScript?

Here is a handy code to list down all the installed softwares on a machine with their installation information:

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.CreateTextFile("D:\Test\softwares.tsv", True)

strComputer = "."
Set objWMIService = GetObject("winmgmts:"_
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colSoftware = objWMIService.ExecQuery("Select * from Win32_Product")

objTextFile.WriteLine "Caption" & vbtab & _
"Description" & vbtab & "Identifying Number" & vbtab & _
"Install Date" & vbtab & "Install Location" & vbtab & _
"Install State" & vbtab & "Name" & vbtab & _
"Package Cache" & vbtab & "SKU Number" & vbtab & "Vendor" & vbtab _
& "Version"

For Each ObjSoftware in colSoftware
objTextFile.WriteLine objSoftware.Caption & vbtab & _
objSoftware.Description & vbtab & _
objSoftware.IdentifyingNumber & vbtab & _
objSoftware.InstallDate2 & vbtab & _
objSoftware.InstallLocation & vbtab & _
objSoftware.InstallState & vbtab & _
objSoftware.Name & vbtab & _
objSoftware.PackageCache & vbtab & _
objSoftware.SKUNumber & vbtab & _
objSoftware.Vendor & vbtab & _
objSoftware.Version
Next

objTextFile.Close

Hope this helps :)

StyleSheet for Floating Div Tag in HTML

Here is the StyleSheet for displaying a floating DIV tag in HTML. This is often required to display status, Tooltips etc.

DIV.floatingDiv
{
border-right: #0067a2 3px solid;
padding-right: 3px;
border-top: #0067a2 3px solid;
padding-left: 3px;
z-index: 1;
left: 18%;
float: none;
visibility: visible;
padding-bottom: 3px;
margin: 2px;
border-left: #0067a2 3px solid;
padding-top: 3px;
border-bottom: #0067a2 3px solid;
position: absolute;
top: 27%;
background-color: #6095b3;
width: 600px;
height: 220px;
}

Include the above class in your stylesheet and use ash shown below:

<div class="floatingDiv" id="Test_1"> </div>

Hope this helps you!

How to dynamically add Update Panel to asp.net page?

Here is a simple code to dynamically add update panel to asp.net page:



UpdatePanel upannel = new UpdatePanel();
upannel.ChildrenAsTriggers = true;
upannel.UpdateMode = UpdatePanelUpdateMode.Conditional;
upannel.ID = "updatePannel_1";
upannel.ContentTemplateContainer.Controls.Add("Control_TO_Add_In_Update_Panel");
Page.Form.Controls.Add(upannel);

Hope this helps you :)

How to parse mails in Microsoft Outlook using C#?

We often get hundreds of mails in our Outlook Inbox and want to do some processing with these mails. This scenario arises mainly with the customer support people who wanted to act depending on the mail subject line. Here is a simple code to parse the Microsoft Outlook Inbox:


static void ReadMail()
{
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.MailItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;

try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null, null, false, false);

inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
// subFolder = inboxFolder.Folders["Inbox"]; //folder.Folders[1]; also works
Console.WriteLine("Folder Name: {0}, EntryId: {1}", inboxFolder.Name, inboxFolder.EntryID);
Console.WriteLine("Num Items: {0}", inboxFolder.Items.Count.ToString());

System.IO.StreamWriter strm = new System.IO.StreamWriter(@"d:\Test\Inbox.txt");
for (int counter = 1; counter <= inboxFolder.Items.Count; counter++)
{
item = (Microsoft.Office.Interop.Outlook.MailItem)inboxFolder.Items[counter];
Console.WriteLine("Item: {0}", counter.ToString());
Console.WriteLine("Subject: {0}", item.Subject);
Console.WriteLine("Sent: {0} {1}", item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString());
Console.WriteLine("Sendername: {0}", item.SenderName);
strm.WriteLine(counter.ToString() + "," + item.Subject + "," + item.SentOn.ToShortDateString() + "," + item.SenderName);
}
strm.Close();
}
catch (System.Runtime.InteropServices.COMException comException)
{
Console.WriteLine(comException.ToString());
}
finally
{
ns = null;
app = null;
inboxFolder = null;
}

}
Hope this helps you :)

How to determine the control that caused PostBack in an ASP.NET Page?

I have faced this issue a lot of time, where I want to know what control caused the asp.net page to postback. If you study carefully, you will find that ALL the server side asp.net controls are rendered as simple HTML to the client browser. When a postback occurs some event at the server side is triggered such as Button_Click, SelectedIndexChanged, Page_Load etc. Now let's go in some more details.. The rendered asp.net page is nothing but a plain HTML. Now when the page causes a postback, the asp.net engine needs to know what has cused the postback. Depending on this, the engine will trigger particular event on the server side. How does the asp.net engine know what control has caused postback???

If you view the source of the rendered asp.net page you would find some hidden text fields such as __EVENTTARGET, __EVENTARGUMENT, __VIEWSTATE. These fields act as information storage for the HTML page. They convey the postback infromation to the asp.net engine, which can then trigger appropriate event.

When you change the index of dropdown control or any other control, a javascript function name "__doPostBack" is invoked. This function is responsible for saving the control information along with control arguments i.e. called as EventTarget and EventArguments. The __EVENTTARGET field stores the name of the control that caused postback. Hence by simply querying this hidden field we can get the name of the control that caused postback as shown below:


string controlName = page.Request.Params.Get("__EVENTTARGET");
if (controlName != null && controlName != string.Empty)
{
return this.Page.FindControl(controlName );
}

This will work absolutely fine with TextBox, DropDown, LinkButton control, but it won't work with Button control. Since the Button control is rendered as <input type="Submit" />. The __doPostBack function is not called in this case, hence the hidden field __EVENTTARGET is not set. Now in such case how to find the control name that caused postback?

An IMPORTANT point to note is a Submit button i.e. <input type="Submit" /> is not added to the Form until it causes a postback. This means that if their are 3 buttons on the page names B1, B2 and B3. And B2 caused a postback then B1 and B3 will not be added to the form. Thus if the Button causes a postback we can definitely search it in page.Request.Form as shown below:

Control control = null;
foreach (string formControl in page.Request.Form)
{
Control ctrl = page.FindControl(formControl );
if (ctrl is System.Web.UI.WebControls.Button)
{
control = ctrl;
break;
}
}

Thus the final method to get the postback control will look like:


 public Control GetPostBackControl(Page CurrentPage)
{
Control control = null;
string controlName = page.Request.Params.Get("__EVENTTARGET");
if (controlName != null && controlName != string.Empty)
{
control this.Page.FindControl(controlName );
}
else
{

foreach (string formControl in page.Request.Form)
{
Control ctrl = page.FindControl(formControl );
if (ctrl is System.Web.UI.WebControls.Button)
{
control = ctrl;
break;
}
}
}
return control;
}

In this way we can find out the control that caused postback in asp.net.

Hope this helps :)

Agile/Scrum Methodology for Software Projects!

Here is a classic presentation from Ken Schwaber on Agile/Scrum methodology for software project development.



Click here to view the presentation on youtube.

Download Month Calendar User Control!

We get many advance Calendar controls on the internet and in controls library, but I was struggling to find the Month Calendar control. A control that will only display months in a year with a hyperlink(event). Finally here is one that I have developed.

Usage:

Code in ASPX Page:

<%@ Register Src="~/UserControls/MonthSelectControl.ascx" TagName="MonthSelectControl" TagPrefix="uc1" %>

<div>

<uc1:MonthSelectControl ID="TestControl" runat="server" />

</div>

Code in .aspx.cs (CodeBehind) Class:

In Page_Load event register the Month Calendar control DateChanged event as shown below:

TestControl.DateChanged += new EventHandler(Control_DateChanged);

Code for the DateChanged Event:

void DateChanged(object sender, EventArgs e)

{

MonthCalendar.
MonthCalendarControlEventArgs arg = (MonthCalendar.MonthCalendarControlEventArgs) e;

string month = arg.Month;

string year = arg.Year;

}

Download the control here.

Your comments are welcome :)

Why I cannot access classes in .aspx codebehind from the classes in app_code in asp.net?

This is a fantastic problem that I faced. I was having a user control in my asp.net application as MSDD.ascx. I wanted to dynamically display this user control from the code written in the Dynamic.cs file in app_code folder of my applicaiton. But at this movement, I was unable to access the MSDD class written in codebehind file from my class in app_code. How can we proceed now???

Solution:

The best solution is to write an Interface. Place this interface in the app_code folder of you application. The aspx codebehind class should implment this particular interface. Now via interface you can access the codebehind class from you class in app_code folder. See the scenario below:

I have following files:

ASPX: A user control/class named MSDD.

app_code: A call named Dynamic, in which I want to access the above user control class MSDD.

Now write an interface IMSDD and make the codebehind class MSDD to implement this IMSDD interface. So you MSDD class will look like:

public class MSDD : IMSDD

{

// Code here...

}

And your Dynamic class which uses the Interface will look like:

public class Dynamic

{

IMSDDctrl = (IMSDD) Page.LoadControl("../MSDD.ascx");

// Now using this interface you can invoke any method/property of the MSDD class this is exposed via the interface.

ctrl.Invoke();

}


Hope this helps you...

How to Create a Process on Remote Computer using VBScript WMI?

Here is a sample code to start the notepad.exe on a remote computer. This code works well with all the Windows operating system except for the advance OS like Windows XP the notepad opens in an invisible mode. In the code below you need to replace "server" with the name of the computer where you want to start the process.

strComputer = "server"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
Error = objWMIService.Create("notepad.exe", null, null, intProcessID)
If Error = 0 Then
Wscript.Echo "Notepad was started with a process ID of " & intProcessID & "."
Else
Wscript.Echo "Notepad could not be started due to error" & Error & "."
End If

Hope this helps!

How to prevent sending an email without subject from Microsoft Outlook?

We often feel horrible when we send email messages to our bosses without any subject line. Here is a simple way to avoid such mistakes...

Steps: -
1. Open your Outlook,
2. Press Alt+F11. This opens the Visual Basic Editor and then Press Ctrl+R which in turn open Project-Project 1 (left side)
3. On the Left Pane, one can see "Microsoft Outlook Objects" or "Project1", expand this. Now one can see the "ThisOutLookSession".
4. Double click on "ThisOutLookSession". It will open up a Code Pane on the right hand side.
5. Copy and Paste the following code in the right pane (Code Pane) and save it

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim strSubject As String
strSubject = Item.Subject
If Len(Trim(strSubject)) = 0 Then
Prompt$ = "Subject is Empty. Are you sure you want to send the Mail?"
If MsgBox(Prompt$, vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Check for Subject") = vbNo Then
Cancel = True
End If
End If
End Sub
6. Save the Project and exit.

Now whenever you try to send a mail without subject, a pop-up is raised to remind you of the blank subject.

How to Bulk Insert records to T-SQL Table from a DataTable in C#?

This article will tell you two method of inserting bulk records into a T-SQL table from a DataTable in C#:

1. Bulk insert using the SqlBulkCopy class

2. Bulk insert by passing XML data table to the stored procedure

The first method is used ONLY to insert the data to the database and is simple as compared to the second method. The second method can be used to do some complex processing while inserting/updating the data in the SQL table.

In the first method we will make use of the SqlBulkCopy class provided in .NET. Following code illustrates the use of the SqlBulkCopy class for bulk insert:

#region references
using System.Data;
using System.Data.SqlClient;
#endregion references

namespace SQLBulkInsert
{
class Program
{
static void Main(string[] args)
{
// T-SQL Connection
string connection = "Data source=.; Initial Catalog= MyDatabase; SSPI=true";
DataTable dtData = new DataTable();

// Get the data into the DataTable
//dtData = GetData(...);

// Create an object of SqlBulkCopy
SqlBulkCopy objSBC = new SqlBulkCopy(connection);
// Specify the destination table
objSBC.DestinationTableName = "Table_Name";
// Write the data to the SQL Server
objSBC.WriteToServer(dtData);
}
}
}


You can find the implementation of the second method in my article on CodeProject.com

Hope this helps you!

How to convert int Month to String Month Name in C#?

Often we get month as integer from external source and want to display it as "Oct" or "October" i.e. string. Following is a code to convert the int month to string month :)

 
/// <summary>
/// Converts the given month int to month name
/// </summary>
/// <param name="month">month int </param>
/// <param name="abbrev">return abbreviated or not</param>
/// <returns>Short or long month name as string </returns>
private static string GetMonthName(int month, bool abbrev)
{
DateTime date = new DateTime(2000, month, 1);
if (abbrev) return date.ToString("MMM");
return date.ToString("MMMM");
}
Hope this helps :)

How to assign a static IP address using VBScript?

This type of scripts are always in demand by the network proffessionals. Here is a handy script that assigns a static IP address to a machine:

strComputer = "."
Set objWMIService = GetObject ("winmgmts:" & "{impersonationLevel = impersonate}!\\" & strComputer & "\root\cimv2")
Set colNetAdapters = objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE")
strIPAddress = Array("192.168.1.202")
strSubnetMask= Array("255.255.255.0")
strGateway = Array("192.168.1.100")
strGatewayMetric = Array(1)
For Each objNetAdapter in colNetAdapters
errorEnable = objNetAdapter.EnableStatic(strIPAddress,strSubnetMask)
errorGateway= objNetAdapter.SetGateways(strGateway, strGatewayMetric)
If errorEnable = 0 Then
WScript.Echo "The IP Address has been changed successfully!!"
Else
WScript.Echo "Their was an error, the IP Address could not be changed!"
End If
Next
Hope this helps :)

How to Start, Stop and Pause a Web Server on IIS using VBScript?

Here is a VBScript code to start, stop and pause a web server running in IIS:

Start a Web Server

strComp = "LocalHost"
Set objIIS = GetObject("IIS://" & strComp & "/W3SVC/2142295254")
objIIS.Start

Stop a Web Server

strComp = "LocalHost"
Set objIIS = GetObject("IIS://" & strComp & "/W3SVC/2142295254")
objIIS.Stop


Pause a Web Server

strComp = "LocalHost"
Set objIIS = GetObject("IIS://" & strComp & "/W3SVC/2142295254")
objIIS.Pause

Hope this helps :)