Archive for January, 2008

 

There is one requirement of storing file content in a database using Image data type. Image field can store up to 231 -1 bytes and that equals around 2 GB. So you can store up to 2 GB data in image field of Microsoft SQL Server. Let us come to the point now; I was required to store uploaded file content in image field of database. File is uploaded through file upload control of HTML of course! While uploading the content you need to convert that content into byte array and then you can store it into the database. Now, how to convert file content into byte that I have displayed below with code.

Code: C#

Int32 intDocLength = File1.PostedFile.ContentLength;

byte[] bytDocTemp = new byte[intDocLength];

Stream objStream;

objStream = File1.PostedFile.InputStream;

objStream.Read(bytDocTemp, 0, intDocLength);

 

Now you can use bytDocTemp variable to store content of the file in the form of byte array into the database. Here, File1 is a file upload control and I used content length of the file to create an array of byte with exact size of the file.

I will show you how to retrieve file content from Image data type and showing it in its original form. You can display uploaded content of the file back to its original form with the following code:

Code: C#

Response.Clear();

Response.AddHeader(“Content-Disposition”, “attachment; filename=<filename>” + <File Extention>);

Response.ContentType = “application/octet-stream”;

Response.BinaryWrite(<byte array of the file>);

Response.End();

 

Here, replace <filename> with any of the file name that you need to display. File name must be without extension, and replace <File Extension> with your original file extension (like .doc, .pdf, .html etc). <byte array of the file> can be replaced with the content that you have fetched from the Image field of the database.

Whether you found this article useful or not? please provide your valuable comments.

Advertisements

 

There may be circumstances when you would like to use file upload control to upload different file using your web application, at the same time you need to set this control as read only so that no one can change the text inside the textbox in a file upload control. You can achieve this by following code.

<input type=”file” id=”file1″ onkeypress=”javascript:return false;” onkeydown=”javascript:return false;” name=”file1″ />

If your file upload control is server control then you can also set its attribute runtime as describe below:

file1.Attributes.Add(“onkeydown”, “javascript:return false;”);

file1.Attributes.Add(“onkeypress”, “javascript:return false;”);

You can set this attribute in a Page_Load event of web page. Just by using simple javascript you can achieve file upload control with read only property.

Whether you found this article useful or not? please provide your valuable comments.

 

Sending child window’s value to parent window is one of the very common requirements for web developers. I also used it a lot, so decided to make a post for some of our beginners friends to Javascript. There are many ways you can send values of child window to parent window, however, I have described here two ways to send value from child window to parent.

Either you can send value through an argument to a function or you can directly set parent window’s object value from the client window. How to do it? that I have described below.

Find the below code to send value to parent window through an argument to a function. Write below code in your parent window.

<head>

<script language=”javascript” type=”text/javascript”>

    function GetValueFromChild(myVal)

    {

        document.getElementById(‘mytxt’).value = myVal;

    }

</script>

</head>

 

<body>

        <input id=”mytxt” type=”text” />

</body>

Fig. 1

Here in fig 1, “mytxt” is a textbox object whose value will be received from the child window. “myVal” is argument of this function, this function will be called from the child window later.

Find the below code to be written in child window.

<head>

<script language=”javascript” type=”text/javascript”>

    function SendValueToParent()

    {

        var myVal = document.getElementById(‘mytxt’).value;

        window.opener.GetValueFromChild(myVal);

        window.close();

        return false;

    }

</script>

</head>

 

<body>

Type text here and send it to parent window:

        <input id=”mytxt” type=”text” />

        <input id=”btn1″ type=”button” value=”Send Value to Parent” onclick=”javascript:return SendValueToParent();” />

</body>

Fig. 2

Here in fig 2, we are sending child window’s textbox value to the parent window’s function by calling “GetValueFromChild(myVal)”. “myVal” is the value of the child window’s textbox and will be sent to parent window as an argument by clicking “btn1” button.

You can also set parent window’s object value from the child window. You only need to do is, just write the below code in your child window only and there is no need to write any script in the parent window. Only you need is a textbox or any other object that can display the value of the parent window in browser.

Put the following code in child window to set parent window’s object value:

<head>

<script language=”javascript” type=”text/javascript”>

    function SetValueInParent()

    {

        window.opener.document.form1.mytxt.value = document.getElementById(‘mytxt1’).value;

        window.close();

        return false;

    }

</script>

</head>

 

<body>

Type text here and set it to parent window      :

        <input id=”mytxt1″ type=”text” />

        <input id=”btn1″ type=”button” value=”Set Value in Parent” onclick=”javascript:return SetValueInParent();” />

</body>

Fig. 3

In fig 3, we have set the value of child window’s textbox object to parent window’s textbox object directly by using it’s ID property. I have called this function by clicking on “btn1” button.

Whether you found this article useful or not? please provide your valuable comments.

 

I was required to bind DataFormatString in my GridView control and I was using  asp:BoundField, so what I have done is, I have set one date format in my web.config file and then access that format in my GridView to bind it in my HTML code.

Write the following code in your web.config file to set your desired date format:

<configuration>

      <configSections>

            <add key=GridDateFormat value={0:dd/MM/yyyy}/>

      </configSections>

</configuration>

You can apply any date format other than “dd/MM/yyyy” as per your need, now how to access this date format in Grid view? is very important, so below is the code, that defines how to access web.config file’s date format in your GridView:

<asp:BoundField HtmlEncode=”False” DataField=”CreatedDate”  SortExpression=”CreatedDate” HeaderText=”Created Date” DataFormatString=”<%$Appsettings:GridDateFormat%>“/>

Here, we have set “HtmlEncode” property to “False”, if you do not set this property then it might possible that you will get proper result while running your application in localhost but you might not get proper result of the date format after publishing the code on hosting server. Therefore, it is better to set HtmlEncode property to False. So, now no need to apply date format at run-time, you can use your required date format in a GridView while creating it.

To access outlook emails and its contents like total number of emails in inbox, number of unread emails, subject and title of email, attachments of email etc. To acquire these, all you need is Interop.Outlook.dll. How to access outlook using ASP.NET is given below. You can write this code in a button click event or in page load event. The code part contains C# language:

 

 using Outlook;

 Outlook.Application oOutlook;
 Outlook.NameSpace oNs;
 Outlook.MAPIFolder oFldr;
 long iAttachCnt;

 try
 {
     oOutlook = new Outlook.Application();
     oNs = oOutlook.GetNamespace(“MAPI”);

     //getting mail folder from inbox
     oFldr = oNs.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
     Response.Write(“Total Mail(s) in Inbox :” + oFldr.Items.Count + “<br>”);
     Response.Write(“Total Unread items = ” + oFldr.UnReadItemCount);
     foreach (Outlook.MailItem oMessage in oFldr.Items)
     {
         StringBuilder str = new StringBuilder();
         str.Append(“<table style=’border:1px solid gray;font-family:Arial;font-size:x-small;width:80%;’ align=’center’><tr><td style=’width:20%;’><b>Sender :</b></td><td>”);
         str.Append(oMessage.SenderEmailAddress.ToString() + “</td></tr>”);
         //basic info about message
         str.Append(“<tr><td><b>Date :</b></td><td>” + oMessage.SentOn.ToShortDateString() + “</td></tr>”);
         if (oMessage.Subject != null)
         {
             str.Append(“<tr><td><b>Subject :</b></td><td>” + oMessage.Subject.ToString() + “</td></tr>”);
         }
         //reference and save all attachments

         iAttachCnt = oMessage.Attachments.Count;
         if (iAttachCnt > 0)
         {
             for (int i = 1; i <= iAttachCnt; i++)
             {
                 str.Append(“<tr><td><b>Attachment(” + i.ToString() + “) :</b></td><td>” + oMessage.Attachments[i].FileName + “</td></tr>”);
             }
         }
         str.Append(“</table><br>”);
         Response.Write(str.ToString());

     }

 }
 catch (System.Exception ex)
 {
     Response.Write(“Execption generated:” + ex.Message);
 }
 finally
 {
     GC.Collect();
     oFldr = null;
     oNs = null;
     oOutlook = null;

 }

 

Hi, I stuck with one requirement as describe in title and after searching for the solution, I found how can I call javascript function of the parent window whereas I am working with the child window. Here is the solution for you all.

 

Write below function of javascript in your parent window. We will call it later from the child.

 

    <script language=”javascript” type=”text/javascript”>

    function ParentWindowFunction()

    {

        alert(‘Hi, At least someone has called me from the child window’);

        return false;

    }

    </script>

 

Write the below code in your child window

 

    <script language=”javascript” type=”text/javascript”>

    function CallParentWindowFunction()

    {

        window.opener.ParentWindowFunction();

        return false;

    }

    </script>

 

You can call above function from a button click event like

    <input type=”button”  name=”btn1″ value=”Call Parent Window Function” onclick=”javascript:return CallParentWindowFunction();”/>

 

That’s it. Now by clicking on this child window’s button you can call a function resides in parent window.

Whether you found this article useful or not? please provide your valuable comments.

How to convert HTML content to PDF? Once, this question was very intricate. But after getting the solution I found it like a piece of cake. Here, I have provided solution with C# code so that you don’t have to waste your time by looking here and there for the solutions.

I have used iTextSharp.dll (version 4.0.6.0) in my solution which is very useful indeed. You can get it from here.

Review the below code, where I have converted content of the GridView to HTML and then I have converted that HTML content into a PDF file.

I have put comments with the code for more specification.
//Include following name space to use iTextSharp library
using iTextSharp.text;
using iTextSharp.text.pdf;
//Document is inbuilt class, available in iTextSharp
Document document = new Document(PageSize.A4, 80, 50, 30, 65);
StringBuilder strData = new StringBuilder(string.Empty);
//I have provided Path for the HTML which will be generated from GridView content
string strHTMLpath = Server.MapPath("MyHTML.html");
//I have provided Path for the PDF file which will be generated from HTML content
string strPDFpath = Server.MapPath("MyPDF.pdf");
try
{
StringWriter sw = new StringWriter();
sw.WriteLine(Environment.NewLine);
sw.WriteLine(Environment.NewLine);
sw.WriteLine(Environment.NewLine);
sw.WriteLine(Environment.NewLine);
HtmlTextWriter htw = new HtmlTextWriter(sw);
//gvSearchResult is a GridView, I have converted its content to HTML and will acquire final PDF file
/*Here i have set AllowPaging and AllowSorting property of GridView as false, As my aim is to get whole content of the GridView in a single table, by setting these properties and binding the GridView again will remove paging and sorting property from it. */
gvSerchResult.AllowPaging = false;
gvSerchResult.AllowSorting = false;
BindGridView();
//Rendering the HtmlTextWriter
gvSerchResult.RenderControl(htw);
/*Here i have set AllowPaging and AllowSorting property of GridView as true, As my aim is to get whole content of the GridView is now finished and I have acquire its content in HtmlTextWriter. Then by setting properties again I will get the original form of my GridView again*/
gvSerchResult.AllowPaging = true;
gvSerchResult.AllowSorting = true;
BindGridView();
StreamWriter strWriter = new StreamWriter(strHTMLpath, false, Encoding.UTF8);
strWriter.Write("<html><head><link href=Style.css rel=stylesheet type=text/css /></head><body>" + htw.InnerWriter.ToString() + "</body></html>");
strWriter.Close();
strWriter.Dispose();
iTextSharp.text.html.simpleparser.
StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
styles.LoadTagStyle("ol", "leading", "16,0");
PdfWriter.GetInstance(document, new FileStream(strPDFpath, FileMode.Create));
document.Add(new Header(iTextSharp.text.html.Markup.HTML_ATTR_STYLESHEET, "Style.css"));
document.Open();
ArrayList objects;
styles.LoadTagStyle("li", "face", "garamond");
styles.LoadTagStyle("span", "size", "8px");
styles.LoadTagStyle("body", "font-family", "times new roman");
styles.LoadTagStyle("body", "font-size", "10px");
document.NewPage();
objects = iTextSharp.text.html.simpleparser.
HTMLWorker.ParseToList(new StreamReader(strHTMLpath, Encoding.Default), styles);
for (int k = 0; k < objects.Count; k++)
{
document.Add((IElement)objects[k]);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
document.Close();
Response.Write(Server.MapPath("~/" + strPDFpath));
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + strPDFpath);
Response.ContentType = "application/octet-stream";
Response.WriteFile(Server.MapPath("~/" + strPDFpath));
Response.Flush();
Response.Close();
if (File.Exists(Server.MapPath("~/" + strPDFpath)))
{
File.Delete(Server.MapPath("~/" + strPDFpath));
}
}

Whether you found this article useful or not? please provide your valuable comments.