Monday, September 26, 2011

A simple example GetPostBackEventReference

You can copy the code and test. Web page:
Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Pass Javascript Variables to Server</title>
     <script type="text/javascript">
         function SetHiddenVariable()
         {
            var jsVar = "dotnetcurry.com";
            __doPostBack('callPostBack', jsVar);
        }
        function Submit_Click() {
            var text = document.getElementById("TextArea1");
            __doPostBack("btnSubmit", text.value);
            return false;
        }
    </script>
</head>
 
<body>
    <form id="form1" runat="server">
    <div>   
        <asp:TextBox ID="txtJSValue" runat="server"></asp:TextBox><br />
        <textarea id="TextArea1" cols="20" rows="2"></textarea><br />
        <asp:Button ID="btnJSValue" Text="Click to retreive Javascript Variable"
            runat="server"/><br />
        <asp:Button ID="Button1" runat="server" Text="Button"  OnClientClick="return Submit_Click();" UseSubmitBehavior="false" />
    </div>
    </form>
</body>
</html>
Code Behind:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.ClientScript.GetPostBackEventReference(this, "arg");
        if (IsPostBack)
        {
            string eventTarget = this.Request["__EVENTTARGET"];
            string eventArgument = this.Request["__EVENTARGUMENT"];

            if (eventTarget != String.Empty && eventTarget == "callPostBack")
            {
                if (eventArgument != String.Empty)
                {
                    txtJSValue.Text = eventArgument;
                    //btnJSValue.Enabled = false;
                }
            }
            else if (eventTarget != String.Empty && eventTarget == "btnSubmit")
            { txtJSValue.Text = eventArgument; }
        }
        else
        {
            btnJSValue.Attributes.Add("onClick", "SetHiddenVariable();");
        }
    }
}

Thursday, August 4, 2011

3 Client Side Javascript sample



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>

<script type="text/javascript">

function displaymessage() {
alert("Hello World!");
}

function updatelabelcontrol(Lavell) {
var usename = $get("TextBox1").value;
var lb2 = $get("Label2").innerText;
var labella = $get("Label1");// $get(Lavell);
labella.innerHTML = usename+lb2; //"test";
}

function btn_Click() {
var usename = $get("TextBox1").value;
var lb2 = $get("Label2").value
var labell = $get("Label1");
labell.innerHTML = usename+lb2;
}

function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}

function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}

function checkCookie() {
var username = getCookie("username");
if (username != null && username != "") {
alert("Welcome again " + username);
}
else {
username = prompt("Please enter your name:", "");
if (username != null && username != "") {
setCookie("username", username, 365);
}
}
startTime();
}

function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
t = setTimeout('startTime()', 500);
}

function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}

</script>

</head>
<body onload="checkCookie()">
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div id="txt"></div>
<div>
<asp:Label ID="Label1" runat="server" Text="Label1" onclick='updatelabelcontrol(this)'></asp:Label>
<br />
<asp:Label ID="Label2" runat="server" Text="Label2"></asp:Label><br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="btn_Click()" />
<br />
<input type="button" value="Click me!" onclick="displaymessage()" />
</div>
</form>
</body>
</html>

Friday, June 3, 2011

Combining JQuery Form Validation and Ajax




<script src="scripts/jquery-1.4.4.js" type="text/javascript"></script>

<script src="scripts/jquery.popup.js" type="text/javascript"></script>

<script src="scripts/jquery.updnValidatorCallout.js" type="text/javascript"></script>


<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div class="textField">
<asp:TextBox Width="255px" ID="txbName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txbName"
ErrorMessage="Error: Contest Name is required."></asp:RequiredFieldValidator></div>
<p>
</p>
<asp:Button ID="btnSave" Text="Save" Class="submitBTN" runat="server" OnClick="btnSaveNew_Click" />

<script type="text/javascript">
$(document).ready(function() {

$.updnValidatorCallout.attachAll();
});
</script>

Wednesday, May 11, 2011

An MYSQL Statement that gets the last Thursday in the month

Here is a simplified version using just date math:

SELECT LAST_DAY(NOW()) - ((7 + WEEKDAY(LAST_DAY(NOW())) - 5) % 7);

Tuesday, March 29, 2011

Using Table-Valued Function in MS SQL

Code:
-- SET NOCOUNT ON 

CREATE FUNCTION DatesBetween2()
RETURNS @dates TABLE (
DateValue date NOT NULL PRIMARY KEY CLUSTERED
)
as
begin
DECLARE @startDate DATETIME = GETDATE();
DECLARE @endDate DATETIME = DATEADD(day, 9999, GETDATE());
BEGIN
WHILE (@startDate <= @endDate) BEGIN
INSERT INTO @dates VALUES (@startDate);
SET @startDate = DATEADD(day, 1, @startDate);
END;
RETURN;
END;
END;

select * from dbo.DatesBetween2()

Thursday, March 17, 2011

What is message queuing?

Message queuing has been used in data processing for many years. It is most commonly used today in electronic mail. Without queuing, sending an electronic message over long distances requires every node on the route to be available for forwarding messages, and the addressees to be logged on and conscious of the fact that you are trying to send them a message. In a queuing system, messages are stored at intermediate nodes until the system is ready to forward them. At their final destination they are stored in an electronic mailbox until the addressee is ready to read them.

Even so, many complex business transactions are processed today without queuing. In a large network, the system might be maintaining many thousands of connections in a ready-to-use state. If one part of the system suffers a problem, many parts of the system become unusable.

You can think of message queuing as being electronic mail for programs. In a message queuing environment, each program from the set that makes up an application suite is designed to perform a well-defined, self-contained function in response to a specific request. To communicate with another program, a program must put a message on a predefined queue. The other program retrieves the message from the queue, and processes the requests and information contained in the message. So message queuing is a style of program-to-program communication.
Queuing is the mechanism by which messages are held until an application is ready to process them. Queuing allows you to:

* Communicate between programs (which might each be running in different environments) without having to write the communication code.
* Select the order in which a program processes messages.
* Balance loads on a system by arranging for more than one program to service a queue when the number of messages exceeds a threshold.
* Increase the availability of your applications by arranging for an alternative system to service the queues if your primary system is unavailable.

How to: Access Binary Data as a Stream (WCF Data Services/Silverlight)

Silverlight

Open Data Protocol (OData) enables a data service to make binary data available outside of the feed itself. This binary data, called a media resource, is separate from but related to an entity, which is called a media link entry. For more information, see Working with Binary Data (WCF Data Services).

The procedure and examples in this topic show you how to add a reference to the Northwind streaming sample data service and call the GetReadStream(Object) method to retrieve binary data as a stream from an OData service.

The streaming data service accessed by the application is a special version of the Northwind sample data service that has been modified to support streaming. For more information see Streaming Provider (WCF Data Services). The Northwind streaming data service sample can be downloaded from the MSDN Code Gallery Web site.

Check the following link:
http://msdn.microsoft.com/en-us/library/ff602281%28v=VS.95%29.aspx

Tuesday, March 8, 2011

Generates Random Numbers

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{

public class MersenneTwister
{
// Class MersenneTwister generates random numbers
// from a uniform distribution using the Mersenne
// Twister algorithm.
private const int N = 624;
private const int M = 397;
private const uint MATRIX_A = 0x9908b0dfU;
private const uint UPPER_MASK = 0x80000000U;
private const uint LOWER_MASK = 0x7fffffffU;
private const int MAX_RAND_INT = 0x7fffffff;
private uint[] mag01 = { 0x0U, MATRIX_A };
private uint[] mt = new uint[N];
private int mti = N + 1;

public MersenneTwister()
{ init_genrand((uint)DateTime.Now.Millisecond); }
public MersenneTwister(int seed)
{
init_genrand((uint)seed);
}
public MersenneTwister(int[] init)
{
uint[] initArray = new uint[init.Length];
for (int i = 0; i < init.Length; ++i)
initArray[i] = (uint)init[i];
init_by_array(initArray, (uint)initArray.Length);
}

public static int MaxRandomInt
{ get { return 0x7fffffff; } }

public int Next()
{ return genrand_int31(); }
public int Next(int maxValue)
{ return Next(0, maxValue); }
public int Next(int minValue, int maxValue)
{
if (minValue > maxValue)
{
int tmp = maxValue;
maxValue = minValue;
minValue = tmp;
}
return (int)(Math.Floor((maxValue - minValue + 1) * genrand_real1() +
minValue));
}

public float NextFloat()
{ return (float)genrand_real2(); }
public float NextFloat(bool includeOne)
{
if (includeOne)
{
return (float)genrand_real1();
}
return (float)genrand_real2();
}
public float NextFloatPositive()
{ return (float)genrand_real3(); }
public double NextDouble()
{ return genrand_real2(); }
public double NextDouble(bool includeOne)
{
if (includeOne)
{
return genrand_real1();
}
return genrand_real2();
}

public double NextDoublePositive()
{ return genrand_real3(); }
public double Next53BitRes()
{ return genrand_res53(); }
public void Initialize()
{ init_genrand((uint)DateTime.Now.Millisecond); }
public void Initialize(int seed)
{ init_genrand((uint)seed); }
public void Initialize(int[] init)
{
uint[] initArray = new uint[init.Length];
for (int i = 0; i < init.Length; ++i)
initArray[i] = (uint)init[i];
init_by_array(initArray, (uint)initArray.Length);
}
private void init_genrand(uint s)
{
mt[0] = s & 0xffffffffU;
for (mti = 1; mti < N; mti++)
{
mt[mti] =
(uint)(1812433253U * (mt[mti - 1] ^ (mt[mti - 1] >> 30)) + mti);
mt[mti] &= 0xffffffffU;
}
}
private void init_by_array(uint[] init_key, uint key_length)
{
int i, j, k;
init_genrand(19650218U);
i = 1; j = 0;
k = (int)(N > key_length ? N : key_length);
for (; k > 0; k--)
{
mt[i] = (uint)((uint)(mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1664525U
)) + init_key[j] + j);
mt[i] &= 0xffffffffU;
i++; j++;
if (i >= N) { mt[0] = mt[N - 1]; i = 1; }
if (j >= key_length) j = 0;
}
for (k = N - 1; k > 0; k--)
{
mt[i] = (uint)((uint)(mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) *
1566083941U)) - i);
mt[i] &= 0xffffffffU;
i++;
if (i >= N) { mt[0] = mt[N - 1]; i = 1; }
}
mt[0] = 0x80000000U;
}

uint genrand_int32()
{
uint y;
if (mti >= N)
{
int kk;
if (mti == N + 1)
init_genrand(5489U);
for (kk = 0; kk < N - M; kk++)
{
y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
mt[kk] = mt[kk + M] ^ (y >> 1) ^ mag01[y & 0x1U];
}
for (; kk < N - 1; kk++)
{
y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
mt[kk] = mt[kk + (M - N)] ^ (y >> 1) ^ mag01[y & 0x1U];
}
y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
mt[N - 1] = mt[M - 1] ^ (y >> 1) ^ mag01[y & 0x1U];
mti = 0;
}
y = mt[mti++];
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680U;
y ^= (y << 15) & 0xefc60000U;
y ^= (y >> 18);
return y;
}
private int genrand_int31()
{ return (int)(genrand_int32() >> 1); }
double genrand_real1()
{ return genrand_int32() * (1.0 / 4294967295.0); }
double genrand_real2()
{ return genrand_int32() * (1.0 / 4294967296.0); }
double genrand_real3()
{ return (((double)genrand_int32()) + 0.5) * (1.0 / 4294967296.0); }
double genrand_res53()
{
uint a = genrand_int32() >> 5, b = genrand_int32() >> 6;
return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0);
}
}
public class Program
{
static void Main()
{
MersenneTwister randGen = new MersenneTwister();
Console.WriteLine("100 uniform random integers in [0,{0}]:", MersenneTwister.MaxRandomInt);
int i;

for (i = 0; i < 100; ++i)
{
Console.Write("{0} ", randGen.Next());
if (i % 5 == 4) Console.WriteLine("");
}
Console.WriteLine("100 uniform random doubles in [0,1]:");
for (i = 0; i < 100; ++i)
{
Console.Write("{0} ", randGen.NextDouble().ToString("F8"));
if (i % 5 == 4) Console.WriteLine("");
}
Console.WriteLine("Press ENTER to quit");
Console.ReadLine();
}
}
}

Thursday, March 3, 2011

C# COPY AND RENAME

Copy file from one folder to another folder, add different prefix to all file.

Code:

using System;
using System.IO;


namespace IOProject
{
class Class1
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Please enter the name of the folder you want to create or use");
// store the folder name in the dirName variable
//string dirName = Console.ReadLine();
string dirName = @"C:\stephen wu\tools\audioBible";
// create the DirectoryInfo instance
//DirectoryInfo dInfo = new DirectoryInfo(@"F:" + dirName);
DirectoryInfo dInfo = new DirectoryInfo(dirName);
string targetDirectory = @"C:\stephen wu\tools\audio2";
DirectoryInfo[] subDirs = dInfo.GetDirectories();
if (subDirs.Length > 0)
{
Console.WriteLine("Directories:");
foreach (DirectoryInfo subDir in subDirs)
{
Console.WriteLine(" " + subDir.Name);

int atmp = subDir.Name.IndexOf("a");
string l4string = subDir.Name.Substring(0, atmp+1);
//l4string = l4string + "_";

Console.WriteLine(" " + l4string);

string sourceDirectory = @"C:\stephen wu\tools\audioBible\" + subDir.Name;
Rename(sourceDirectory,targetDirectory, l4string);
Console.WriteLine(" " + sourceDirectory);
}
}

}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.ReadLine();
}
}

public static void Rename(string sourceDirectory, string targetDirectory, string Prefixtmp)
{
DirectoryInfo di = new DirectoryInfo(sourceDirectory);
if (di != null)
{

FileInfo[] subFiles = di.GetFiles();
if (subFiles.Length > 0)
{
Console.WriteLine("Files:");
foreach (FileInfo subFile in subFiles)
{
Console.WriteLine(" " + subFile.Name + " (" + subFile.Length + " bytes)");

string newname = targetDirectory + "\\" + Prefixtmp + subFile.Name.ToString();
string oldname =sourceDirectory+"\\"+subFile.Name.ToString();
File.Copy(oldname, newname);
}
}
//Console.ReadKey();
}
}
}
}

Tuesday, February 22, 2011

How to increase the upload file length limit in ASP.NET

Generally, the uploading limit of ASP.NET FileUploader is 4MB. But you can increase the limit of length of uploaded file by using the following code into your web.config file in your website.

Code:
<httpruntime maxrequestlength="20480" executiontimeout="600">
</httpruntime>


You have to add this tag after the system.web of your web.config file...
If you want to increase the upload limit more than 20MB, then you have to change both the value of maxRequestLength in KB and also executionTimeout.

MSSQL Delete Duplicates from table

Physical Location

-- 2005
SELECT %%LockRes%%, * FROM MyTable

-- 2008
SELECT %%physloc%%, * FROM MyTable

Wednesday, February 16, 2011

Send Email by Gmail

Code:

public void SendEmailByGmail()
{
MailMessage mail = new MailMessage();
mail.To.Add("your@gmail.com");
mail.To.Add("recever@yahoo.com");
mail.From = new MailAddress("your@gmail.com");
mail.Subject = "Email using Gmail";

string Body = "Hi, this mail is to test sending mail" + "using Gmail in ASP.NET";
mail.Body = Body;

mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.NetNetworkCredential("YourUserName@gmail.com", "YourGmailPassword");//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);
}

Friday, February 4, 2011

Pass Multiple Values from a GridView to Another Page using ASP.NET

Code:
<body>
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">
</asp:SqlDataSource>

</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"
DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="CustomerID"
DataNavigateUrlFormatString="CustomerDetails.aspx?CID={0}"
Text="Pass Single Value" />
<asp:HyperLinkField DataNavigateUrlFields="CustomerID, CompanyName, ContactName, Address, City"
DataNavigateUrlFormatString="CustomerDetails.aspx?CID={0}&CName={1}&ContactName={2}&Addr={3}&City={4}"
Text="Pass Multiple Values" />
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
<asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
</Columns>
</asp:GridView>
</form>
</body>



Code:
C#
protected void Page_Load(object sender, EventArgs e)
{
string cid = Request.QueryString["CID"];
string cname = Request.QueryString["CName"];
string contactName = Request.QueryString["ContactName"];
string address = Request.QueryString["Addr"];
string city = Request.QueryString["City"];
}

Thursday, February 3, 2011

How to show/hide column in GridView by different ways

How to show/hide column in GridView

1. To hide a column just set the width to 0. To show it again set the width to auto.
Code:

GridView1.Columns[0].ItemStyle.Width = 0;


2. Hide the column
Code:
        GridView1.Columns[6].Visible = false;


3. Different way to Hide the columns
Code:

protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Index of column to be hide
e.Row.Cells[0].Visible = false;

}
if (e.Row.RowType == DataControlRowType.Header)
{
// Index of column to be hide
e.Row.Cells[0].Visible = false;
}
}

Wednesday, February 2, 2011

Display the image on the page

Code:
<%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 picid;
if (context.Request.QueryString["id"] != null)
picid = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");

context.Response.ContentType = "image/jpeg";
Stream strm = ShowAlbumImage(picid);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);

while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}

public Stream ShowAlbumImage(int picid)
{
string conn = ConfigurationManager.ConnectionStrings["albumConnString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT pic FROM Album WHERE Pic_ID = @ID";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", picid);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}

public bool IsReusable
{
get
{
return false;
}
}
}

Tuesday, February 1, 2011

Image Resize and Upload



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileImage" runat="server" />

<asp:CustomValidator ID="valFile" runat="server"
ErrorMessage="No file uploaded"
onservervalidate="valFile_ServerValidate" Display="Dynamic" />
<asp:CustomValidator ID="valFileType" runat="server"
ErrorMessage="This isn't not an image"
onservervalidate="valFileType_ServerValidate" Display="Dynamic" />
<asp:CustomValidator ID="valFileSize" runat="server"
ErrorMessage="The image exceeds 10 MB"
onservervalidate="valFileSize_ServerValidate" Display="Dynamic" /><br />

<asp:Button ID="btnSubmit" runat="server" Text="Upload"
onclick="btnSubmit_Click" />
</div>
</form>
</body>
</html>


Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void valFile_ServerValidate(object source, ServerValidateEventArgs args)
{
if (!fileImage.HasFile)
{
args.IsValid = false;
}
}

protected void valFileType_ServerValidate(object source, ServerValidateEventArgs args)
{
if (fileImage.HasFile)
{
string[] acceptedTypes = new string[]
{
"image/bmp",
"image/jpeg",
"image/tiff",
"image/gif",
"image/png"
};

if (!acceptedTypes.Contains(fileImage.PostedFile.ContentType))
{
args.IsValid = false;
}
}
}

protected void valFileSize_ServerValidate(object source, ServerValidateEventArgs args)
{
if (IsValid)
{
int maxSize = 5 * 1024 * 1024;
if (fileImage.PostedFile.ContentLength > maxSize)
{
args.IsValid = false;
}
}
}


protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValid)
{
Bitmap image = ResizeImage(fileImage.PostedFile.InputStream, 200, 400);
image.Save(Server.MapPath("~/Photos/") + Guid.NewGuid().ToString() + ".jpg", ImageFormat.Jpeg);

image.Dispose();
}
}

private Bitmap ResizeImage(Stream streamImage, int maxWidth, int maxHeight)
{
Bitmap originalImage = new Bitmap(streamImage);
int newWidth = originalImage.Width;
int newHeight = originalImage.Height;
double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;

if (aspectRatio <= 1 && originalImage.Width > maxWidth)
{
newWidth = maxWidth;
newHeight = (int)Math.Round(newWidth / aspectRatio);
}
else if (aspectRatio > 1 && originalImage.Height > maxHeight)
{
newHeight = maxHeight;
newWidth = (int)Math.Round(newHeight * aspectRatio);
}

Bitmap newImage = new Bitmap(originalImage, newWidth, newHeight);

Graphics g = Graphics.FromImage(newImage);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);

originalImage.Dispose();

return newImage;
}

}

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

Wednesday, January 12, 2011

What is BOM?

Bill of materials (BOM) is the term used to describe the raw materials, sub-assemblies, intermediate assemblies, sub-components, components, parts and the quantities of each needed to manufacture a final product.[1] It may be used for communication between manufacturing partners,[2] or confined to a single manufacturing plant.

A BOM can define products as they are designed (engineering bill of materials), as they are ordered (sales bill of materials), as they are built (manufacturing bill of materials), or as they are maintained (service bill of materials). The different types of BOMs depend on the business need and use for which they are intended. In process industries, the BOM is also known as the formula, recipe, or ingredients list. In electronics, the BOM represents the list of components used on the printed wiring board or printed circuit board. Once the design of the circuit is completed, the BOM list is passed on to the PCB layout engineer as well as component engineer who will procure the components required for the design.

BOMs are hierarchical in nature with the top level representing the finished product which may be a sub-assembly or a completed item. BOMs that describe the sub-assemblies are referred to as modular BOMs. An example of this is the NAAMS BOM that is used in the automative industry to list all the components in an assembly line. The structure of the NAAMS BOM is System, Line, Tool, Unit and Detail.

The first hierarchical databases were developed for automating bills of materials for manufacturing organizations in the early 1960s.[3]

A bill of materials "implosion" links component pieces to a major assembly, while a bill of materials "explosion" breaks apart each assembly or sub-assembly into its component parts.

A BOM can be displayed in the following formats:


  • A single-level BOM that displays the assembly or sub-assembly with only one level of children. Thus it displays the components directly needed to make the assembly or sub-assembly.[4][5]


  • An indented BOM that displays the highest-level item closest to the left margin and the components used in that item indented more to the right.[1]

  • Modular (planning) BOM A BOM can also be visually represented by a product structure tree, although they are rarely used in the workplace.[1]

See also
  • Bill of quantities (BOQ)
  • Bill of resources (BOR)
  • Configurable BOM (CBOM)
  • Enterprise resource planning (ERP)
  • Manufacturing resource planning (MRP II)
  • Material Requirements Planning (MRP)
  • Product data management (PDM)


References

  1. ^a b c Reid, R. Dan; Sanders, Nada R. (2002). Operations Management. John Wiley & Sons, 457-458. ISBN 0-471-32011-0.
  2. ^"In Search of the Perfect Bill of Materials (BoM)" (PDF). National Electromnics Manufacturing Inititative Inc. (March 2002). Retrieved on 2008-09-28. "As the primary conduit for data transfer among manufacturing partners, the BoM is central to the product life cycle from the very beginning."
  3. ^ "Bill of Materials". The Free Dictionary. Retrieved on 2008-09-28.
  4. ^ "Single Vs. Multi-Level BOMs". Popular Q&A, Oracle Knowledge Base. Oracle (2003-07-30). Retrieved on 2008-10-26.
  5. ^ "Bill of Materials". Inventory Interface. Retrieved on 2008-10-26.