Thursday, January 27, 2011

Remove Number from String

Code:
using System;
using System.Text.RegularExpressions;

class Program
{
/// <summary>
/// Remove digits from string.
/// </summary>
public static string RemoveDigits(string key)
{
return Regex.Replace(key, @"\d", "");
}

static void Main()
{
string input1 = "Dot123Net456Perls";
string input2 = "101Dalmatations";
string input3 = "4 Score";

string value1 = RemoveDigits(input1);
string value2 = RemoveDigits(input2);
string value3 = RemoveDigits(input3);

Console.WriteLine(value1);
Console.WriteLine(value2);
Console.WriteLine(value3);
}
}

A beautiful C# logical

A TextBox in the web page(It will show decimal), data store in database(no decimal). if input nothing, I will give the value "999999" to the database, if the input value is "4.56", I will give the value "456" to the database.
when I get the value from the database, if the database value is "999999", the TextBox will display null; if the database value is "456", then the TextBox will display 4.56".
That is the function:

Code:


public static string TotalBaselineMaximum(string MaximumAMT)
{
string tmpMaximumAMT = "";

if (MaximumAMT == "")
tmpMaximumAMT = "999999";
else if (MaximumAMT == "999999" || MaximumAMT == "0")
tmpMaximumAMT = "";
else
{
decimal dec;
dec = Convert.ToDecimal(MaximumAMT);
if (MaximumAMT.Contains("."))
tmpMaximumAMT = Math.Round(dec * 100).ToString();
else
tmpMaximumAMT = (dec / 100).ToString();
}

return tmpMaximumAMT;
}

Monday, January 24, 2011

Export Gridview

Code:

protected void OnClick_lbtnBack(object sender, EventArgs e)
{
string requestPage = Session["CAABackToPreviousPage"].ToString();
Response.Redirect(requestPage, true);
}

protected void OnClick_btnExport(object sender, EventArgs e)
{
//Export the GridView to Excel
//PrepareGridViewForExport(GridView1);
ExportGridView();
}

private void ExportGridView()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=ContestWinnerReport.csv");
Response.Charset = "";
Response.ContentType = "application/text";

//GridView1.AllowPaging = false;
//GridView1.DataBind();

StringBuilder sb = new StringBuilder();
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Columns[k].HeaderText + ',');
}
//append new line
sb.Append("\r\n");
int testint = GridView1.Rows.Count;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
if (k == 2)
sb.Append("'" + GridView1.Rows[i].Cells[k].Text + ',');
else
sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();

////GridView1.DataSource = Cache["ContestList"];
////GridView1.DataBind();
//GridView1.HeaderStyle.ForeColor = System.Drawing.Color.Black;
//string attachment = "attachment; filename=ContestWinnerReport.xls";
//Response.ClearContent();
//Response.AddHeader("content-disposition", attachment);
//Response.ContentType = "application/ms-excel";
////Response.ContentType = "application/text";
//StringWriter sw = new StringWriter();
//HtmlTextWriter htw = new HtmlTextWriter(sw);
//GridView1.RenderControl(htw);
//Response.Write(sw.ToString());
//Response.End();

//string attachment = "attachment; filename=Contacts.xls";
//Response.ClearContent();
//Response.AddHeader("content-disposition", attachment);
//Response.ContentType = "application/ms-excel";
//StringWriter sw = new StringWriter();
//HtmlTextWriter htw = new HtmlTextWriter(sw);

//// Create a form to contain the grid
//HtmlForm frm = new HtmlForm();
//GridView1.Parent.Controls.Add(frm);
//frm.Attributes["runat"] = "server";
//frm.Controls.Add(GridView1);

//frm.RenderControl(htw);
////GridView1.RenderControl(htw);
//Response.Write(sw.ToString());
//Response.End();
}

private void PrepareGridViewForExport(Control gv)
{
LinkButton lb = new LinkButton();
Literal l = new Literal();
string name = String.Empty;
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(LinkButton))
{
l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(CheckBox))
{
l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
PrepareGridViewForExport(gv.Controls[i]);
}
}
}

Extract Number from String

Code:

static string ExtractNumbers(string expr)
{
return string.Join(null, System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
}

Friday, January 14, 2011

C# Operator Overloading

All unary and binary operators have pre-defined implementations, that are automatically available in any expressions. In addition to this pre-defined implementations, user defined implementations can also be introduced in C#. The mechanism of giving a special meaning to a standard C# operator with respect to a user defined data type such as classes or structures is known as operator overloading. Remember that it is not possible to overload all operators in C#. The following table shows the operators and their overloadability in C#.

Operators Overloadability

+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.

+, -, !, ~, ++, –, true, false All C# unary operators can be overloaded.

==, !=, <, >, <= , >= All relational operators can be overloaded,but only as pairs.

&&, || They can’t be overloaded

() (Conversion operator) They can’t be overloaded

+=, -=, *=, /=, %= These compound assignment operators can be
overloaded. But in C#, these operators are
automatically overloaded when the respective
binary operator is overloaded.

=, . , ?:, ->, new, is, as, size of These operators can’t be overloaded

In C#, a special function called operator function is used for overloading purpose. These special function or method must be public and static. They can take only value arguments.The ref and out parameters are not allowed as arguments to operator functions. The general form of an operator function is as follows.

public static return_type operator op (argument list)
Where the op is the operator to be overloaded and operator is the required keyword. For overloading the unary operators, there is only one argument and for overloading a binary operator there are two arguments. Remember that at least one of the arguments must be a user-defined type such as class or struct type.

Overloading Unary Operators – the general form of operator function for unary operators is as follows.public static return_type operator op (Type t){// Statements}Where Type must be a class or struct.The return type can be any type except void for unary operators like +,~, ! and dot (.). but the return type must be the type of ‘Type’ for ++and o remember that the true and false operators can be overloaded only as pairs. The compilation error occurs if a class declares one of these operators without declaring the other.

The following program overloads the unary – operator inside the class Complex
Code:
// Unary operator overloading
// Author: rajeshvs@msn.com

using System;

class Complex
{
private int x;
private int y;
public Complex()
{
}
public Complex(int i, int j)
{
x = i;
y = j;
}

public void ShowXY()
{
Console.WriteLine("”{0} {1}”", x, y);
}

public static Complex operator -(Complex c)
{
Complex temp = new Complex();
temp.x = -c.x;
temp.y = -c.y;
return temp;
}
}

class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10, 20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex();
c2.ShowXY(); // displays 0 & 0
c2 = -c1;
c2.ShowXY(); // diapls -10 & -20
}
}


Overloading Binary Operators

An overloaded binary operator must take two arguments, at least one of them must be of the type class or struct, inwhich the operation is defined. But overloaded binary operators can return any value except the type void. The general form of a overloaded binary operator is as follows.

public static return_type operator op (Type1 t1, Type2 t2)
{
//Statements
}

A concrete example is given below

Code:
using System;

class Complex
{
private int x;
private int y;
public Complex()
{
}
public Complex(int i, int j)
{
x = i;
y = j;
}

public void ShowXY()
{
Console.WriteLine("”{0} {1}”", x, y);
}

public static Complex operator +(Complex c1, Complex c2)
{
Complex temp = new Complex();
temp.x = c1.x + c2.x;
temp.y = c1.y + c2.y;
return temp;
}
}

class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10, 20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex(20, 30);
c2.ShowXY(); // displays 20 & 30
Complex c3 = new Complex();
c3 = c1 + c2;
c3.ShowXY(); // dislplays 30 & 50
Console.ReadKey();
}
}


This article is from the link

Web Page Design tools for Debug

If you are a good web page developer, There are two useful tools, you need to know.

1. IE Developer Tools
Tools --> Developer Tools

2. FireFox
Firebug

Thursday, January 13, 2011

How to save web page as local file by C#

WebClient
Namespace: System.Net

The WebClient class provides common methods for sending data to or receiving data from any local, intranet, or Internet resource identified by a URI.

The WebClient class uses the WebRequest class to provide access to resources. WebClient instances can access data with any WebRequest descendant registered with the WebRequest.RegisterPrefix method.

Code:

protected void saveDataPsm(string fn, string url, string path2)
{
string sFileName = "c:\\Files\\test.txt";
//string sFileName = "c:\\Files\\test.txt";
WebClient myWebClient = new WebClient();
byte[] myDataBuffer = myWebClient.DownloadData(url);

using (FileStream fsNew = new FileStream(fn, FileMode.Create, FileAccess.Write))
{
fsNew.Write(myDataBuffer, 0, myDataBuffer.Length);
}
}


Thanks the post