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.. :)