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



setfocus on control

Posted by Venkat | Labels:

Here is the code to set focus on some control , while we use the Master page

ScriptManager.RegisterStartupScript(Me, Me.GetType(), "Focus", String.Format("window.setTimeout('$get(""{0}"").focus()', 300);", ControlToFocus.ClientID), True)

or Refer this article

http://www.dotnetcurry.com/ShowArticle.aspx?ID=275

Messagebox in Vb.Net

Posted by Venkat | Labels:

Showing messagebox like yes , no in vb.net and proceed if yes else exit ..

       Dim button As DialogResult

button = MessageBox.Show _
("Are you sure you want to exit this application?", _
"Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)

If button = Windows.Forms.DialogResult.Yes Then
Me.Close()
Else
'Do Nothing
End If

Show dates on different format through Query

Posted by Venkat | Labels: ,

Here the number of way to show the date ie: extract from the SQL query

select convert(varchar,getdate(),101)
OutPut:- 06/18/2008

select convert(varchar,getdate(),102)
OutPut:- 2008.06.18

select convert(varchar,getdate(),103)
OutPut:- 18/06/2008

select convert(varchar,getdate(),104)
OutPut:- 18.06.2008

select convert(varchar,getdate(),105)
OutPut:- 18-06-2008

select convert(varchar,getdate(),106)
OutPut:- 18 Jun 2008

select convert(varchar,getdate(),107)
OutPut:- Jun 18, 2008

select convert(varchar,getdate(),108)
OutPut:- 10:53:20

select convert(varchar,getdate(),109)
OutPut:- Jun 18 2008 10:53:30:507AM

select convert(varchar,getdate(),110)
OutPut:- 06-18-2008

select convert(varchar,getdate(),111)
OutPut:- 2008/06/18

select convert(varchar,getdate(),112)
OutPut:- 20080618

select convert(varchar,getdate(),113)
OutPut:- 18 Jun 2008 10:54:01:253

select convert(varchar,getdate(),114)
OutPut:- 10:54:08:473

select convert(varchar,getdate(),120))
OutPut:- 2008-06-18 10:54:15 
For Further Reference : http://www.sql-server-helper.com/tips/date-formats.aspx

Could not load file or Assembly

Posted by Venkat | Labels:


Hi, if you got error like this..Could not load file or Assembly for While you adding AjaxToolkit.dll

You have update your ajaxtoolkit from Codeplex.com

Here the link


http://www.codeplex.com/AjaxControlToolkit/Release/ProjectReleases.aspx?ReleaseId=8513

Avoid execution of code while you refresh the page

Posted by Venkat | Labels:

Hi , here we have to discuss the how to avoid the execution of code While you refresh the page.. suppose if you have written the code for sending email to users.. after clicking the button the code has been executed suppose if you , Refresh the same page once again the Email sent to the user so here we have to avoid

the execution on code on page_Refresh
this is the code in VB.NET and C#

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
Session("CheckRefresh") = Server.UrlDecode(System.DateTime.Now.ToString())
End If
End Sub


Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
If Session("CheckRefresh").ToString() = ViewState("CheckRefresh").ToString() Then
Label1.Text = "Hello"
Session("CheckRefresh") = Server.UrlDecode(System.DateTime.Now.ToString())
Else
Label1.Text = "Page Refreshed"
End If

End Sub

Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs)
ViewState("CheckRefresh") = Session("CheckRefresh")
End Sub


Here in this code i m saving system date and time in session varaible when the page gets load
and in the page prerender event , which occurs after page_Load event , i am
assigning the value if session variable to viewstate varaible

Now in Button_Click Event i m checking if both the values in session
variable and in ViewState varaible are same than page in not refreshed
if they are not same that means page has got refreshed

This is code for C#.NET


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
}
}


protected void Button1_Click(object sender, EventArgs e)
{
if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
{
Label1.Text = "Hello";
Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
}
else
{
Label1.Text = "Page Refreshed";
}

}

protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["CheckRefresh"] = Session["CheckRefresh"];
}

Upload Large files using asp.net

Posted by Venkat | Labels:

To upload large files in asp.net you have to increase the MaxrequestLength and Executiontimeout of the httpruntime settings of your web.config file.By Default it will upload 4MB

suppose if i want to upload upto 8 MB you have to include this tag in you web.config file , don't change anything in your machine.config files.

httpruntime  maxRequestLength="1048576" executionTimeout="450"


here 1048576 - 1 GB

Validation for FileUploadControl

Posted by Venkat | Labels: ,

To validate the fileupload control use Custom Validator and call this function on ClientValidateFunction property of Custom validator.

You can pass the file extension , Watever you want to allow..

function ValidateSFrontImageUpload(Source, args)
{
var fuData = document.getElementById('<%= FrontSImage_FileUpload.ClientID %>');
var FileUploadPath = fuData.value;

if(FileUploadPath =='')
{
// There is no file selected
args.IsValid = false;
}
else
{
var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();

if (Extension == "jpg" || Extension == "jpeg" || Extension == "png" || Extension == "gif")
{
args.IsValid = true; // Valid file type
}
else
{
args.IsValid = false; // Not valid file type
}
}
}

Code for Logout button

Posted by Venkat | Labels:

If you are not using master pages then you have to paste this code of all the pages (on load event).


Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();

On logout

You have to write

Session.Abandon();
Session.Clear();

Use If condition inside the Gridiview or Datalist

Posted by Venkat | Labels:

Here the Html Code , html was not allowed here so i have conver < - &lt and > - &gt


&lt asp
:HyperLink ID="HyperLink1" Visible=" &lt %# isFilePathEmpty(Eval("filepath")) % &gt " NavigateUrl="~/AddPost.aspx?ForumID=18#" runat="server" &gt
&lt %# Eval("PartNumber") &gt
&lt /asp:HyperLink &gt

then create a method called isFilePathEmpty(string filePath) in the code behind which returns a boolean.

Validation of ViewSate MAC Failed

Posted by Venkat | Labels:

If you are getting this error .

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster

Write the below code..

Update your web.config with following attributes.

pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" enableViewStateMac="false"

Setting default button by using panel

Posted by Venkat | Labels: ,

Here We have to discuss about how to set the default button in Masterpage
for ex: in Master i have Search_textbox and Search_button when the user enter some text in the Textbox and pres Enter so the Search_button should trigger..

Html Code

<asp:Panel ID="SearchStyle_Panel" runat="server" width="100%">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                              <td width="188" align="right" valign="middle" class="white_text">
                                   SEARCH
                              </td>
                               <td width="235" align="right" valign="middle">
                                   <asp:TextBox ID="search_textbox" runat="server" value="ENTER KEYWORD" onfocus="if (this.value == 'ENTER KEYWORD') {this.value = '';}"
                                      onblur="if (this.value == '') {this.value = 'ENTER KEYWORD';}" CssClass="textbox"></asp:TextBox>
                               </td>
                             <td width="5" align="right" valign="middle">
                          </td>
                           <td width="40" align="right" valign="bottom">
                                 <asp:Button ID="search_button" runat="server" Text="GO" CssClass="go_btn"/>
                              </td>
                           </tr>
                      </table>
                     </asp:Panel>

since the button is nested inside of a control that implememts INamingContainer, its UniqueId will not match its server ID

for that reason, you should set the DefaultButton property in code.

myPanel.DefaultButton = myButton.UniqueId

then on page_load

SearchStyle_Panel.DefaultButton = search_button.UniqueID

Publish a Web project

Posted by Venkat | Labels:

Here we are going to see how to publish a web site project . While doing so , you can convert to assemblies, also on you published website folder it contains only .aspx file you cant able to view the code behind file (.aspx.vb , .ascx.vb , .vb , .cs files)

This is for the Security purpose no one able to modify you code..

these are the steps :
  1. On the Build menu, click Publish Web Site.
  2. In the Publish Web Site dialog box, click the ellipsis button (…) to browse to the location to which you want to publish the Web site.
    You can write the Web site output to a local or shared folder, to an FTP site, or to a Web site that you access with a URL. You must have Create and Write permissions in the target location.
  3. To be able to change the layout (but not the code) of .aspx files after publishing the Web site, select the Allow this precompiled site to be updateable check box.
  4. To name strongly named assemblies using a key file or a key container, select the Enable strong naming on precompiled assemblies check box, and then click OK.
    Publishing status is displayed in the taskbar. Depending on the connection speed, the size of the site and the types of content files, publishing time can vary. When publishing is completed, the status of Publish succeeded is displayed.
  5. Make any configuration changes that are necessary for your site. For more information, see How to: Configure Published Web Sites. You might also want to encrypt specific configuration settings. For more information, see Encrypting Configuration Information Using Protected Configuration.
Ref : 
http://msdn.microsoft.com/en-us/library/20yh9f1b(VS.80).aspx
http://msdn.microsoft.com/en-us/library/1y1404zt(VS.80).aspx
http://msdn.microsoft.com/en-us/library/aa983453(VS.80).aspx

Get FreeCaptcha control with installation steps

Posted by Venkat | Labels: ,

Here you can get the Free Captcha Control...

Ref:
http://www.mondor.org/captcha.aspx

pass the imagename to ImageUrl

Posted by Venkat | Labels: ,

Hi generally we are binding image to datalist..

so suppose if we store the image in the project folder

we have to get the name of the file and pass it on the src attribute of

img tag.. Ex:

<img src='< %#"BigImages/" & Eval("imagename") % > ' width ="485px" height="613px"  border="0" />
here bigimages is the foldername and imagename that we will get it from database..

so it will run properly..

Suppose if we do some task ie: hiding images - for that we have to

write the code in Datalist_ItemDatabound and also same for Gridview.. event has

been changed ie:ItemCommand..

At that if we use runat="server" id="Image1" for the above tag , while we get the

image through code it shows error

Unable to cast the html image to webcontrol image

for that use asp:image this is way you have to apply imageurl so it display the

image as per imagename - from the folder

<asp:Image ID="ProductImg"
CssClass="ProductImg"
runat="server"
ImageUrl=' < %# Eval("BigImages","imagename/{0}").Trim() % >'
AlternateText=' < %# Eval("imagename","").Trim() % >' 


Validation for Tiny_MceEditor Control

Posted by Venkat | Labels: , ,

Here is the code

validation for tiny_mceEditor control

here is the code for validate the (Required field validation ) for the control

< style="font-weight: bold;">OnClientClick="tinyMCE.triggerSave(false,true);"

Accept a Textbox of 1000 Characters Only

Posted by Venkat | Labels: ,

Suppose in a message board related to same point of view , we place the text with multiline = True.. so user can enter a number of paragraphs, so the user has to avoid more lines ( paragraph ) to allow only the specific Character here the Regular expression to allow only 1000 Characters

EGEX - Validataion Expression - [\\s\\S]{0,1000}$

Use Like Operator using Parameterize Queries

Posted by Venkat | Labels: ,

To use like operator using parametrized Queries suppose if we use the like ie: wild character "%" directly through the query.

There may be attach of Sql Injection - so we have to avoid.

Here is the sample code.

// 1 . using "Like" operator with plus sign in query :

string command = "Select Name from UsersTable1 where Name Like '%'+ @Name + '%' ";

SqlCommand cmd = new SqlCommand(command);

cmd.Parameters.AddWithValue("@Name", textBox1.Text);

// 2. using percentage sign when parameter assignments :

string command = "Select UserName from UsersTable2 where UserName Like @UserName";

SqlCommand cmd = new SqlCommand(command);

cmd.Parameters.AddWithValue("@UserName", string.Format("%{0}%", textBox1.Text));

Avoid execution of page While you Refresh

Posted by Venkat | Labels: , , ,

Hi , here we have to discuss the how to avoid the execution of code

While you refresh the page.. suppose if you have written the code for sending email to users.. after clicking the button the code has been executed suppose if youRefresh the same page once again the Email sent to the user so here we have to avoid the execution on code on page_Refresh

this is the code in VB.NET and C#

Vb.NET


Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
Session("CheckRefresh") = Server.UrlDecode(System.DateTime.Now.ToString())
End If
End Sub


Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
If Session("CheckRefresh").ToString() = ViewState("CheckRefresh").ToString() Then
Label1.Text = "Hello"
Session("CheckRefresh") = Server.UrlDecode(System.DateTime.Now.ToString())
Else
Label1.Text = "Page Refreshed"
End If
End Sub

Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs)
ViewState("CheckRefresh") = Session("CheckRefresh")
End Sub

Here in this code i m saving system date and time in session varaible when the page gets load and in the page prerender event , which occurs after page_Load event , i m assigning the value if session variable to viewstate varaible
Now in Button_Click Event i m checking if both the values in session variable and in ViewState varaible are same than page in not refreshed
if they are not same that means page has got refreshed

This is code for C#.NET


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
}
}


protected void Button1_Click(object sender, EventArgs e)
{
if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
{
Label1.Text = "Hello";
Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
}
else
{
Label1.Text = "Page Refreshed";
}

}

protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["CheckRefresh"] = Session["CheckRefresh"];
}

PayOffers.in