Validate US Social Security Number

Posted by Venkat | Labels: ,

Here we have to discuss how to validate US Social security number


<asp:regularexpressionvalidator id="RegularExpressionValidator1" runat="server" validationexpression="\d{3}-\d{2}-\d{4}"
controltovalidate="TextBox1" errormessage="Input valid U.S. Social Security Number!"></asp:regularexpressionvalidator>

Disable past dates in Calendar control

Posted by Venkat | Labels:

Here we are going to see how to disable the past date in the Calendar contorl




<asp:Calendar ID="Calendar1" runat="server" OnDayRender="Calendar_DayRender"></asp:Calendar>

protected void Calender_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date < DateTime.Today.Date)
{
e.Day.IsSelectable = false;
}
}

Upload and show the images from database

Posted by Venkat | Labels: ,

Hi , Here we are going to see how to upload the image file to database ie : we store the image as a binary format in database.

create the table(name myImages) in sqlserver

with the following columns.

Img_Id --> datatype int (Primary Key with identity)

Image_Content --> datatype image

Image_Type --> datatype varchar(50)

Image_Size --> datatype bigint

Now create a page with name ImageUpload.aspx write the following code....

HtmlCode...


<asp:fileupload id="FileUpload1" runat="server">
<asp:button id="Button1" runat="server" onclick="Button1_Click" text="Button">
</asp:button></asp:fileupload>



CodeBehind..

protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);

SqlConnection myConnection = new SqlConnection(@"integrated security=yes;data source=.\sqlexpress;database=aaa");
SqlCommand storeimage = new SqlCommand("INSERT INTO myImages(Image_Content, Image_Type, Image_Size) values (@image, @imagetype, @imagesize)", myConnection);
storeimage.Parameters.Add("@image", SqlDbType.Image, myimage.Length).Value = myimage;
storeimage.Parameters.Add("@imagetype", SqlDbType.VarChar, 100).Value = FileUpload1.PostedFile.ContentType;
storeimage.Parameters.Add("@imagesize", SqlDbType.BigInt, 99999).Value = FileUpload1.PostedFile.ContentLength;

myConnection.Open();
storeimage.ExecuteNonQuery();
myConnection.Close();
}
}

To display the image....

Create one HttpHandler class with name Handler.ashx write the following code...


<%@ WebHandler Language="C#" Class="Handler" %> >

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

public class Handler : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
SqlConnection myConnection = new SqlConnection(@"integrated security=yes;data source=.\sqlexpress;database=aaa");
myConnection.Open();
string sql = "Select * from myImages where Img_Id=@ImageId";
SqlCommand cmd = new SqlCommand(sql, myConnection);
cmd.Parameters.Add("@ImageId", SqlDbType.Int).Value = context.Request.QueryString["id"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.ContentType = dr["Image_Type"].ToString();
context.Response.BinaryWrite((byte[])dr["Image_Content"]);
context.Response.End();
dr.Close();
myConnection.Close();

}

public bool IsReusable
{
get
{
return false;
}
}

}

and create one aspx file with name.... ImageDisplay.aspx

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%#"Handler.ashx?id="+Eval("Img_Id") %>' Height="100" Width="100" />
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Img_Id") %>'></asp:Label>
<asp:Label ID="Label2" runat="server" Text='<%#Eval("Image_Type") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = FetchAllImagesInfo();
GridView1.DataBind();
}
public DataTable FetchAllImagesInfo()
{
string sql = "Select * from myImages";
SqlDataAdapter da = new SqlDataAdapter(sql, @"integrated security=yes;data source=.\sqlexpress;database=aaa");
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}

Get filename without extension

Posted by Venkat | Labels:

To get the filename without extension

There's an existing method in the System.IO namespace which can return a file name without the extension. You can call this passing in either a full file path, or just a file name.

For example:


string fileName = System.IO.Path.GetFileNameWithoutExtension("building.jpg")

Get details error msg through email

Posted by Venkat | Labels:

Here we discuss how to get the html errormessage ie: yellow asp.net error message ie: show on stack trace if any error occurs in our project so we have to pass this msg to user through email.

we just get that Asp.net yellow error msg

this is the code

Exception err = Server.GetLastError();
Response.Clear();
HttpUnhandledException httpUnhEx = err as HttpUnhandledException;
if (httpUnhEx != null)
{
Response.Write("<h1>ASP.NET Error Page:
\n"+ httpUnhEx.GetHtmlErrorMessage());
}

how to pass if condition through the inline HTML Code

Posted by Venkat | Labels: ,

Here is the code we are passing the if condition through inline code..

ex:

Visible='<%# IIf((((Eval("productsize")).ToString().Length > 0) OrElse (Decimal.Parse(Eval("productsize
")) <= 0)), "true", "false") %>'

instead of using some function or procedure or by writing code on Gridview_Rowdatabound
just we simple pass the condition to make the control visible True or flase

Download a file from database

Posted by Venkat | Labels: ,

Hi , we have to discuss about how to download a file from the database , we generally upload a file to database in binary form so how to download that file that is going to see here..

suppose if i upload a file and bind the file detail in Gridview or datalist there i have give the Download link - here i am passing the id of the specific row so using this is i will retrieve the file.
so we pass the id to other page to make the file as download.



If Not Request.QueryString("id") Is Nothing Then
Dim As New SqlCommand("Select * from where download_id like @id", con)
Dim ID As New SqlParameter("@ID", SqlDbType.SmallInt, 2)
ID.Value = Request.QueryString("id")
ID.Direction = ParameterDirection.Input
cmd.Parameters.Add(ID)
cmd.Connection = con
con.Open()
Dim dRE As SqlDataReader
dRE = cmd.ExecuteReader()
While dRE.Read()
Dim myTitle As String = dRE.GetString(4).ToString 'document title
Dim myType As String = dRE.GetValue(5).ToString 'document type
If myTitle = "None" Or myType = "None" Then
message.Text = "No Attachements Present !"
Exit Sub
Else
Dim myDoc = dRE.GetSqlBinary(3) 'document


Response.Buffer = True
Response.Clear()
Response.AddHeader("content-disposition", "attachment; filename=" & myTitle)
'application/octet-stream
Select Case myType.ToLower
Case "doc"
Response.ContentType = "application/msword"
Case "docx"
Response.ContentType = "application/msword"
Case "ppt"
Response.ContentType = "application/vnd.ms-powerpoint"
Case "xls"
Response.ContentType = "application/x-msexcel"
Case "htm"
Response.ContentType = "text/HTML"
Case "html"
Response.ContentType = "text/HTML"
Case "jpg"
Response.ContentType = "image/JPEG"
Case "gif"
Response.ContentType = "image/GIF"
Case "pdf"
Response.ContentType = "application/pdf"
Case Else
Response.ContentType = "text/plain"
End Select
Response.BinaryWrite(myDoc.Value)
Response.Flush()
Response.Close()
If myDoc.isNull Then
message.Text &= "Retrieving File: " _
& myTitle & "." & myType & " Size: NULL
"
Else
message.Text &= "Retrieving File: " _
& myTitle & "." & myType & " Size: " & myDoc.ToString() & "
"
End If
End If
End While
con.Dispose()
con = Nothing
cmdDownloadDoc.Dispose()
cmdDownloadDoc = Nothing

End If
End Sub

Get Co-ordinates of the image onclick of the image

Posted by Venkat | Labels: ,

We discuss about how to get the co-ordinates of the image , while you click on the image at runtime
so using javascript we will get the x and y co-ordinates of the image
so using this we can wirte the text on that image ie: where we clicked on that image.

Already i have posted the article how to write text on image check the GDI Labels

Javascript


<script language="JavaScript">
function point_it(event){

var txtX=document.getElementById('<%= XTextBox.ClientID %>');
var txtY=document.getElementById('<%= YTextBox.ClientID %>');
pos_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById("pointer_div").offsetLeft;
alert(pos_x);


pos_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById("pointer_div").offsetTop;
alert(pos_y);
txtX.value=pos_x;
txtY.value=pos_y;

}
</script&gt;


HTML Code is

img id="pointer_div" onclick="point_it(event)" src ="../Availability/2_type_A.JPG"

X= asp:TextBox ID="XTextBox" runat="server"
Y= asp:TextBox ID="YTextBox" runat="server"

Generate a image on the fly

Posted by Venkat | Labels:

Here we have to discuss about how to create small rectangle with fill color and write text on image
for that you have to use some namespace

Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Text
Imports System.Drawing.Drawing2D

// Code behind file is

Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
Response.Clear() ' make sure Nothing has gone to the client
Dim imgOutput As New Bitmap(120, 30, PixelFormat.Format24bppRgb) ' create a New 24bit, 120x30 pixel image
Dim g As Graphics = Graphics.FromImage(imgOutput) ' create a New graphic object from the above bmp
' Application("intPageCount") += 1 ' really dumb page counter

g.Clear(Color.DarkGreen) ' blank the image
g.SmoothingMode = SmoothingMode.HighQuality ' antialias objects
' draw the number on the image canvas in verdana 10pt font bold
'g.DrawString("Count: " & Application("intPageCount"), New Font("verdana", 14, FontStyle.Bold), SystemBrushes.WindowText, New PointF(2, 2))
g.DrawString("A 2", New Font("verdana", 14, FontStyle.Bold), SystemBrushes.WindowText, New PointF(6, 6))
' draw a graduated fill across the image
g.FillRectangle(New LinearGradientBrush(New Point(0, 0), New Point(200, 200), Color.FromArgb(0, 0, 0, 0), Color.FromArgb(255, 255, 255, 255)), 0, 0, 120, 120)
imgOutput.Save(Response.OutputStream, ImageFormat.Jpeg) ' output to the user
' tidy up
g.Dispose()
imgOutput.Dispose()
Response.End()
End Sub

All the best

Write text on image

Posted by Venkat | Labels: ,

Here we have to discuss about how to write a text on image

this is the code written in Button_Click Event


Dim i As System.Drawing.Image = System.Drawing.Image.FromFile(Server.MapPath("~/Availability/2_type_A.JPG"))
Dim b As Drawing.Bitmap
b = Sold(i, i.Width, i.Height, "Sold", 100)
b.Save(Server.MapPath("~/Updated/2_type_A.JPG"), System.Drawing.Imaging.ImageFormat.Jpeg)


And also make sure you have store the image in different folder suppose if you getting the image form folder ie: Availability and once written the text on image store it on same folder Availability - this leads to error: Generic Error occured in GDI+. so you have to store it on differen folder
this is the functions which is going to write the text on image



Private Function Sold(ByVal resim As System.Drawing.Image, ByVal genislik As Integer, ByVal yukseklik As Integer, ByVal yazilacak As String, ByVal font As Single) As Bitmap
Dim resmim As New Bitmap(resim, genislik, yukseklik)
Dim graf As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(resmim)
Dim firca As System.Drawing.SolidBrush = New SolidBrush(System.Drawing.Color.Red)
Dim fnt As System.Drawing.Font = New Font("Verdana", font)
Dim size As System.Drawing.SizeF = New SizeF(400, 400) ' this is the size of the font ie: width and height
Dim coor As System.Drawing.PointF = New PointF(XTextBox.Text, YTextBox.Text) ' this is X and Y Co-ordinates where you going to write the text on image
Dim kutu As System.Drawing.RectangleF = New RectangleF(coor, size)
Dim sf As New StringFormat()
sf.FormatFlags = StringFormatFlags.NoWrap
graf.DrawString(yazilacak, fnt, firca, kutu, sf)
Return resmim
End Function



PayOffers.in