Tuesday, February 22, 2011

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);
}
}