Monday, May 25, 2009

List all the Logical Drive in the Computer : Windows Application, C#

Using System.Management name space we can read the all operating system details and we query System_Win32 database in the following example I am trying to read all the logical drives in the computer and list them in a ListBox and select a drive and you can browse all the files in the drive.

So lets start creating the example, open visual studio and create a Windows Forms Application.

Add one list box and 2 buttons to the Form, you can below screen shot for the design

Design

Now we need to add the reference for the System.Management.dll to project so that we can make use of some class using which we can read all logical drives. Once you add the reference you need to import the System.Management namespace, you can refer below screen shot.

Reference

Now we are ready with Design part and reference part so let start putting code to retrieve drive, for that please double click on Get All Drives button and add following code, in the following code I am call a method GetAllDrives in which I am creating object for ManagementObjectSearcher and searching all the drives using “SELECT Caption, DeviceID FROM Win32_DiskDrive” query, please refer below screen shot for code

GetAllDrives

Now we are done with searching and listing all the drives in the local computer now we will add the code for opening the selected drive in listbox, please refer the below screen shot.

OpenDrive

We are now ready with our code just build, run and test.

output

Hope this helps.

Tags: Read all Logical Drives in Local Computer, C#, Windows Application, .NET

Saturday, May 23, 2009

What’s New In Visual Studio 2010 ASP.NET 4.0

Microsoft has released Visual Studio 2010 and ASP.NET 4.0 beta 1 recently, I felt there are some amazing features which can help developers improve productivity.

Please have look at screen shot of new feature below.

1) New Start page where you have 3 tabs, one is Welcome where we can find welcome note, feedback etc, second tab is project where you can create open projects, third one is Visual Studio tab where you have MSDN, community links

image

2) Target Multiple Versions of .NET: we can build project on different version of .NET versions and also navigation of projects selection is improved.

image

3) Code Snippets: this is one of the best feature I felt in Visual Studio 2010 ASP.NET 4.0, type control name like button and press tab you will button control tag is generated for you similarly when you type script and press tab you will see script tags are created for you.

image

image

4) FormView Improvements, normally when you use FormView Control it will be rendering HTML with Table tag now by default RenderTable = False if you want you can make it True this is still kept for compatible issues.

5) Improved intelligence, now you can filter the intelligence result by pressing Ctrl+Alt+Space

image

image

6) ViewState changes: Now ViewState of a control is by default inherit, that means you can set page level view state and under page all control can inherit its ViewState, if you want to set ViewState to one control separate then you can set for individual control.

This can be done using ViewStateMode = “Inherit” / “Disable” / “Enable”

image

7) ASP.NET provides multiple ways of generating ClientID. You set a way of ClientID in following ways.
Legacy : The ClientID value is generated by concatenating the ID values of each parent naming container with the ID value of the control. In data-binding scenarios where multiple instances of a control are rendered, an incrementing value is inserted in front of the control's ID value. Each segment is separated by an underscore character (_). This algorithm was used in versions of ASP.NET earlier than ASP.NET 4.0.
Static : The ClientID value is set to the value of the ID property. If the control is a naming container, the control is used as the top of the hierarchy of naming containers for any controls that it contains.
Predictable : This algorithm is used for controls that are in data-bound controls. The ClientID value is generated by concatenating the ClientID value of the parent naming container with the ID value of the control. If the control is a data-bound control that generates multiple rows, the value of the data field specified in the ClientIDRowSuffix property is added at the end. For the GridView control, multiple data fields can be specified. If the ClientIDRowSuffix property is blank, a sequential number is added at the end instead of a data-field value. Each segment is separated by an underscore character (_).
Inherit : The control inherits the ClientIDMode setting of its parent control.

image

These are very few of new features I will be posting more very soon.

Hope this helps

Tags: What's New in Visual Studio 2010, ASP.NET 4.0

Friday, May 22, 2009

Read & Write ListBox Item into File: Windows Application

Normally some projects will have very small requirement of storing data, so going to have database and storing small amount of data into database is not suitable answer, you can go for storing data into XML or txt file, in following example I am trying to read and write Listbox items into txt file.
I am using Form_Load method to read data from the txt file and on closing the form I am reading all items in the list box and saving them into a txt file with , separator.
Let start building the example.
Create a windows forms applciation and add a List Box, a Text Box and 2 buttons.
Please refer the screen shot : Design.jpg.

design


Make sure that you have created data.txt in c:\logs folder, here I am using C:\logs path you can create any where in the system and change page in the code.
Once you are ready with design and creating txt file, we will add code to read all the items in the text file in Form_Load and also in Form_Closing we will ad code to store all the items in to text file back please refer the code below in screen shot FomLoadUnload.JPG

FomLoadUnload

Once we have added code to read and write to text file now we will add code to add and remove items in the list box, we are using Button2 for removing the items and Button1 for adding the items, please add Click event of Button 1 and 2 to the code, you can refer below code in screen shot AddRemoveItems.JPG

AddRemoveItems

Now we are ready with code just build, run and test

Output


hope this helps.

Wednesday, May 20, 2009

Using SMOs, Read Tables Script using C#.NET

SQL Server Management Objects (SMOs) are used manipulate database for DBA activities via an application build by you, you can automate some of the DBA tasks by using SMOs in the application.

In this article I am try to explain how we can use SMO to retrieve all the Table listed in Nortwind database and selecting a Table I am display its create script and listing down all the columns in that table.

So lets start create an example how to use SMOs.

Create a Windows Forms application and Add following controls

1) 2 List boxes one is for listing all the tables and one is for listing all the columns in particular table
2) A Text box with multi line mode true and set scrollbars to Vertical

Refer Screen Shot: Design.JPG

Design

Once we have added controls and designed, we need add SMO DLLs for reference so that we can use built-in class.

You need to add following 4 DLL for reference
1) Microsoft.SqlServer.ConnectionInfo
2) Microsoft.SqlServer.Smo
3) Microsoft.SqlServer.SmoEnum
4) Microsoft.SqlServer.SqlEnum

You will find these DLL at following location:
C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\

Once you have added DLL import them for use, please refer screen shot: References.JPG

References

Now we are ready with our design and references part, so let’s start writing code to get all the Tables in the Northwind Database and add to the ListBox1, for this I have to create a Server object which represents a SQL Server in the machine we need to pass the server name to create that object, here I am creating module level variable so that I can use it in other methods also.

Once you have created server object, you need to get the Database object and Database object will have collection of table, read the Table collection and add Table names to ListBox1, please can refer the code below and also screen shot:Form_Load.jpg

Form_Load

Now ListBox1 has all the Tables in the Northwind database on selecting any of the table in ListBox1 we want to show all the columns of that table in Listbox2 and also display Create Script of that table in multi line Text box, for that we need to write code in listBox1_SelectedIndexChanged , we create a Table object using selected Table Name in ListBox1 and read all the columns of that table and display in ListBox2, you can refer below code and also screen shot ListColumns.jpg

ListColumns

Now we are ready with our code just build, run and test.

Output

Hope this helps.

Monday, May 18, 2009

Search Files in a Directory : Windows Application

Following example I am trying to search files in a directory using a criteria, using DirectoryInfo.GetFiles() method we can search files with Criteria and you can use * to find all files those are starting with the some string.

So lets start building example, create a windows forms application and add one label, text box, a button and list box, please refer following screen shot

image

Add following function to Form1 which takes Search Text as file name and Folder Path where files needs to be searched, In following function I am taking FileName as search text and DirectoryName as folder path and searching the files

image

Double click on Search button add following code, following code I am simply taking the search text and selecting folder path and passing to the above function

image

Now we are ready with Code, lets build, run and test

Output:

image

Tag: DirectoryInfo, FileInfo, C#, Windows Application, Search Files

Saturday, May 16, 2009

TechEd 2009 India Experience

I have attended Microsoft TechEd 2009 at Hyderabad HICC from 13 to 15 May 2009; it was great experience and a great chance to learn new technologies.


Day 1 Experience:
It was awesome to Steve Ballmer speaking at TechEd, he mentioned about present and future opportunities in the market and he mentioned that we need to be more productive in the financial situation, do more with less will help us to come out from the present situation. He also mentioned that being innovative will help us go gain more opportunities. Day 1 I also attended Stephen Walther’s presentation what‘s new in ASP.NET 4.0


Day 2 Experience:
Attended Stephen Walther’s Presentation what’s New in ASP.NET AJAX 4.0, I also personally speak to him and had a photograph with him.


Day 3 Experience:
Attended Presentations on Sliver Light and also some of SQL Server 2008 presentation and those were very informative.

Tags: TechEd 2009 India

SQL Server 2008 Developer Training Kit Available

The training kit offers the following benefits:
Learn how to build web applications that exploit the unique features and capabilities of SQL Server 2008.
Provides a comprehensive set of presentations, demos and hands-on labs
Designed for web developers who are already familiar with SQL Server application development.
Easy to download and install and works on free editions of SQL Server 2008 and Visual Studio 2008.

Produced by Southworks SRL, a well-known provider of evangelism content, using both existing and new content custom developed for this training kit.
Software Requirements
The following software is not included with the training kit and must be downloaded and installed separately.

SQL Server 2008 Express with Advanced Services (or higher-level SKU)
Microsoft Visual Web Developer 2008 Express (or higher-level SKU)
AdventureWorks 2008 Sample Databases

The training kit is available at the following URL:
SQL Server 2008 Developer Training Kit



SQL Server 2008, Learn, Training Kit, SQL Server 2008 Learning Videos

Tuesday, May 12, 2009

Export DataGridView into .csv file

Following example I am trying to save the DataGridView's Data into .csv file

Please create a Windows Application and Add a DataGridView and a button on Form1, to fill the data initially please add following code in Form1_Load

image

Double click on the Button and add following code in Button1_Click, in this code we are reading all columns and rows and forming a string and saving in data.csv file

image

Now we are ready with our code, just build, run and test.

Tags: Export DataGridView to .csv file, Windows Forms, C#, .NET

Handle Click Event of Eclipse: Windows Application

Normally we dont have any event for the Drawing objects like circle, eclipse ect., so here I am trying to draw a eclipse using graphics and try to give clicking effect and handing that event.

Declare the event handler and deligate to handle the events

image

Initialise the Click Event for eclipse we are drawing in Form_Load

image

Draw eclipse in Form paint method

image

To give clicking effect we need to draw a similar eclipse when you 
press the mouse, also check the bounds where mouse is being clicked, please add following code in Form1_MouseDown

image

And add following code in Form1_MouseUp

image

Following event will be called when you click the eclipse, so please add following code block

image

Now we are ready our code just build, run and test.

Tags: Drawing in C#, Eclipse, Handling Events

Saturday, May 9, 2009

Getting the Selected Value of Combo Box in DataGridView

In following example I am try to get the Selected value of Combo Box which is in DataGridView.
Create a Windows Applicaiton and Add a DataGridView in the Form1

We need to initialise DataGridViewEditingControlShowingEventHandler of DataGridView to handle its control events, so please use follwoing code in Forms Constructor

image

In the form load we will fetch all the data and assign to DataGridView

image

Now catch the control edit event in the DataGridView and assign the SelectIndexChanged event to each Combo Box in DataGridView

image

Add Follwoing Combo Box's SelectedIndexChanged which we assigned to all the combo boxes in DataGridView

image

Now we are ready with our code lets build, run and test.

Output:

image

Tags: Getting the Selected Value of Combo Box in DataGridView, DataGridView

Wednesday, May 6, 2009

Reading Outlook Contacts in VB.NET

In this article I am trying to read the Outlook contact into a Combo Box and selecting a contact I am displaying his/ her details in below Label controls, so lets start building example.

Create a Windows Forms Application and Add Label and Combo Box and change the lable text to Select Contact.

To use the Outlook object in our project we need include a dll from the add references, now add a reference and select "Microsoft.Office.Interop.Outlook" dll from the list.

After adding the dll, now we will import the name space for that use following import

To access Outlook we need to create a object for Outlook via its interface and to get current session we need a NameSpace object to create these object use following code

Imports

Now in the Form Load we will initialise the objects and fill the combo box with contact names, for that in the Form_Load use following code

FormLoad

Once we get the list of contacts in the Combo box use will select a Contact on selecting a contact we will display his or her details in the labels we put on the form for that we need to add following coding in the ComboBox_SelectedIndexChanged event, basically we are searching through all contacts and get the selected contact and display his or her details

We need to clear the object memory we used in the project in Form_Disposed event

ComboBoxSelect

Now we are ready with our code just build, run and test

Output

Tags: Reading Outlook Contacts using VB.NET

Tuesday, May 5, 2009

Reading ini File using VB.NET

Following fucntion reads INI file by Section and Keys and get the value of the Section. Following function uses GetPrivateProfileStringW API function to read the INI file

Private Declare Unicode Function GetPrivateProfileString Lib "kernel32" _
    Alias "GetPrivateProfileStringW" (ByVal lpApplicationName As String, _
    ByVal lpKeyName As String, ByVal lpDefault As String, _
    ByVal lpReturnedString As String, ByVal nSize As Int32, _
    ByVal lpFileName As String) As Int32

Public Overloads Sub ReadINIFile(ByVal INIPath As String, _
ByVal SectionName As String, ByVal KeyName As String(), _
ByRef KeyValue As String())
    Dim Length As Integer
    Dim strData As String
    strData = Space$(1024)
    For i As Integer = 1 To KeyName.Length - 1
        If KeyName(i) <> "" Then
            'This will read the ini file using Section Name and Key
            Length = GetPrivateProfileString(SectionName, KeyName(i), KeyValue(i), _
            strData, strData.Length, LTrim(RTrim((INIPath))))
            If Length > 0 Then
                KeyValue(i) = strData.Substring(0, Length)
            Else
                KeyValue(i) = ""
            End If
        End If
    Next
End Sub


Testing above function
Create a Sample INI file using below text in C:\Logs\test.ini
[Sample Section 1]
SampleKey1=SAMPLEVALUE1
SampleKey2=SAMPLEVALUE2
[Sample Section 2]
SampleKey3=SAMPLEVALUE3
SampleKey4=SAMPLEVALUE4

And use following code
Dim KeyName(2) As String
Dim KeyValues(2) As String
KeyName(1) = "ServerName"
KeyName(2) = "DBName"
ReadINIFile("C:\Logs\test.ini", "TEST Server", KeyName, KeyValues)
MessageBox.Show(KeyValues(1) & " " & KeyValues(2))

Hope this helps

Monday, May 4, 2009

Validate All TextBoxes Using JavaScript

Using following function you can find out all text boxes in the page are entered a value or not, no need to manually write each text box name to validate.

<script language="javascript" type="text/javascript">
function validate() {
    // Get all input controls
    var arrTextBox = document.getElementsByTagName("input");
    var retValue = 1;
    // Loop through all controls
    for(i=0;i<arrTextBox.length;i++)
    {
        // Check whether control is textbox and has a value
        if (arrTextBox[i].type == "text" && arrTextBox[i].value == "") {
            retValue = 0;
        }
    }
    //based on the validation return the value
    if (retValue == 0) {
        alert("Validation Failed");
        return false;
    }
    else {
        alert("Validation Success");
        return true;
    }
}
<script>


Tags : Validate JavaScript, All TextBoxes, document.getElementByTagName

Saturday, May 2, 2009

Microsoft Tech-Ed 2009 At Hyderabad

 

Microsoft’s Tech-Ed is going to happen in Hyderabad this year, you can here latest technology news from Microsoft speakers who are actually involved in developing that particular technology.

Tech-Ed is one place where you can make yourself ready for next generation technology, today's economic scenario you need to be ahead of others so this Tech-Ed will help you to stay ahead of others.

You can know about the event at  Tech-Ed 2009

You can see what is the agenda at Day 1 Day 2 Day 3

You can register for the event at Register

Tags: Tech-Ed 2009, ASP.NET