5 November 2014

Show delimiter Text file data to DataGridView

Hi All,

Lets see how to show the delimiter text file in DataGridView in C#.  Lot of use face the problem when we have CSV or any other delimiter text file and asked to show it as table in C# DataGridView.

As one user asked at Stackoverflow


You can have to copy paste the following code and ready to go..

using System.Data;
using System.IO;


public class Helper
{

 public static DataTable DataTableFromTextFile(string location, char delimiter=',')
 {
     DataTable result;

     string[] LineArray = File.ReadAllLines(location);

     result = FormDataTable(LineArray, delimiter);

     return result;
 }


 private static DataTable FormDataTable(string []LineArray, char delimiter)
 {
     bool IsHeaderSet = false;

     DataTable dt = new DataTable();

     AddColumnToTable(LineArray, delimiter, ref dt);

     AddRowToTable(LineArray, delimiter, ref dt);

     return dt;
 }


 private static void AddRowToTable(string []valueCollection, char delimiter, ref DataTable dt)
 {

     for (int i = 1; i < valueCollection.Length; i++)
     {
     string[] values = valueCollection[i].Split(delimiter);

     DataRow dr = dt.NewRow();

     for (int j = 0; j < values.Length; j++)
     {
         dr[j] = values[j];
     }

     dt.Rows.Add(dr);
     }
 }


 private static void AddColumnToTable(string []columnCollection, char delimiter, ref DataTable dt)
 {
     string[] columns = columnCollection[0].Split(delimiter);

     foreach (string columnName in columns)
     {
     DataColumn dc = new DataColumn(columnName, typeof(string));
     dt.Columns.Add(dc);
     }

 }

}

Thats all.. ready to use.. Now let me tell you how to bind this with DataGridView just call

// if | is delimiter char
//fname| sname| age
//deepak| sharma| 23
//Gaurav| sharma| 32
//Alok| Kumar| 33
dataGridView1.DataSource = Helper.DataTableFromTextFile("Testing.txt", '|');


//if comma , is delimiter char like - 
//fname, sname, age
//deepak, sharma, 23
//Gaurav, sharma, 32
//Alok, Kumar, 33
dataGridView1.DataSource = Helper.DataTableFromTextFile("Testing.txt");


if pipeline(|) is delimiter character else pass what else it is.  Default delimiter char is common(,) so in case of (,) no need to even pass it.

It works like charm. :)




Happy Coding.. and Sharing.. :)

17 September 2014

Convert C# DataTable to JavaScript 2D Array

Hi All,

Lets see how to send the DataTable from Code behind to JavaScript.  Some time we face the problem when we need to array the value from C# code behind to JavaScript use use script tag <%=variable_name%> Right we are also going to use the same approach. But the main point is how to convert the DataTable(or Dictionary or List of object) from C# to JavaScript.

Someone might come up with the thought to use the Repeater control.  But its really typical,  What about if I say you can get the C# DataTable  as 2D array in JavaScript with no extra efforts??

:) Cool...

you just need to pass your DataTable in this method and it will create the Json Serialized array to be used in JavaScript. :)

   public partial class RepeaterControlTesting : System.Web.UI.Page
   {
      public string dataTable;        
      protected void Page_Load(object sender, EventArgs e)
      {
         if (!IsPostBack)
         {
            dataTable = ConvertDataTabletoString(getDT());                
         }
      }
      public string ConvertDataTabletoString(DataTable dt)
      {            
          JavaScriptSerializer serializer = new JavaScriptSerializer();
                   
          List<List<object>> rows = new List<List<object>>();
          List<object> row;
          foreach (DataRow dr in dt.Rows)
          {
             row = new List<object>();
             foreach (DataColumn col in dt.Columns)
             {
                row.Add(dr[col]);
             }
             rows.Add(row);
          }

          return serializer.Serialize(rows);
      }
      public DataTable getDT()
      {
          /// or get the DataTable from Database.. 
          DataTable dt = new DataTable();
          dt.Columns.Add("Col_int", typeof (int));
          dt.Columns.Add("Col_string", typeof(string));
          dt.Columns.Add("Col_bool", typeof(bool));
          dt.Columns.Add("Col_4th", typeof(string));
          dt.Columns.Add("Col_float", typeof(float));

          DataRow dr;
          for (int i = 1; i <= 5; i++)
          {
              dr = dt.NewRow();
              dr[0] = i;
              dr[1] = i + "  Col_string";
              dr[2] = (i%2 == 0);
              dr[3] = i + " Col_4th";
              dr[4] = (float)i;

              dt.Rows.Add(dr);
          }

          return dt;
      }

  }

Thats it.. now just goto you aspx file and access the "dataTable" in your JavaScript code..

<body>
    <div id="main">
                
    </div>
        
    <script>        
        var dataTable = <%= this.dataTable %>;
        for (var i = 0; i < dataTable.length; i++) {
            $("#main").append("| "+dataTable[i][0] + " | ");
            $("#main").append(dataTable[i][1] + " | ");
            $("#main").append(dataTable[i][2] + " | ");
            $("#main").append(dataTable[i][3] + " | ");
            $("#main").append(dataTable[i][4] + " |<br/><br/>");
        }
    </script>
</body>



Good to go.. :) Happy Code sharing.. :)

2 September 2014

SignalR - Real Time Communication

Hi All,

Today lets talk about "SignalR", I hope You might have heard about it.  But How to use it you might face some problem.
SignalR is used for real time communication, eg like - social networking site for notification, in your mail inbox for new mail arriving, real time chat application, group chatting forums and other.  Real time communication make sense and we know what does it mean.

When we try to implement real time relationship, the first way came in our mind it polling.. Long-polling or short-polling.. But what about if I say we have one more efficient method then polling?  Oh you got it? is that Web-Socket??  Yes it is.. but if you are going to use Web-Socket or any other HTML5 elements you have to make it sure you are going to support few old browsers as well which doesn't support HTML5 elements.

Now you  might think about long-polling with Web socket?  web-socket for new browser and polling for old browser? Right?

Yes that the way to support the old and new browser. But you have to code for polling and web-socket, then check the browser support, then call the supported coding snippet.  But I am saying no need to code for all SignalR here to do all this.  SignalR is enough intelligent to figure out what to use and how to use.  No need to code for polling and web-socket.

SignalR check the client and Server both, if both support the Web-Socket it goes for web-socket else efficient polling.  The best part is you no need to worry about it and coding part, it takes care for that. :)  Lets see for example and dependencies..


  • JQuery > 1.6 
  • SignalR  JS file
  • SignalR dll
  • Owin dll
  • Newtonsoft.Json dll


but again no worry, follow the below steps one by one - (Download Sample from here)

  • Open your Visual Studio and Create new blank Web Project.
  • Go to TOOLS >  NuGet Package Manager  >  Package Manager Console.  Type the following command on console and hit the  <Enter>, it will process and install and add the reference to your project..
    install-package Microsoft.AspNet.SignalR
  • install this package, it will automatically download all the dependencies and required dll all jquery files.
  • Right click project and add one class called as "Startup.cs"(name should be same) and paste the following code.
  • using Microsoft.Owin;
    using Owin;
    
    [assembly: OwinStartup(typeof(SignalR_For_Upload.Startup))]
    namespace SignalR_For_Upload
    {    
      public class Startup
      {
        public void Configuration(IAppBuilder app)
        {
           app.MapSignalR();
        }
      }
    }
    
    
  • Now create another class file and named it as "MyHub.cs", and paste the below code
  • using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Hubs;
    
    namespace SignalR_For_Upload
    {
      [HubName("newNameOfHub")]
      public class MyHub : Hub
      {
        public void SendMsg(string message)
        {
          Clients.All.ReceiveMsg(message);
        }
      }
    }
    
    
  • So the above is the Hub which keeps track of all the client and send the message to them using the statement stated above. 
  • Clients.All.ReceiveMsg(message);
    here 'Client.All' mean all the clients while 'ReceiveMsg(message)' is the dynamic expression which can be considered as event name for client 
    
  • Thats all now no more coding .. :) just need to bind up this event from client using javascript snippet. let have a look at that part as well.
  • Create your "Default.aspx" page and replace the "body" section with the following code(You can take the plain html page as well :) no worries).
  • <body>
      <input type="text" id="msg" value=" " />
      <input type="button" id="send" value="send" />
      <ul id="message">
      </ul>
        
      <script src="Scripts/jquery-1.6.4.min.js"></script>
      <script src="Scripts/jquery.signalR-2.1.1.min.js"></script>    
      <script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
      <script>        
        $(function () {
            
           var con = $.hubConnection();
           var hub = con.createHubProxy('newNameOfHub');
            
           hub.on('ReceiveMsg', function (message) {
              $('#message').append('<li>' + message + '</li>');
           });
    
           con.start().done(function () {
              $('#send').click(function () {
                 hub.invoke('sendMsg', $('#msg').val());                    
              });
           });
    
        });
      </script>
    </body>
    
  • So thats it.. just save the page. and run this in two browser and check they are communication in real time.  :)  Download Sample


Happy Code Sharing.. :)

13 June 2014

Auto Complete TextBox in Window Form C#

Hi All,

Let see how to create the AutoComplete TextBox in window form.
You might be aware of Auto Complete in web page using the Ajax and JQuery plugins or using the asp.net ajax toolkit.

But when it comes to the Auto Complete TextBox in Window Form some people find it difficult.

I am gonna demonstrate you Auto Complete Textbox for months Jan - Dec.

Download Sample
  • Open Visual Studio and create a Window Form application. 
  • It will add a blank default Window Form for you.
  • Drag a label name it Months and a Input TexBox for Auto Complete Months.

  • Double Click form to open Form_Load event. and create AutoCompleteStringCollection class object.
  • Add you indented string item in object in this case months name string array.
        private void Form1_Load(object sender, EventArgs e)
        {            
            // Create the list to use as the custom source.  
            var source = new AutoCompleteStringCollection();            
            source.AddRange(new string[]
                    {
                        "January",
                        "February",
                        "March",
                        "April",
                        "May",
                        "June",
                        "July",
                        "August",
                        "September",
                        "October",
                        "November",
                        "December"
                    });
            
            // attched it with the created text box.
            textBox1.AutoCompleteCustomSource = source;
            textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
        }

  • Bind the AutoCompleteStringCollection with textBox1.

and you are done.  Now when you run the form and just type only one character "j" it will show the months starting from "j".

Happy knowledge sharing.. ☺

26 March 2014

Parent Div height zero(0) even child div has content

Hi,

Let see what happened when we float the child div to Left or Right. Parent Div shows the height as 0.

<html>
  <head>
    <style>
      #parent
      {
        width:100%;
        height:auto;
      }
      #child
      {
        float:right;
        width:25%;
        height:auto;
        border:1px solid black;
        margin:10px;
      }
    </style>
  </head>
  <body>
    <div id="parent">
      <div id="child">
        this is the content inside the child
      </div>
    </div>
  </body>
</html>

It shows the result as -


Notice child div has content so it has the height but if child div has the height why parent div showing height as zero(0)??

Its because of you set the
float:right; 
on child div which make it position:absolute and thats why parent div height is zero.  To correct is you just need to set the overflow:hidden on parent div.

modified the css part as below -
      #parent
      {
        width:100%;
        height:auto;
        overflow:hidden;
      }
And you are good to go you will get the correct result as -

Happy Blogging and Sharing.. ☺☻

25 February 2014

Read-Write Excel file in Java

Hi All,

Lets see you can read/write the data from/to Excel worksheet(.xls file) .  Its very useful when you provide the option to export and import the data in you web page.



package myExcel;
import java.io.File;
import java.io.FileInputStream;

import  org.apache.poi.hssf.usermodel.HSSFSheet;  
import  org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import  org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;

public class ReadExcel {
  public static void main(String[] args) {
    try
    {
      File f = new File("C:\\Users\\dsharma\\Desktop\\Excel.xls");
      FileInputStream fin = new FileInputStream(f);
      HSSFWorkbook workbook = new HSSFWorkbook(fin);
      HSSFSheet tempSheet;
      HSSFRow tempRow;
      HSSFCell tempCell;
      for (int i = 0; i < workbook.getNumberOfSheets() ; i++) {
        tempSheet = workbook.getSheetAt(i);
        System.out.println("Sheet - \""+tempSheet.getSheetName()+"\"");
        /*
         *  remember getLastRowNum() returns the 0 based index
         *  so we have to use ( "<=" )
         *  
         *  in for loop  [ j <=  tempSheet.getLastRowNum() ]
         */                 
        for (int j = 0; j <= tempSheet.getLastRowNum() ; j++) {
          tempRow = tempSheet.getRow(j);      
          if(tempRow!=null)
          {
            for (int j2 = 0; j2 <tempRow.getLastCellNum(); j2++) {
              tempCell = tempRow.getCell(j2);
              System.out.printf("%-15s|",tempCell);
            }
          }          
          System.out.println("");
        }
        System.out.println("\n\n");
      }
    }
    catch(Exception ex)
    {
      ex.printStackTrace();
    }    
  }
}

This will read you excel file specified at line number 15. and will print the data in all the sheets inside your excel workbook.

And Lets see how can you create and write excel file(.xls) from your Java Code.
package myExcel;

import java.io.File;
import java.io.FileOutputStream;

import  org.apache.poi.hssf.usermodel.HSSFSheet;  
import  org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import  org.apache.poi.hssf.usermodel.HSSFRow;

public class WriteExcel {
  public static void main(String[] args) {
    try{          
      HSSFWorkbook workbook = new HSSFWorkbook();      
      HSSFSheet tempSheet = workbook.createSheet("Created Sheet");
      
      //Create first row reference from the sheet "tempSheet"
      HSSFRow tempRow = tempSheet.createRow(0);
      
      //add the 3 column and value in first row
      tempRow.createCell(0).setCellValue("Roll No.");
      tempRow.createCell(1).setCellValue("Name");
      tempRow.createCell(2).setCellValue("Passed?");
      
      //adding 5 students details
      for (int i = 0; i < 5; i++) {
        //create second row. as first is header
        tempRow = tempSheet.createRow(i+1);
        
        //add three columns value
        tempRow.createCell(0).setCellValue(i+1);
        tempRow.createCell(1).setCellValue("Student "+(i+1));
        tempRow.createCell(2).setCellValue(i%2==1);
      }
        
      //outputstream object of the file to be created
      File f = new File("C:\\Users\\dsharma\\Desktop\\New_Excel.xls");    
      FileOutputStream fout = new FileOutputStream(f);
      workbook.write(fout);
    }
    catch(Exception ex){
      ex.printStackTrace();
    }
  }
}

You can see for both read-write we need few new reference, yes we need a library file. Called "Apache POI library",  don't worry you can download the that jar file from the below links.
Download POI

So this is the basic to read and write the Excel file in Java.  Now if you find its typical to implement it in you JSP-Servlet webproject?? get the below sample project(Eclipse Project.  jdk1.7  used).  Don't worry for the library for JSP project, I have included all the jar file inside the project.

Download Eclipse Project(.ZIP)

Happy Coding and Sharing.. :)

25 January 2014

Convert DataGridView column to Combo Box

Hi Friends,

Sometime if you work in windows form application in C# or using VB,  you may face a problem where you want to put a combo on a field in grid view for a column from the data source table.

Consider a gridview displaying the information of the student  or employee then for the Gender field you may want a Combo Box having the two value Male and Female,  so that for the new record user no need to type the gender value MALE or FEMALE he will select the value from the Combo Box.


So you want to convert plain text column Combo Box. You can download the above sample from the given download link.  Download Sample.

In Form_Load event code the below part.  just copy-paste the below code.

DataTable dt = new DataTable();

private void getDataSource()
{
 dt.Columns.Add("Name");
 dt.Columns.Add("Last");
 dt.Columns.Add("Gender");

 dt.Rows.Add("Rohit", "Sharma", "Male");
 dt.Rows.Add("Saurabh", "Singh", "Male");
 dt.Rows.Add("Gurpreet", "Kaur", "Female");        
}

private void Form1_Load(object sender, EventArgs e)
{
    // just fill the dummy record in datatable dt
    getDataSource();

    // table dt has three column index 0,1,2
    dataGridView1.DataSource = dt;

    // create Combo Box Cell
    DataGridViewComboBoxCell bc = new DataGridViewComboBoxCell();               
 
    //if want to add the fix value in ComboBox Male and Female
    bc.Items.AddRange("Male","Female");
 
    /*  if you want to get the existing value in gender column 
     * and display them in ComboBox
     */
     // var ss = dt.AsEnumerable()
     //           .Select(_ => _.Field<string>("gender")).
     //           .Distinct();
     // bc.Items.AddRange(ss.ToArray());

    /* add one more column at index 3 as ComboBox for the value
     * in index-2 column "Gender"    
     */
    DataGridViewColumn cc = new DataGridViewColumn(bc);
    dataGridView1.Columns.Add(cc);
    dataGridView1.Columns[3].HeaderText = dataGridView1.Columns[2].HeaderText;
    

    /* hide the plain value for gender mean index-2 column as we
     * have index-3 column as combobox for gender
     */
    dataGridView1.Columns[2].Visible = false;       

    // set the gender value in combobox
    foreach (DataGridViewRow item in dataGridView1.Rows)
    {
       item.Cells[3].Value = item.Cells[2].Value;
    }    
}

Happy Code sharing and Blogging.. :)

22 January 2014

DataGridView not showing the DataSource (List, Array) in Grid

Hi Friends,

Sometime we bind the datasource with DataGridView object but still it doesn't show the data in grid view.

Consider we have a class Employee as

 class Employee
 {
     public string fname;
     public string sname;

     public Employee(string f, string s)
     {
         fname = f;
         sname = s;
     }
 }

and we bind List/Array of the Employee class as the datasource of the DataGridView in window form as below -

public partial class Form1 : Form
{
    List<Employee> lst = new List<Employee>();    
    
    public Form1()
    {
        InitializeComponent();

        lst.Add(new Employee("deepak1", "sharma"));
        lst.Add(new Employee("deepak2", "sharma"));
        lst.Add(new Employee("deepak3", "sharma"));                
        
        dataGridView1.DataSource = lst;
        dataGridView1.Refresh();        
    }

}

but when we open the form we are not able to see the data in datagridview.

The main reason is we don't have get set properties in Employee class.  Even the fname and sname are public but still we have to define the properties for the attribute we want to show.

You just need to modify two line in your Employee class.



 class Employee
 {
     public string fname; 
     public string sname; 
    
     public string fname { get; set; }
     public string sname { get; set; }
    
     public Employee(string f, string s)
     {
         fname = f;
         sname = s;
     }
 }

Now if you run the above code it will display the records in DataGridView. :)

Happy Code Sharing and Blogging.. :)

21 January 2014

Generate the barcode in C# (String to Image in C# )

Hi Friends,

Last day on https://stackoverflow.com one user ask two questions ( one and second) how to generate the barcode in C# like the below image -


he has generated the barcode(only stripe) using the font (free 3 of 9) and string "123456" in string now he wanted to merge them like the above image. and finally he want to output as an image so that he can display that of window form / web page or he can save that for future reference.

well its really interesting task, isn't it??

I tried it at my end and finally got a solution and suggested him the same solution and finally he accepted and appreciated the solution. Use the below code that's it.

 //Set the font style of output image
Font barCodeF = new Font("Free 3 of 9", 45, FontStyle.Regular, GraphicsUnit.Pixel);
Font plainTextF = new Font("Arial", 20, FontStyle.Regular, GraphicsUnit.Pixel);


public Image stringToImage(string inputString)
{
  //remove the blank space after and before actual text
  string text = inputString.Trim();

  Bitmap bmp = new Bitmap(1, 1); 
  Graphics graphics = Graphics.FromImage(bmp);

  
  
  int barCodewidth = (int)graphics.MeasureString(text, barCodeF).Width;
  int barCodeHeight = (int)graphics.MeasureString(text, barCodeF).Height;

  int plainTextWidth = (int)graphics.MeasureString(text, plainTextF).Width;
  int plainTextHeight = (int)graphics.MeasureString(text, plainTextF).Height;

  
  
  //image width 
  if (barCodewidth > plainTextWidth)
  {
    bmp = new Bitmap(bmp,
                     new Size(barCodewidth, barCodeHeight + plainTextHeight));
  }
  else
  {
    bmp = new Bitmap(bmp,
                     new Size(plainTextWidth, barCodeHeight + plainTextHeight));
  }
  graphics = Graphics.FromImage(bmp);

  
  
  //Specify the background color of the image
  graphics.Clear(Color.White);
  graphics.SmoothingMode = SmoothingMode.AntiAlias;
  graphics.TextRenderingHint = TextRenderingHint.AntiAlias;

  

  //Specify the text, font, Text Color, X position and Y position of the image
  if (barCodewidth > plainTextWidth)
  {
    //bar code strip
    graphics.DrawString(text,
                        barCodeF,
                        new SolidBrush(Color.Black),
                        0,
                        0);
    
    // plain text
    graphics.DrawString(text,
                        plainTextF, 
                        new SolidBrush(Color.Black),
                        (barCodewidth-plainTextWidth)/2,
                        barCodeHeight);
  }
  else
  {
    //barcode stripe
    graphics.DrawString(text,
                        barCodeF,
                        new SolidBrush(Color.Black),
                        (plainTextWidth - barCodewidth) / 2,
                        0);

    //plain text
    graphics.DrawString(text,
                        plainTextF,
                        new SolidBrush(Color.Black),
                        0,
                        barCodeHeight);
  }

  
  
  graphics.Flush();
  graphics.Dispose();

  
  //if you want to save the image  uncomment the below line.
  //bmp.Save(@"d:\myimage.jpg", ImageFormat.Jpeg);

  return bmp;
}
use this code.  Pass the string in this method and it will return you the barcode image.  Remember you must have installed the free 3 of 9 font in you systems to generate the bar code. You can download the free3 of 9 font from the given linke. Download Free3of9 Font.

This is the output of the above code when I pass string as "NRL9685325PR".


You can download the sample from here.  Download BarCodeSample .

Happy Coding and Sharing.. :)

20 January 2014

C# Extension Methods

Hi All,

Lets see whats the extension method in C# and whats the main use of it.  Sometime we want to add a method in existing class.  This class can be from the .net library or any third party class.  To do so we generally extends the existing class in our new class and then compile it and use that new class.

Like in c# library class - "string" does not have any such method to count if we want such method we have to design our own method.  Remember you can not inherit the "string" class as its sealed.

static class MyClass
{
  public static int WordCount(string line)
  {
      line = line.Trim();
      return line.Split(' ').Length;
  }
}


now you have to call this method like -

int n = MyClass.WordCount("String whatever we want to pass");


but if we want to merge this method with existing c# library string class?  but as we dont have source code of string class we can not edit the source code write?

Extension method do this job.  Using the extension method we can add the method in compiled class without needing source code, so that you can call your own method like the previous existing method in string class.

string str = "string whatever we want to pass";
int n = str.WordCount();


to add an extension method to existing class you just need to class a static class and static method like we created earlier.  The only change we required in passing parameter we need to add the "this" keyword.

static class MyClass
{
    public static int WordCount( this string line)
    {
        line = line.Trim();
        return line.Split(' ').Length;
    }
    
    public static int WordCountStartsWith( this string line, char c)
    {
        int result = 0;
        line = line.Trim();
        
        var word = from wrd in line.Split(' ')
                   where wrd.First() == c
                   select wrd;
        result = word.Count();

        return result;
    }

    public static int WordCountContains( this string line, string str)
    {
        int result = 0;
        line = line.Trim();

        var word = from wrd in line.Split(' ')
                   where wrd.Contains(str)
                   select wrd;
        result = word.Count();

        return result;
    }
}


Now to call these method we can just use the object of string class.

This is the beauty of the extension method, we do not need to recompile the parent class(in this case string class).  We just need to remember when want to design an extension method -
  1. static class
  2. static method
  3. this keyword just before the passing parameter class, whose extension we want. 
Download Sample


See we are getting our own three extension method on string class.

string line = "string value or line whose word we want to count";
int n = line.WordCountContains("nt");

Happy Coding and Blogging.. !! :)

16 January 2014

Pipe (|) symbol, Blank line and Comment in batch programming

Hi Friends,

Lets see how can you print the pipe line ( | ) symbol in batch file.  If you directly use the | symbol then batch file will throw an error.  To display the pipeline symbol in batch file, you have to use the "^" symbol just before the pipeline symbol.

As we know we use "echo hello" to print the hello then you might think to print line we can use the "echo" only. Am I right? but to display the blank line, we have to use the dot( . ) just after the echo word "echo." remember there should not be any space between echo and dot(.)

To mark the line as comment we have to use the double colon ( :: )

 Check the below example -

@echo off
echo.
echo above line is blank
::echo This line is comment as the line starts with Double colon (::)
echo +--------------------------------+
echo ^|                          ^|
echo ^|        Hello World..!!      ^|
echo ^|                          ^|
echo +--------------------------------+
pause

when you will try to run the above batch code, you will get the below output.


Happy Sharing.. :)

Command Line Argument to Batch file (Parameter)

Hi All,

Lets see how can we pass the parameter to batch file.  If you have worked with C, C++ and anyother programming language then I hope you must be familir with "Command Line Args" and whats the use of it.

lets see the basic batch file code to print the value.
@echo off
set n=Hello World..!!!
echo Hello Friends the value stored in variable n is = %n%
pause

when i will run the above batch code it will show the output as below -

Hello Friends the value stored in variable n is = Hello World..!!!
Press any key to continue . . .

but I want to pass the value to the batch code, to run the file I have to use the file name followed by the value we want to pass.

batch_file.bat value1 value2

now our job is to take these value from the command line and use it in our batch code. %1 will refer to the first parameter value and %2 will point to the second value.

@echo off

if %1.==. goto novar1
if %2.==. goto novar2

set first_var= %1
set second_var=%2

echo first variable pass as command line is = %first_var%
echo second variable pass as command line is = %second_var%
goto end

:novar1
echo no command line argument passed in.
goto end

:novar2
echo only one command line argument passed in.
goto end

:end
pause
so in this way you can pass the command line argument to batch file,  and can check either command line argument is passed or not.

Happy Coding & Sharing..

3 January 2014

How to Change the Login Screen - Windows

Hi All,

Lets see how can we have the Login screen in Windows.  Its a registry trick.  Let me tell you this trick so that you can change.

I have bundle all these step together and create a software for you in C# net framework 4.0.  You can download this tool from the following link
Download

You can do all this manually also.  Follow the below steps.
  1. Goto to "C:\Windows\System32\oobe\"
  2. Create a directory "info" at the above location.
  3. Create another directory "backgrounds" inside "info".
  4. Goto the path "C:\Windows\System32\oobe\info\backgrounds"
  5. Paste your "jpg" file (Remember  file size must be less than 256KB)
  6. Rename the file as "backgroundDefault.jpg"
  7. Press "Win key + R" type "regedit.exe"
  8. Goto the path "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\Background"
  9. Double click the key "OEMBackground" and change the value from "0" to "1".

Thats it.  Now if you lock your system you will see the new background image.

To restore the original image you just need to revert back the registry value from "1" to "0".


Or 

Use the below link, download the tool designed by me and do the above step in just few clicks.  
Download (Tested on Win7/Server 64 bit. If facing any issue in 32 bit please let me know.)

  • Browse - use this button to find your image.  This button has the filter on image size.  As it allowed the jpeg image having the size less then 256 kb.
  • Default - if you click this button it will show you the default login screen.
  • Current - it will show you the current background image which is active.
  • Preview - this will show you the Preview of the image select on full screen mode.
  • Save - This will be used to save the changes.

when click the preview button 



Happy coding and sharing.. !! :)

2 January 2014

This app needs permission to use the camera. Camera app: error in Windows 8.

Hi All,

Lets see how to enable the Camera App's in window 8 once it got disable by mistake.  First time when you open the "Camera app" in "Windows 8" it will prompt and ask you to for the permission to access the hardware - "Camera and Mic".  If by mistake you click on "Block" that mean windows will consider this app as blocked app which can not access the "Camera and Mic".  Now whenever you will start this app you will get a message



Now lets see you to allow the this app to access your "Camera and Mic"

1.  Open your Windows 8 "Camera App".  You will see the above error screen.

2. Press "Win + C" to bring the Windows 8 Charms Bar.

3. Click on the "Settings".

4.  Select the "Permissions" from the setting Menu.

5.  Change the access permission of your "Camera and Mic".

6.  Done. Close the Camera app and reopen it.  Its work. :)

Happy knowledge sharing.. !! :)
Happy Blogging.. :)

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