Tuesday, 4 March 2014

BeginUpdate() and EndUpdate() when populating ListView/TreeView in C# ASP.NET

Often a listview control in C# needs to be populated with large amount of data (bulky operations, for example, adding 1000 items). For every item added in the Listview, the control will redraw itself, thus greatly reduce the overall performance.

However, using the two methods BeginUpdate() and EndUpdate() while performing these bulk operations gives significant advantage. A call to BeginUpdate() can be made before adding/deleting/clearing items. This will stop any paint messages being sent or processed. Once the operation is done, the EndUpdate() can then be called.


I have logged the time taken of the above code (i.e. adding 1000 items in a ListView for each button click) with and without the BeginUpdate/EndUpdate method calls using a test application.
The use BeginUpdate() and EndUpdate populates the control with a constant duration and much better performance. Amazing, isn't it?

Here's a simple source code example for using this technique with a ListBox:

ListBox1.Items.BeginUpdate;

for i := 1 to 10000 do
    ListBox1.Items.Add('abcd');

ListBox1.Items.EndUpdate;
 
To give you an idea of the improvement, we timed the code above (your PC may be faster or slower):

without the BeginUpdate/EndUpdate lines: 4.3 seconds...
with BeginUpdate/EndUpdate: 0.1 seconds, that's 43 times faster!

 

That’s it!!…..Happy Programming...

How to Pass Encoded data in Query String in C# ASP.NET

Solution :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class encode
{
    public encode()
    {

    }
    public string base64Encode(string data)
    {
        try
        {
            byte[] encData = new byte[data.Length];
            encData = System.Text.Encoding.UTF8.GetBytes(data);
            string encodedData = Convert.ToBase64String(encData);
            return encodedData;
        }
        catch (Exception ex)
        {
            throw new Exception("Error in base64Encode" + ex.Message);
        }
    }
    public string base64Decode(string data)
    {
        try
        {
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            System.Text.Decoder utf8Decode = encoder.GetDecoder();

            byte[] todecode = Convert.FromBase64String(data);
            int charCount = utf8Decode.GetCharCount(todecode, 0, todecode.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode, 0, todecode.Length, decoded_char, 0);
            string result = new String(decoded_char);
            return result;
        }
        catch (Exception ex)
        {
            throw new Exception("Error in base64Decode" + ex.Message);
        }
    }
}
Just Create a class like this..Now call one of these method by just passing any string data, it will also return string data after encode/decode. Now you can pass this data in your query string just like any normal data.Now the question which was raised on our mind, What is base64 Encoding??

It's a textual encoding of binary data where the resultant text has nothing but letters, numbers and the symbols "+", "/" and "=". It's a convenient way to store/transmit binary data over media that is specifically used for textual data.


That’s it!!…..Happy Programming...

Friday, 14 February 2014

How to make Asp.net Textbox Readonly in JavaScript

Solution:
script type="text/javascript">
    function makeReadOnly(){
        var textbox = document.getElementById("txtName");
        textbox.readOnly = "readonly";                          //readOnly is case-sensitive
        }

<body onload=" makeReadOnly ()">
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    </div>
    </form>
</body>
The reason behind calling makeReadOnly function in body tag is to make textbox readonly when page is loading. You can also make textbox readonly after page load by just calling the makeReadOnly function on any textbox or button control.

That’s it!!…..Happy Programming...

Friday, 7 February 2014

Program to catch and process an error n times in C#

I am going to implement a class which will catch error only once and process an error more than once which would depend on user, it means how many times user want to process that error. In this class 'n' represent how many times you want to process an error. If you want to process an error three times, you just need to change '3' at the place of 'n'.

using System;

class student
{
    public static void Main(String[] args)
    {
        int a = 3;
        int b = 0;
        int result;
        for (int i = 0; i < n; i++)
        {

            try
            {
                result = a / b;
                Console.WriteLine(result);
            }

            catch (Exception ex)
            {
                Console.WriteLine("error is" + ex.Message);
            }

        }
    }
}

That’s it!!…..Happy Programming...

Wednesday, 5 February 2014

What is the difference between ExecuteNonQuery and ExecuteScalar in SQL

ExecuteNonQuery 
  1. Used mainly for action queries(insert,delete,update,create,alter). 
  2. Returns an int value indicating the number of affected rows.
  3. Return value is optional and can be assigned to an integer variable.
Example :
public void updateEmail()
{
        SqlConnection con = new SqlConnection(connString);
        String sqlQuery = "UPDATE Employee SET email='a@b.com' WHERE id=1;
        SqlCommand cmd = new SqlCommand(sqlQuery, con);
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
         finally
         {
            con.Close();
         }
}
 
ExecuteScalar 
  1. Used in queries where we have to read a single value.
  2. Returns an object.
  3. Return value is compulsory and should be assigned to a variable of required type.
Example:
public int getSomeNumber()
{
        int count=0;
        SqlConnection con = new SqlConnection(connString);
        String sqlQuery = "SELECT COUNT(*) FROM dbo.myTable";
        SqlCommand cmd = new SqlCommand(sqlQuery, con);
        try
        {
            con.Open();
            //return type is System.Object, a typecast is must
            count = (Int32)cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
         finally
         {
            con.Close();
         }
         return count;
}


That’s it!!…..Happy Programming...

Tuesday, 4 February 2014

How to Convert Date into different format in C#

There are some situations where it is useful to convert a Date into a formatted character string within a application. 
Note:- Confusion between “m” and “M”, small case “m” represent minutes while “M” represent Month. This is most common cause of error while converting String to date and back date to string. In short ddMMyy is not equal to ddmmyy .
using System;

class DateFormat
{
    static void Main()
    {
       String dateFormat1=DateTime.Now.ToString("MM/dd/yyyy");
       Console.WriteLine(dateFormat1);  
       
       String dateFormat2=DateTime.Now.ToString("dd/MM/yyyy");
       Console.WriteLine(dateFormat2);
       
       String dateFormat3=DateTime.Now.ToString("MMM d, yyyy");
       Console.WriteLine(dateFormat3); 
       
       String dateFormat4=DateTime.Now.ToString("dddd, MMMM d");
       Console.WriteLine(dateFormat4); 
       
       String dateFormat5=DateTime.Now.ToString("MM/dd/yy");
       Console.WriteLine(dateFormat5); 
       
       String dateFormat6=DateTime.Now.ToString("dd MMM yyyy");
       Console.WriteLine(dateFormat6); 
       
       String dateFormat7=DateTime.Now.ToString("dd.MM.yyyy");
       Console.WriteLine(dateFormat7); 
       
       String dateFormat8=DateTime.Now.ToString("yyMMdd");
       Console.WriteLine(dateFormat8);
       
       String dateFormat9=DateTime.Now.ToString("dddd");
       Console.WriteLine(dateFormat9); // get only current day
       
       String dateFormat10=DateTime.Now.ToString("MMMM");
       Console.WriteLine(dateFormat10); // get only current month       
    } 
} 

That’s it!!…..Happy Programming...