24 December 2013

Lock the computer Programmatically using C#

Hi Friends,

Let see how to lock the computer Programmatically using the C# code.  We have to use the function LockWorkStation written inside the user32.dll.  We have to first import the dll in our C# class and we have to declare an extern method LockWorkStation which is already in user32.dll.

Finally We just need to call the method LockWorkStation to lock the system.  We can call this method on button click event or anywhere as per the requirements.

You have to import the user32.dll and declare LockWorkStation method signature as follows.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

public partial class Form1 : Form
{
    [DllImport("user32.dll", SetLastError = true)]
    private static extern void LockWorkStation();    
        
    public Form1()
    {      
      InitializeComponent();      

      // calling here will lock the computer once the form loaded.      
        bool result = LockWorkStation();

        if( result == false )
        {
           // An error occured
           throw new Win32Exception( Marshal.GetLastWin32Error() );
        }
         
      /*
       * we can call this method on button click or anywhere else
       * as per the requirement.
       */
    }
}

Thanks for reading..!!
Happy Code Sharing..!! :)

Placeholder text on TextBox in C#

Hi Friends,

To set the place holder text in html we just use the placeholder attribute of that input type="text".

<input type="Text" placeholder="Username" />

<input type="Password" placeholder="Password" />


it looks like -



To do the same thing in C# window form, we do not have such attribute of properties on TextBox class in C#.
But we can accomplish this task by importing the user32.dll.  We have to use the following syntax to set the placeholder text.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

public partial class Form1 : Form
{
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern Int32
            SendMessage(
                            IntPtr hWnd, 
                            int msg, 
                            int wParam,
                            [MarshalAs(UnmanagedType.LPWStr)]string lParam
                        );
    
    private const int EM_SETCUEBANNER = 0x1501;
        
    public Form1()
    {      
      InitializeComponent();      
   
   // set the placeholder text to the user name and password field.
      SendMessage(txtUser.Handle, EM_SETCUEBANNER, 0, "Username");
      SendMessage(txtPassword.Handle, EM_SETCUEBANNER, 0, "Password");
    }
}  

And you will get the same required result.


Thanks for Reading..!!

Happy Knowledge sharing..!! :)

20 December 2013

Store the Object in XML File, and Get Back - C#

Hi Friends,

Let see how can we store the object in XML file and get back the object whenever needed.  Sometime we need to store the object or the collection of the objects of any class (Remember - Collection of the object is also a Object - list, array or whatever) anywhere and later point of time we required to get those object back.  You can do this by using serialization and deserialization.

You have to include the following class from in you project and call the Save and GetFromXML method to store and get the object back.

using System;
using System.IO;
using System.Xml.Serialization;
using System.Xml;

class SerializeDeserialize
{
  #region store the object in xml file at specify path
  public static void Save<T>(T obj, string path)
  {
    try
    {
      using (StreamWriter writer = new StreamWriter(path))
      {          
        XmlSerializer xs = new XmlSerializer(obj.GetType(),
          new XmlRootAttribute("RootNode"));
        XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
        xsn.Add("", "");          

        xs.Serialize(writer, obj, xsn);
      }
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.GetBaseException());
      return;
    }
  }
  #endregion



  #region get the object back from the xml file specified as path string
  public static T[] GetFromXML<T>(string Path)
  {
    T[] result = null;

    XmlRootAttribute xRoot = new XmlRootAttribute();
    xRoot.ElementName = "RootNode";
    xRoot.Namespace = "";
    xRoot.IsNullable = true;


    XmlSerializer ser = new XmlSerializer(typeof(T[]), xRoot);
      
    using (FileStream fs = new FileStream(Path, FileMode.Open))
    {
      XmlReader reader = XmlReader.Create(fs);
      try
      {
        result = (T[])ser.Deserialize(reader);
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.GetBaseException());
      }
    }

    return result;
  }
  #endregion
}
To store the object you just need to call the corresponding method, use the below syntax to call these method.
   ..
   ..
   ..
   List<MyClass> list = new List<MyClass>();
   list.Add(new MyClass("name1", "desc1", "path1"));  
   list.Add(new MyClass("name2", "desc2", "path2"));
   list.Add(new MyClass("name3", "desc3", "path3"));
   ..
   ..
   ..
   //Save the list created in xml file.
   SerializeDeserialize.Save<List<MyClass>>(list, @"C:\abc.xml");

   // get the array of the MyClass objects store in "abc.xml" file.
   MyClass[] ob = SerializeDeserialize.GetFromXML<MyClass>(@"C:\abc.xml");

   // Element count
   Console.WriteLine(ob.Length);

   // if element found in xml file print the properties of first object in ob
   if(ob.Length > 0 )
   {
     Console.WriteLine(ob[0].Name);
     Console.WriteLine(ob[0].Description);
     Console.WriteLine(ob[0].Path);
   }
When you call Save it will create the abc.xml file in C:\ driver.  The content in xml file will be-
<?xml version="1.0" encoding="utf-8"?>
<RootNode>
  <MyClass>
    <Name>name1</Name>
    <Description>desc1</Description>
    <Path>path1</Path>
  </MyClass>
  <MyClass>
    <Name>name2</Name>
    <Description>desc2</Description>
    <Path>path2</Path>
  </MyClass>
  <MyClass>
    <Name>name3</Name>
    <Description>desc3</Description>
    <Path>path3</Path>
  </MyClass>
</RootNode>


Thanks..!!
Happy Sharing.. !! :)

Add the Row Programmatically to the DataGridView

Hi Friends,

Lets see how to add the row to the DataGridView if its already bind to DataSource. Remember if DataGridView is already bound with any DataSource, You can not directly add DataGridViewRow or DataRow to the DataGridView.

If you have bound the DataTable as DataSource with DataGridView, then you just need to add the row in DataTable it will automatically reflect in DataGridView. But sometime we face the problem we have List<object> of the object and we have DataGridView. Of course we can bind the List with DataGridView(Refer this link), but we can not add the row the DataGridView after binding the DataSource.  The best approach to overcome this problem is add the Object/Row in DataSource, your List <object> or DataTable.

1.  If you have bound the DataGridView with List<object>
     list = new List<MyClass>();
     list.Add(new MyClass("name1", "desc1", "path1"));  
     list.Add(new MyClass("name2", "desc2", "path2"));
     list.Add(new MyClass("name3", "desc3", "path3"));


     var bindingList = new BindingList<MyClass>(list);
     BindingSource bindingSource = new BindingSource(bindingList, null);
     dataGridView1.DataSource = bindingSource;
Now to add the row in grid you just need to add the object in the list and it will automatically reflect in DataGridView.
    ..
    ..
    // create the blank object
    MyClass obj = new MyClass("", "", "");

    //create the 5 blank lines in Grid
    for(int i=0; i <5; i++)
       list.Add(obj);
    ..
    ..

2.  If you have bound the DataGridView with the DataTable. You just need to add the row in DataTable as below-
    // Create new DataRow
    DataRow newCustomersRow = dt.NewRow();
 
    // add the column same as specified in DataTable and set the value
    newCustomersRow["Name"] = "";
    newCustomersRow["Description"] = "";
    newCustomersRow["Path"] = "";

    // add the row in DataTable which is bound as DataSource for Grid
    dt.Rows.Add(newCustomersRow);

Thanks..!!
Happy Knowledge sharing..!! :)

19 December 2013

Convert List<object> to the DataTable in C#

Hi Friends,

Lets see how to convert the List to the DataTable. Sometime we encounter such a situation that we require to convert the List of the object to the DataTable.

See the below diagram can tell you the correct requirement.

class MyLocation
{        
    private string _name;
    private string _desc;
    private string _path;
        
    public string Name { get { return _name; } set { _name = value; } }
    public string Description { get { return _desc; } set { _desc = value; } }
    public string Path { get { return _path; } set { _path = value; } }

    public MyLocation(string Name, string Description, string Path)
    {
        this.Name = Name;
        this.Description = Description;
        this.Path = Path;
    }
}

We have the list of the object as follow
    ..
    ..
    // create the list for the "MyLocation" Objects
    List<MyLocation> list = new List<MyLocation>();

    // add the "MyLocation" Objects to the list
    list.Add(new MyLocation("name1", "desc1", "path1"));  
    list.Add(new MyLocation("name2", "desc2", "path2"));
    list.Add(new MyLocation("name3", "desc3", "path3"));
    ..
    ..

Now I want to convert this list to the DataTable as
NameDescriptionPath
name1desc1path1
name2desc2path2
name3desc3path3
You have to implement the code which will get the object one by one from the list and get all the properties of the object and create the DataTable according to that.  And then add all the properties of the object as a DataRow in DataTable and then return that DataTable.

I have done this part for you, you just need to copy-paste the following code and use it.
public DataTable ConvertToDataTable<T>(List<T> data)
{
    // get the properties of the Object inside the List
    PropertyDescriptorCollection properties =
       TypeDescriptor.GetProperties(typeof(T));

    // create the DataTable
    DataTable table = new DataTable();

    // read the properties one-by-one and add the Name as 
    // column in the DataTable table
    foreach (PropertyDescriptor prop in properties)
    {
      table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
    }

    // now read the Object in the list one-by-one and
    // add the properties of object in DataRow,
    //and finally add DataRow row in DataTable table
    foreach (T item in data)
    {
      DataRow row = table.NewRow();
      foreach (PropertyDescriptor prop in properties)
      {
        row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
      }
      table.Rows.Add(row);
    }

    // finally return the DataTable
    return table;

}
Thats it..!!!
Happy Code Sharing.. :)

Bind the "List" as DataSource to the DataGridView

Hi Friends,

Sometime we encounter the problem when we have List<MyClass> list and we want to bind it with DataGrid or DataGridView.  Of course we can bind it by using the following code.

Lets see how we can bind the List to the DataGridView

            // create the list for the objects of "MyClass"
            List<MyClass> list = new List<MyClass>();
            ..
            ..// add the object of "MyClass" into the "list".
            ..
            // create the binding list from the "List list" object
            var bindingList = new BindingList<MyClass>(list);

            // create the BindginSource from the "bindingList" variable
            BindingSource bindingSource = new BindingSource(bindingList, null);

            // bind the DataSource to the DataGridView object "dataGridView1"
            dataGridView1.DataSource = bindingSource;

The above code will work perfectly and you can bind the List in this way as DataSouce for the DataGridView.

Happy Knowledge Sharing.. :)

18 December 2013

Detect the Removable drive in C#

Hi Friends,

Let see how can you get the USB drive information using the C# code.  I mean the code which shows us if the Removable drive is inserted in computer.

If you want to trigger some program, you have to implement this code in window service and check for the condition in loop.

For the console program the below code shows you how can you get the removable drive and get the other information related to that drive.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DetectRemovableDrive
{
  class Program
  {
    static void Main(string[] args)
    {
      // for all the ready drives
      IEnumerable a= DriveInfo.GetDrives().Where(d => d.IsReady);

      // if you want to get only Removable drives use the below two lines..
      //IEnumerable a = DriveInfo.GetDrives().Where(d => d.IsReady 
      //&& d.DriveType == System.IO.DriveType.Removable);

      Console.WriteLine("Total {0} ready drives found.!!\n", a.Count());

      foreach(DriveInfo temp in a)
      {
        Console.WriteLine("\tDrive {0} has the label \"{1}\"",
                  temp.Name,
                  temp.VolumeLabel==""?"Local Disk":temp.VolumeLabel);

        Console.WriteLine("\t\tTotal size {0} bytes, free is {1} bytes.\n",
                  temp.TotalSize,
                  temp.TotalFreeSpace);
      }
      Console.ReadKey();
    }
  }
}
Create a console program the paste the following code in Program.cs file. And compile the code.

You will see the code like below

Total 5 ready drives found.!!

 Drive C:\ has the label "Local Disk"
  Total size 104752738304 bytes, free is 27952164864 bytes.

 Drive D:\ has the label "Local Disk"
  Total size 364670611456 bytes, free is 207251906560 bytes.

 Drive G:\ has the label "Deepak"
  Total size 214748360704 bytes, free is 214185193472 bytes.

 Drive H:\ has the label "WD Unlocker"
  Total size 7507968 bytes, free is 0 bytes.

 Drive I:\ has the label "My Passport"
  Total size 1000169533440 bytes, free is 836563316736 bytes.



  Remember- d.IsReady is must, other wise it will throw error when it will try to get the information of the CD-Rom and found CD-Rom is empty mean we have not inserted any CD or DVD, in this situation CD-Rom is not ready so by applying the proper LINQ we have removed the not ready drive from the all drive collection.

Happy Reading and knowledge sharing.. !! :)

17 December 2013

Create your own Right Click Menu

Hi Friends,

Sometime we want to create the right click menu as shortcut so that we can easy our task.  Sometime when we install any application it create a right click shortcut.

I have created a tool for you.  You just need to download it and run it. Let me explain about the application.

It has 4 options-

  • File-  When we want to create the right click menu on a file.  If you add menu by choosing this option it will be shown whenever you right click on any file.

  • Folder-  When we want to create the right click menu on a Folder.  Just create the menu by choosing this and right click any folder, you can find your newly created menu over there.

  • Desktop Background- When you create a menu by choosing this option.  You can find newly created menu when you right click on your desktop. (Note-  Remember because desktop is also a Directory that's why it is also showing the menu created by choosing 4th Option)

  • Directory Background- This is same as the Desktop Background menu, the only difference is that you can find this newly menu whenever you right click on empty space in any directory including your desktop.

You can download the executable file from the following link.
Download from here

Note-  Remember You must have installed the .Net framework (4.0, 3.5, 3.0 or 2).  As its a .net application so for the execution it needs the environment, provided by the .Net framework.

Happy Tricks and Coding.

10 December 2013

Change Screen Resolution using C#

Hi All,

I'm back.  Today let see how can we change the screen resolution using the C#. You might aware we can get the screen resolution in C# using the Screen class.

Screen Srn=Screen.PrimaryScreen;
            
int tempWidth=Srn.Bounds.Width;
int tempHeight=Srn.Bounds.Height;
Console.WriteLine("Current Screen width is {0} and height is {1}.", tempWidth, tempHeight);

and we get the output -
 Current Screen width is 1152 and height is 864.

Using the Screen class, we can get the screen resolution and size, but whats about to set the screen resolution as per the requirement.

Sometime we code in such a way we need a fix screen resolution mean to work the piece of code of whole snippet we require a size (x*y).

Using the Screen class we can verify either we have suitable environment or not but to set the environment to make the piece of code work we explicitly need to change the resolution of the screen.

I have code to change the resolution of the screen, you just need to down the DLL and you are ready to using it.

Download from here Download DLL Now.

After the downloading you are ready to go by including the dll in your project reference and you need to one line only

 MyTactics.blogspot.com.NewResolution n = new MyTactics.blogspot.com.NewResolution(1024, 768);



You can download the full sample from here. Download Full Sample.

First button to change the resolution to 1024 * 768, while the second button show the current resolution is 1152 * 864.  After clicking the First button resolution would be 1024 * 768 and we can revert back to original resolution by just clicking the Second Button.

Happy Coding and Knowledge sharing..!!!