Showing posts with label C#.net. Show all posts
Showing posts with label C#.net. Show all posts

09 September 2015

Extension Methods in C#.Net


  • Extension methods are a new feature in C# 3.0

  • You can use extension methods to extend a class/interface, but not to override them.

  • Extension methods are static methods of a static class, and the 1st parameter is preceded by the “this” modifier (refers to class/interface/the called value), 2nd onward parameters act as passing parameters as in normal method calling

  • you need to add the "using System.Linq" directive to the top of the code

  • Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code

  • If the class is sealed than there in no concept of extending its functionality

  • This feature is important for all developers, especially if you would like to use the dynamism of the C# enhancements in your class's design

  • An extension method must be defined in a top-level static class

  • An extension method is defined as static method but it is called like as instance method

  • Overuse of extension methods is not a good style of programming


Ex: With Multiple Parameters
public static class MyExtensions
{
static int WordCount(this String str, char[] charArray)
{
return str.Split(charArray).Length;
}
}

And it can be called from an application by using this syntax:
string str = "Hello Extension Methods";
int i = str.WordCount(new char[] { ' ', '.', '?' });

Extension methods at compile time:


An extension method with the same name and signature in an interface or class method (1st priority) will never be called.


Inherit the class and then implement the functionality in an instance method in the derived class.


Use aggregation instead of inheritance.

Aggregation example:

university owns various departments (e.g., chemistry), and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.


Ex1: with Interface
public interface IMyInterface
{
        // Any class that implements IMyInterface must define a method 
        // that matches the following signature. 
        void MethodB();
}

public static class Extension
{
    public static void MethodA(this IMyInterface myInterface, int i)
    {
       Console.WriteLine("Extension.MethodA");
    }
}

public class A : IMyInterface
{
      public void MethodB() { Console.WriteLine("A.MethodB()"); }
}

class ExtMethodDemo
{
static void Main(string[] args)
{
A a = new A();
a.MethodA(1); //A contains no MethodA,
//so it calls the extension method that has a matching signature.
}
}

Output:
    Extension.MethodA

Ex2: with class
public class Class1
    {
        public string Display()
        {
            return ("Display");
        }

        public string Print()
        {
            return ("Print");
        }
    }

public static class XX
    {
         public static void NewMethod(this Class1 ob)
        {
            Console.WriteLine("NewMethod");
        }
    }

class Program
    {
        static void Main(string[] args)
        {
            Class1 ob = new Class1();
            ob.Display();
            ob.Print();
            ob.NewMethod();
            Console.ReadKey();
        }
    }
}

Output:
Display
Print
NewMethod

The compiler doesn't cause an error if two extension methods with same name and signature are defined in two different namespaces and these namespaces are included in same class file using directives. Compiler will cause an error if you will try to call one of them extension method.


One of the great reasons for Extension methods is behind LINQ. Without extension methods a lot of what you can do in LINQ would be very hard. The Where(), Contains(), Select extension methods means a lot more functionality is added to existing types without changing their structure


The biggest disadvantage is that there's no compiler error or warning if you have a regular method and an extension method with the same signature in the same context.


Extension methods fit very well into an OOP design: consider the simple method



bool empty = String.IsNullOrEmpty (myString)

in comparison to
bool empty = myString.IsNullOrEmpty ();

Ex3: With Multiple parameters in Extension Method
class Program
{
static void Main(string[] args)
{
List<Product> Products = new List<Product>()
{
new Product{ProductName = "White Shoe", ProductPrice = 10},
new Product{ProductName = "Green Shoe", ProductPrice = 5},
new Product{ProductName = "Black Shoe", ProductPrice = 15}
};

foreach (Product p in Products)
{
Console.WriteLine("{0} costs {1} (VAT: {2})",
p.ProductName, p.ProductPrice, p.CalculateVat());
}
}
}

public static class MyExtensions
{
public static double CalculateVat(this Product p)
{
return (p.ProductPrice * .25);
}
}

public class Product
{
public string ProductName { get; set; }
public double ProductPrice { get; set; }
}

However, you do not own or have control over the Product class since it is owned by someone else. So you can’t add a CalculateVat() method to the product class, And it can be done by using EXTENSION METHODS.

21 December 2013

Difference between String and string

1. String stands for System.String and it is a .NET Framework type.
2. string is a type in C#. System.String is a type in the CLR.
3. string is an alias for System.String in the C# language. Both of them are compiled to System.String in IL (Intermediate Language),
4. So there is no difference. Choose what you like and use that.
5. For code in C#, its prefer to use string as it's a C# type alias and well-known by C# programmers.


6. string is a reserved word, but String is just a class name.This means that 'string' cannot be used as a variable name by itself.


StringBuilder String = new StringBuilder(); // compiles
StringBuilder string = new StringBuilder(); // doesn't compile


7. If you really want a variable name called 'string' you can use @ as a prefix :
StringBuilder @string = new StringBuilder(); this applies to string also.


8. So String is not a keyword and it can be used as Identifier whereas string is a keyword and cannot be used as Identifier. And in function point of view both are same.
9. You can't use String without using System; but string can use without that namespace.
10. Static functions such as String.Format, String.Join, String.Concat, String.isNullOrWhitespace etc... are from String.



I can say the same about (int, System.Int32) etc..

20 December 2013

default Timeouts in c#

SqlConnection.ConnectionTimeout - 15 sec

- Gets the time to wait while trying to establish a connection before terminating the attempt.

SqlCommand.CommandTimeout - 30 seconds

- Gets or sets the wait time before terminating the attempt to execute a command

Session Timeout - 20 mins

<system.web>
<SessionState timeout=”10”></SessionState>

Cookies per Domain - 20 - 1KB

 

String Vs StringBuilder

System.String
-------------
1. String is immutable. It means that you can't modify string at all, the result of modification is new string. This is not effective if you plan to append to string
2. many actions that you do with string
3. Here concatenation is used to combine two strings by using String object
4. The first string is combined to the other string by creating a new copy in the memory as a string object, and then the old string is deleted
5. string is non updatable
6. everytime a object has to be created for Operations like append,Insert etc. at runtime

System.StringBuilder
--------------------
1. StringBuilder is mutable. It can be modified in any way and it doesn't require creation of new instance.
2. if you try to do some other manipulation (like removing a part from the string, replacing a part in the string, etc.), then it's better not to use StringBuilder at those places. This is because we are anyway creating newstrings.
3. system.stringbuilder is updateble
4. string builder is faster than the string object
5.String builder is more efficient in case large amount of string operations have to be perform.
6.Insertion is done on the existing string.
7. At the end, we can get the string by StringBuilder.ToString()
dis-adv:
1. We must be careful to guess the size of StringBuilder. If the size which we are going to get is more than what is assigned, it must increase the size. This will reduce its performance.
2. many actions can't be done with StringBinder.
3. When initializing a StringBuilder, you are going down in performance.
4. StringBuilder can be used where more than four or more string concatenations take place.

10 February 2013

9 February

i). Machine. Config

ii). Web.Config (For desktops app.Config)

Common paints for confn files:

  • These are simple text files & can be edited using any simple text editor.

  • These are xml formatted (case sensitive) & any xml programs can use these files or they can be directly edited because xml is human readable.

  • * They are automatically cached on memory for faster retrieval of settings (Cache memory àprogrammed memory area).

  • * Processed in hierarchical manner which means every configuration file inherits its parent configuration file settings. The root for all these files is Machine.Config.

  • Also called as configuration inheritance apart from this configuration is also hierarchical as xml is hierarchical.


Machine.Config points:

  • It is called per-server basis file. Only one machine.config is allowed for one runtime/server.

  • Located .NET framework folder not on our project & all settings are common to all websites running in that system. * 4 MB (default)(more than 4.0 go to machine.config – one file- change)

  • Most of the settings are maintained by administrator but not by application developers.

  • here we find all website settings(default) i.e., namespaces, services of support, net support, compileation settings, deploy settings, db settings ......


Web.Config points:

  • It is called as application Configuration file.

  • **** It is optional today also to have web.config in our application located in root & can be created sub folders also. We can create multiple web.config’s on our site maximum is how many folders we have in our project.

  • we can perform the following functionalities in web.config file:



  1.  Maintain connection strings

  2. Custom errors

  3. Security

  4. Debugging

  5. Tracing


----------------------------

The Cursor Process has the following steps involved in it: (exception handling in sp)

  • Declare a Cursor

  • Open a Cursor

  • Fetch data from the Cursor

  • Close the Cursor

  • De-allocate the Cursor


----------------------------

When a client, makes a request for an aspx page, it will be processed at server & all the result produced is concatenated as a single string along with some hash values in it.

These concatenated values are converted into base 64 format***. These base 64 values are stored in one or more hidden fields*** by server sent to client along with other from contents.

User adds/modifies the content & resubmits the form to server. Server first reads the hidden field values so that it retains the last given values (act as stateful) &responds the same process with new repeated as long as user is working with current page....

---------------------------

What is the scope of application variable?

  1. Accessible to all users of application, irrespective of the user who created it.

  2. The common memory area which is created in the webserver, which is common for all the users is k.led as App. Memory.

  3. Storing the data in this app.memory is k.ed App. state in State mngt. sys      

  4. .: The values stord by the webuser in the app memory, can be accessed by the other users also.                  

  5. The App State can store obj data types.

  6. App.State have to be used to store the Data which will be common for all the users of website.


---------------------------

All session variables are accessible to current user only.

Session variable are also of type object which means they can store any type of data (Load on server should be considered).

Session data will be stored @ server only & only session id travels. This data will be available as long as session is preserved by server. Sessions are normally ended based on timeout***.

In ASP.NET by default 20 min’s it the timeout (idle timeout) using configuration settings as well as programmatically with session object we can change this default time.

A session can be ended programmatically also. Session object has a method called Abandon () which kills the current session.

<system.web>

<SessionState timeout=”10”></SessionState>

-------------------------------

Untitled





Non.Persistent Cookies: These Cookies will be created in the browser's process area. They r not mentioned with Time duration. These Cookies will be destroyed when the app is closed

Persistent Cookies: The Cookies which are created & exists for a given time duration., is k.ld as the Persistent Cookie. They are created in the Client machine

Query string:                                                                                                                                                               Query string is Client side st.mngt sys. It can hold only strings. The Query string Memory will destroyed, when the app is closed.                                                                                                                                                The values Stored in Query string can be accessed from any page through out the app. In general Query string is used 2 carry small values from one to another page.

----------------------------

  1. Caching is the process of storing the page or objects in the cache memory of browse, proxy servers or webserver.      

  2. in general, caching is used to improve the performance i.e., the page or object that is cached will be accessed from the cache memory tor the next request with out fetching it from the db server.

  3. caching can be done at client side as well as server side.


These are 3 types of caching:

client side caching:

  • output page caching (or) entire page caching

  • fragment caching (or) partial page caching


server side caching:

  • data caching (or) object caching.


using system.web.caching;

//create{                                                                                                                                                                                                            CacheDependency cd = new Cache Dependency(Server.MapPath("XMLfile.xml"), Cache.Insert("key1",ds.Tables[0]),cd,DateTime.Now.AddMinutes(10),Cache.NoSlidingExpression);              }

//get{                                                                                                                                                                                         gv1.DataSource = (DataTable)Cache.Get("key1");                                                                                                                      gv1.DataBind();                                                                                                                                                                                             }

  1. Obj caching or data caching is server side State Management Sys.

  2. we can create this kind of caching in 2 cryterious



  • cache dependency: By using this, cache memory will be destroyed if the dependent file is modified.

  • cache expiration: By using this parameter, cache mem. will be destroyed with in a given time after the creation.


-----------------------------

Primary Key:
Primary Key enforces uniqueness of the column on which they are defined.
Primary Key creates a clustered index on the column.
Primary Key does not allow Nulls.

CREATE TABLE EMP (eID INT NOT NULL PRIMARY KEY,
eName VARCHAR(100) NOT NULL)

Alter table with Primary Key:
ALTER TABLE EMP
ADD CONSTRAINT pk_eID PRIMARY KEY (eID)

Unique Key:
Unique Key enforces uniqueness of the column on which they are defined.
Unique Key creates a non-clustered index on the column.
Unique Key allows only one NULL Value.

Alter table to add unique constraint to column:
ALTER TABLE EMP ADD CONSTRAINT UK_empName UNIQUE(empName)

25 January 2013

Create virtual files in asp

    private void virfile()
    {
        if (!Directory.Exists(Server.MapPath("download/")))
            Directory.CreateDirectory(Server.MapPath("download/"));
        string filpath = Server.MapPath("download/" + "data.txt");
        string filedir = filpath.Substring(0, filpath.LastIndexOf('.'));
        string fileext = System.IO.Path.GetExtension(filpath);
        if (!File.Exists(filpath))
        {
            File.AppendAllText(filpath, "file downloaded on : " + DateTime.Now.ToString() + "\r\n");
        }
        else
        {
            int i = 1;
            while (true)
            {
                filpath = filedir + "(" + i + ")" + fileext;
                if (!File.Exists(filpath))
                {
                    File.AppendAllText(filpath, "file downloaded on : " + DateTime.Now.ToString() + "\r\n");
                    break;
                }
                i++;
            }
        }
    }

20 January 2013

Image binary format c#

source:
    <div>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

        OnRowCommand="gv_command">

        <Columns>

            <asp:TemplateField HeaderText="files">

                <ItemTemplate>

                    <asp:LinkButton ID="l1" runat="server" Text='<%#Eval("filenam") %>' CommandArgument='<%#Eval("id") %>' CommandName="link"></asp:LinkButton>

                </ItemTemplate>

            </asp:TemplateField>

            <asp:TemplateField HeaderText="image">

                <ItemTemplate>

                    <asp:ImageButton ID="i1" runat="server" ImageUrl='<%#"Handler.ashx?id=" + Eval("id")  %>' CommandName="image" CommandArgument='<%#Eval("id") %>'

                    Visible='<%#Convert.ToString(Eval("isimage")).Trim()=="yes"?true:false %>' Height="50px" Width="50px" />

                </ItemTemplate>

            </asp:TemplateField>

        </Columns>

        </asp:GridView>

        <asp:FileUpload ID="FileUpload1" runat="server" />

        <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="b1_click"/><br />

        <asp:Image ID="Image1" runat="server" Height="300px" Width="300px"/>

    </div>


aspx.cs:



using System.Data.SqlClient;

using System.Data;

using System.IO;



    SqlConnection con = new SqlConnection("Data Source=.;database=db;UID=sa;Pwd=sa123");

    SqlDataAdapter da = new SqlDataAdapter();

    DataSet ds = new DataSet();

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack) {

            GetData();

        }

    }

    private void GetData()

    {

        da = new SqlDataAdapter("select * from upld order by id", con);

        ds = new DataSet();

        da.Fill(ds);

        GridView1.DataSource = ds;

        GridView1.DataBind();

    }

    protected void gv_command(object sender, GridViewCommandEventArgs e)

    {

        if (e.CommandName == "link")

        {

            string path = "";

            byte[] a = getbyte(e.CommandArgument.ToString(), out path);

 

            if (!File.Exists(Server.MapPath(path)))

                //File.Delete(Server.MapPath(path));

                File.WriteAllBytes(Server.MapPath(path), a);

            System.Diagnostics.Process.Start(Server.MapPath(path));

        }

        else if (e.CommandName == "image")

        {

            string path = "";

            byte[] a = getbyte(e.CommandArgument.ToString(), out path);

            string fil = path.Substring(path.LastIndexOf('.') + 1).ToUpper();

            string[] files = new string[] { "GIF", "PNG", "JPG", "BMP", "ICO" };

            if (files.Contains(fil))

            {

                MemoryStream ms = new MemoryStream(a);

                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms);

                if (!File.Exists(Server.MapPath("d/" + ds.Tables[0].Rows[0][1].ToString())))

                    //File.Delete(Server.MapPath("d/" + ds.Tables[0].Rows[0][1].ToString()));

                    bmp.Save(Server.MapPath("d/" + ds.Tables[0].Rows[0][1].ToString()), System.Drawing.Imaging.ImageFormat.Jpeg);

                Image1.ImageUrl = "d/" + ds.Tables[0].Rows[0][1].ToString();

            }

        }

    }

 

    byte[] getbyte(string s, out string p)

    {

        da = new SqlDataAdapter("select top 1 filebin,filenam from upld where id=" + s, con);

        ds = new DataSet();

        da.Fill(ds);

        string fil = ds.Tables[0].Rows[0][1].ToString().Substring(ds.Tables[0].Rows[0][1].ToString().LastIndexOf('.') + 1);

        p = "d/" + ds.Tables[0].Rows[0][1].ToString();

        return (byte[])ds.Tables[0].Rows[0][0];

    }

    protected void b1_click(object sender, EventArgs e) 

    {

        FileUpload1.PostedFile.SaveAs(Server.MapPath(FileUpload1.FileName));

        string sFileName = Server.MapPath(FileUpload1.FileName);

        byte[] fileData = File.ReadAllBytes(Server.MapPath(FileUpload1.FileName));

        SqlCommand cmd = new SqlCommand();

        cmd.Parameters.Add(new SqlParameter("@filenam", sFileName));

        cmd.Parameters.Add(new SqlParameter("@filebin", fileData));

 

        string fil = FileUpload1.PostedFile.ContentType.ToString();

        fil = fil.Substring(fil.LastIndexOf('/') + 1).ToUpper();

        string[] files = new string[] { "GIF", "PNG", "JPG", "BMP","ICO" };

        fil = files.Contains(fil) ? "yes" : "no";

 

        cmd.CommandText = "insert into upld(path,filebin,filenam,isimage) values(@filenam, @filebin,'" + FileUpload1.FileName + "','" + fil + "')";

        cmd.Connection = con;

        con.Open();

        cmd.ExecuteNonQuery();

        File.Delete(Server.MapPath(FileUpload1.FileName));

        GetData();

    }


ashx.cs:



using System.Data;

using System.Data.SqlClient;


public void ProcessRequest (HttpContext context)

{

    SqlConnection con = new SqlConnection("Data Source=.;database=db;UID=sa;Pwd=sa123");

        SqlDataAdapter da = new SqlDataAdapter();

        DataSet ds = new DataSet();

 

        da = new SqlDataAdapter("select top 1 filebin from upld where id=" + context.Request.QueryString["ID"].ToString(), con);

        ds = new DataSet();

        da.Fill(ds);

        context.Response.BinaryWrite((byte[])ds.Tables[0].Rows[0][0]);

}




db: with auto increment id


db


05 December 2012

Create a table named 'select' with column 'table'

SET QUOTED_IDENTIFIER ON
CREATE TABLE "SELECT" ("TABLE" int)

When SET QUOTED_IDENTIFIER is ON, all strings delimited by double quotation marks are interpreted as object identifiers. Therefore, quoted identifiers do not have to follow the Transact-SQL rules for identifiers. They can be reserved keywords and can include characters not usually allowed in Transact-SQL identifiers

Reference: http://msdn.microsoft.com/en-us/library/aa259228(v=sql.80).aspx

or

CREATE TABLE [SELECT] ([TABLE] INT)

06 October 2012

sort array of int values without using built-in functions (using Bubble sort)

string res = "";
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
for (int k = 0; k < arr.Length; k++)
{
for (int i = 0; i < arr.Length - 1; i++)
{
if (arr[i] > arr[i + 1])
{
int hold = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = hold;
}
}
res += arr[k].ToString();
arr[k] = arr[k];
}

string s = "1,2,3,,3,2";
string[] ss = (s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
for (int k = 1; k < ss.Length; k++)
{
for (int i = 0; i < (ss.Length - 1); i++)
{
if (Convert.ToInt32(ss[i].Trim()) > Convert.ToInt32(ss[i + 1].Trim()))
{
string hold = ss[i];
ss[i] = ss[i + 1];
ss[i + 1] = hold;
}
}
}
s = string.Join(",", ss);

04 October 2012

split string in c# with regular expression instead of forloop

string s = "er32(s),re4'wr(a),f2.0(t)A(y),(a)";
        s = Regex.Replace(s, @"[\w\s';.&,:]+\(([\w\d.]+)\)", "$1");
        Response.Write(s);

16 July 2012

array conversions

using System;
using System.Collections.Generic;
---------------------------
arraylist to array
> string[] a = (string[])arraylist.toarray(typeof(string));
> arraylist.copyto(array,0);
list to array
> string[] a = list.toarray();
---------------------------
arraylist to arraylist
> arraylist.addrange(arraylist);
---------------------------
array to arraylist
> arraylist.addrange(array);
> arraylist a = new arraylist(array);
array to list
> list<string> l = new list<string>(array)
> list<string> l = array.tolist();
---------------------------
array to array
> string[]  a = (string[])array.clone();// Clone method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array
---------------------------
array declaration and intilization methods
int[] a;
a = new int[3]{3,5,6};
int[] a = new int[]{3,4,5};
int[] a = new int[3]{3.4,5};
int[] a = new int[3];
a[0] = 2; a[1] = 3; a[2] = 4;
---------------------------
search arraylist
arraylist.sort();
arraylist.binaryseach(43);
arraylist.indexof(searchstr , 0);
---------------------------
string to bytearray
> byte[] = (new UnicodeEncoding()).GetBytes(stringToConvert);
---------------------------
bytearray to string
>char[] cs = new char[bs.Length];
for (int i = 0; i < cs.Length; ++i)
{
cs[i] = Convert.ToChar(bs[i]);
}
---------------------------

char array to string
string str = new string(chararray);

string to char array
string s = "hello";
char[] c = s.ToCharArray();
---------------------------

array to datatable

>DataTable dataTable = new DataTable();dataTable.LoadDataRow(array, true);//Pass array object to LoadDataRow methodreturn dataTable;
---------------------------
get array size
array.getlength(0).tostring();
array.getlowerbound(0).tostring();
---------------------------
better to use List instead of ArrayList
better to use Dictionary instead of HashTable

28 June 2012

clear all cotrol values of a page

<script type="text/javascript">
    function allclear()
    {    //debugger
        var elements=document.getElementsByTagName("INPUT");
        for(i=0;i<elements.length;i++)
            if(elements[i].type=="radio")
                elements[i].checked=false;
        for(i=0;i<elements.length;i++)
            if(elements[i].type=="checkbox")
                elements[i].checked=false;
        for(i=0;i<elements.length;i++)
           if (elements[i].type=="text")
                elements[i].value="";
        var elements1=document.getElementsByTagName("SELECT");
        for(i=0;i<elements1.length;i++)
            if(elements1[i].id!="" && elements1[i].id!=null)
                elements1[i].selectedIndex=0;
     }
</script>
---------------------------------------------------------------------------------------
private void ClearControls(Control c)
    {
        if (c.GetType() == typeof(System.Web.UI.WebControls.TextBox))
            ((TextBox)c).Text = "";
        if (c.GetType() == typeof(System.Web.UI.WebControls.RadioButtonList))
        {
            RadioButtonList rbtl = (RadioButtonList)c;
            for (int j = 0; j < rbtl.Items.Count; j++)
                rbtl.Items[j].Selected = false;
        }
        if (c.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
            ((DropDownList)c).SelectedIndex = 0;
        if (c.GetType() == typeof(System.Web.UI.WebControls.RadioButton))
            ((RadioButton)c).Checked = false;
        foreach (Control child in c.Controls)
            ClearControls(child);
}

------------------------------------------------------------------------------------------------------------------------

  private void DisableControls(Control c)
    {
        if ((c is TextBox) || (c is LinkButton) || (c is Button) || (c is CheckBox) || (c is CheckBoxList) || (c is RadioButtonList) || (c is DropDownList) || (c is Panel) || (c is ImageButton))
        {
            ((WebControl)c).Enabled = false;
        }
        foreach (Control child in c.Controls)
            DisableControls(child);
    }

make listbox items colorful

protected void Page_PreRender(object sender, EventArgs e)
{
    bool flag=false;
    foreach (ListItem li in ListBox1.Items)
    {
        if (flag)
        {
            li.Attributes.Add("class", "optred");
            flag = false;
        }
        else
        {
            li.Attributes.Add("class", "optblue");
            flag = true;
        }
    }
}
<style type="text/css">
.optred{background-color:red;}
.optblue{background-color:blue;} 
</style>

String formats

String strVal = "a(1), a1(2), a.3(3), a'4 (4), a.5:(5)";
Regex.Replace(strVal, @"[\w\s';.&,:]+\((\d+)\)", "$1") = 1,2,3,4,5
-----------------------------------------------------------------------
string dNum = "32.123456";
string.Format("{0:c}", double.Parse(dNum)) = $32.12
string.Format("{0:n}", double.Parse(dNum)) = 32.12
string.Format("{0:D}", DateTime.Now) = Thursday, June 28, 2012
string.Format("{0:T}", DateTime.Now) = 10:59:28 AM
DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") = 28/06/2012 10:59:28
---------------------------------------------------------------------------------
decimal dNum = decimal.Parse("32.12345");
Response.Write(dNum.ToString("0.00"));

01 June 2012

image file path to byte[] format

private byte[] imgStream(string filePath)
{
MemoryStream stream = new MemoryStream();
tryagain:
try
{ Bitmap bmp = new Bitmap(filePath);
  bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex) { goto tryagain; }
return stream.ToArray();
}

System.Drawing.ColorTranslator.FromHtml("#D8BFD8");

06 January 2012

sql syntaxes

Select Statement
SELECT "column_name" FROM "table_name"

Distinct
SELECT DISTINCT "column_name" FROM "table_name"

Where
SELECT "column_name" FROM "table_name" WHERE "condition"

And/Or
SELECT "column_name" FROM "table_name" WHERE "simple condition" {[AND|OR] "simple condition"}+

In
SELECT "column_name" FROM "table_name" WHERE "column_name" IN ('value1', 'value2', ...)

Between
SELECT "column_name" FROM "table_name" WHERE "column_name" BETWEEN 'value1' AND 'value2'

Like
SELECT "column_name" FROM "table_name" WHERE "column_name" LIKE {PATTERN}

Order By
SELECT "column_name" FROM "table_name" [WHERE "condition"] ORDER BY "column_name" [ASC,DESC]

Count
SELECT COUNT("column_name") FROM "table_name"

Group By
SELECT "column_name1", SUM("column_name2") FROM "table_name" GROUP BY "column_name1"

Having
SELECT "column_name1", SUM("column_name2") FROM "table_name" GROUP BY "column_name1" HAVING (arithematic function condition)

Create Table Statement
CREATE TABLE "table_name" ("column 1" "data_type_column_1", "column 2" "data_type_for_column_2",.... )

Drop Table Statement
DROP TABLE "table_name"

Truncate Table Statement
TRUNCATE TABLE "table_name"

Insert Into Statement
INSERT INTO "table_name" ("column1", "column2", ...) VALUES ("value1", "value2", ...)

Update Statement
UPDATE "table_name" SET "column_1" = [new value] WHERE {condition}

Delete From Statement
DELETE FROM "table_name" WHERE {condition}

select--scalar--string, update,insert,delete--nonquery--int

Ref: 

http://www.1keydata.com/sql/sql-syntax.html

http://www.sqlcommands.net/

02 January 2012

C# Features not in Java

•No automatic fall-through from one case block to the next

•Strongly-typed enums

•By reference calls are explicit at caller AND callee

•Method overrides are explicit

•Supports versioning

•Structs (value types)

•Integrated support for properties and events

•Can still use pointers with RAD language

Can share data and use functionality with components written in many different languages

Development tools and Documentation
—Server-side is well supported by both Java and .NET IDEs

—On the client-side .NET IDEs benefit from the fact that .NET CF is so close to .NET  (With Java there are separate IDEs for desktop and mobile application development)

—Compatibility problems between Java vendors

—Java IDEs are slow!

—C# is a richer/more complex language than Java

—Both Java and .NET have well documented API

—Web service documentation

—.NET - MSDN

—Java – Google

—Support for encryption of web services

—.Net CF: HTTPS and SOAP extensions

J2ME: HTTPS, but only in CDC & MIDP 2.0

C# and JAVA


CSharp and JAVA are two different Object Oriented Languages , both have some similarities and differences also . The Csharp and JAVA derived from their own single ancestor Class "Object". All Classes in C# are descended from System.Object Class and in JAVA all classes are subclasses of java.lang.Object Class.

Both C# and JAVA have their own runtime environments . C# source codes are compiled to Microsoft Intermediate Language (MSIL) and during the execution time runs it with the help of runtime environments - Common Language Runtime (CLR). Like that JAVA source codes are compiled to Java Byte Code and during the execution time runs it with the help of runtime environments - Java Virtual Machine (JVM). Both CSharp and JAVA supports native compilation via Just In Time compilers.

More over both C# and JAVA have their own Garbage Collector. In the case of keywords comparison some keywords are similar as well as some keywords are different also. The following are the examples of few similar and different keywords.

Similar Keywords examples

class , new , if , case , for , do , while , continue , int , char , double , null

 

17 November 2011

querystring n gv rows in javascript

query string in js: '<%=Request.QueryString["val"]%>';
--------------------------
gridrows in js: Totalrows = parseInt('<%= this.gv1.Rows.Count %>');
--------------------------
var rows = document.getElementById('gv').rows;
for(i=0;i <rows.length;i++)
{
   fd = rows[i].cells[4].innerText;
   rows[i].cells[4].style.display="none";
   rows[i].cells[8].style.display="none";
}

------------------------------------
<asp:Label ID="lblSno" runat="server" Text="<%# Container.DataItemIndex + 1%>"  />    ------------> to get the serial no for the gridview rows after bind the data (take the control to item template field of the grid)

24 October 2011

get datetime in user friendly (datetime convertion) in sqlserver

select convert (varchar(10), getdate(),101)
------------------------------------------
ddat = new Date();
ddat = new Date(ddat.setDate(new Date(stdate.value).getDate()+parseInt(days)));
var d=newdate.getDate();
var m=(newdate.getMonth()+1);
var y=newdate.getFullYear();
-----------------------------------------
day = new Date()
day = new Date("August15, 2006 08:25:00")
day = new Date(06,8,15)
day = new Date(06,8,15,8,25,0)

Ref: http://msdn.microsoft.com/en-us/library/ms187928.aspx with convertion chart

 

select convert(varchar, getdate(), 100) convertResult,100 style union
select convert(varchar, getdate(), 101),101 union
select convert(varchar, getdate(), 102),102 union
select convert(varchar, getdate(), 103),103 union
select convert(varchar, getdate(), 104),104 union
select convert(varchar, getdate(), 105),105 union
select convert(varchar, getdate(), 106),106 union
select convert(varchar, getdate(), 107),107 union
select convert(varchar, getdate(), 108),108 union
select convert(varchar, getdate(), 109),109 union
select convert(varchar, getdate(), 110),110 union
select convert(varchar, getdate(), 111),111 union
select convert(varchar, getdate(), 112),112 union
select convert(varchar, getdate(), 113),113 union
select convert(varchar, getdate(), 114),114  union
select convert(varchar, getdate(), 120),120  union
select convert(varchar, getdate(), 121),121  union
select convert(varchar, getdate(), 126),126  union
select convert(varchar, getdate(), 127),127  union
select convert(varchar, getdate(), 130),130  union
select convert(varchar, getdate(), 131),131
order by 2

 



























































































convertResultstyle
Mar 18 2016  5:27AM100
3/18/2016101
2016.03.18102
18/03/2016103
18.03.2016104
18-03-2016105
18-Mar-16106
18-Mar-16107
5:27:19108
Mar 18 2016  5:27:19:257AM109
3/18/2016110
3/18/2016111
20160318112
18 Mar 2016 05:27:19:257113
05:27:19:257114
3/18/2016 5:27120
27:19.3121
2016-03-18T05:27:19.257126
2016-03-18T05:27:19.257127
 9 ????? ??????? 1437  5:27:19130
 9/06/1437  5:27:19:257AM131

 

19 September 2011

Operator OverLoading in console apps

class ClsComplex
{
int R, I;
public ClsComplex(int R, int I)
{
this.R = R;
this.I = I;
Console.WriteLine("{0} + {1}i", R, I);
}
public static ClsComplex operator +(ClsComplex Num1, ClsComplex Num2)
{
ClsComplex Num3 = new ClsComplex(Num1.R + Num2.R, Num1.I + Num2.I);
return Num3;
}
}
class ClsOpOverLoad
{
static void Main(string[] args)
{
Console.Write("C1= ");
ClsComplex C1 = new ClsComplex(4, 5);
Console.Write("C2= ");
ClsComplex C2 = new ClsComplex(8, 2);
Console.Write("C3= ");
ClsComplex C3 = C1 + C2;
Console.Read();
}
}