Monday, July 18, 2011

Store files in database

Scenario:


This may not be very common scenario but needed some time to store the files in database. Mostly the attachments needs to be stored in a database instead of maintaining as files.

Solution:

This is very easy with the .NET and SQL Sever environment. Let me start from the database side.We need to have the varbinary field in the database table in order to store the file stream. Look at the below image shows about the table structure.



We can go for the coding part, we'll use File upload control to get the file from the user. We need to convert the file stream in file upload control to byte array. This byte array has to be passed to the database as param.
Look at the screenshot of the code used to store the file,

Hope the above screenshot is explanatory about the code used. I would like to show how this parameter has been handled in executing the stored procedure.


Conclusion:


I believe the above code will be used to store the files in database.

Happy .NETting..

Thursday, July 14, 2011

MailMessage - Allowing html tags inside body text

Problem


This is the very simple scenario required when sending email from our application. We need to put html tags in the body of the text which we are sending.


We are expected to send the email with the above body. This should be appear in their inbox with two lines. The text "Dear Murugesan," should come in the first line and the rest in second line.

Solution

Normally this won't appear as we wish. We need to true the property named "IsBodyHtml". Look at the below code sample,

The above picture clearly shows the how to enable the property to get the work done.

Keep .Neting...

Tuesday, June 21, 2011

ASP.NET Gridview Sorting

Gridview Sorting:


The Gridview sorting can be done with little code block. The Gridview itself has two events for sorting and one property to enable the sorting. Look at the below picture to change the Gridview property and create onsorting event.












In addition with the AllowSorting property set and event creation, we need to do some code in the event method. Look at the below picture, the red colored box indicates the property enabled with ViewState to hold what sortdirection had clicked. With the help of the property, we cross check and sort the session stored dataview and assign it back to Gridview. Before that we need assign the property to switch between ASC and DESC.


Hope this will help. Happy Coding...

Wednesday, June 15, 2011

Open Database stored files in ASP.NET

Scenario:


This post is about how to open the DB stored binary files in a ASP.NET form.

Solution:


This can be achieved with the Response of ASP.NET. Response's BinaryWrite function can write the binary content into appropriate content type and ll be opened.

Code Sample:



          string fileName = dt.Rows[0]["AttachFileName"].ToString();
          byte[] FileContent = (byte[])dt.Rows[0]["AttachFile"];
          Response.Clear();
          Response.AddHeader("Content-Disposition", "inline;attachment; filename=" + fileName);
          Response.AddHeader("Content-Length", FileContent.Length.ToString());
          Response.ContentType = "application/octet-stream";
          Response.BinaryWrite(FileContent);
          Response.Flush();


From the above sample code, We are fetching the file name and binary file content from the database and assign to string and byte array respectively. We are adding some response Header with Content Description and Content-Length. Here we also need to specify the content type as octet-stream in order to write it as a file. Finally write the byte array content using BinaryWrite of Response method to open the attached document.

Happy .Neting



How to update parent form control from child form

Situation:


I have had a scenario while developing one application like need to open a child window for adding attachments for the parent window. There is a link in parent window along with No. of attachments has to be displayed near by the link. The thing is the parent form control should be updated when user adds/deletes attachment in child form.

Solution:


I believe most of the people known about the "window.opener" is pointing the parent form and can manage this with some Javascript code. Here one more thing also there. When you write Javascript code, this has to be called during add/delete button click of server side event. This can be achieved by "RegisterClientScriptBlock" of ClientScript object.

Code Sample :


      StringBuilder RTScript = new StringBuilder();
      RTScript.Append("script>window.opener.document.forms['aspnetForm']." + 
                                  "ControlName.value  = '[" + AssigningValue + "]';script");
      ClientScript.RegisterClientScriptBlock(this.GetType(), "script", RTScript.ToString());


Kindly add less than[<] symbol before and after the script tag in the above code.


In the above code you have to change it in two places one is ControlName, which is the name of the control in parent window and AssigningValue, whats the value you want to display it in the parent window.


Happy .Neting.. :)





Friday, June 3, 2011

Server side web reports using Reportviewer

Scenario:


I had to show SSRS report in my web application. I have used the MicrosoftReportviewer 9.0 control and add little bit of code can make it happen.

Solution:


Its very easy to do it in few steps.

1. Add MicrosoftReportViewer control to the web form. This will add the control and necessary @ Register directives and assembly to the references.

2. Add the below code during any of the page events like load or Init.

        Before start the code add the namespace Microsoft.Reporting.WebForms

        a. Start with Reset command of the Reportviewer and set ProcessingMode as Remote.

        ReportViewer1.Reset();
        ReportViewer1.ProcessingMode = ProcessingMode.Remote;
        
        b. Create Uri based on the SSRS server name. 
        Uri ReportURL = new Uri("http://ServerName/ReportServer");


        c. Instantiate the ServerReport to assign the Report server and report path
        ServerReport sr = ReportViewer1.ServerReport;
        sr.ReportServerUrl = ReportURL;
        sr.ReportPath = "/ReportFileName";


        d. Define ReportParameter array to hold parameter to the report.
        ReportParameter[] rp = new ReportParameter[1];


        e. Create and assign parameter name and value. Repeat for all the parameters.
        rp[0] = new ReportParameter();
        rp[0].Name = "EmpNo";
        rp[0].Values.Add(Convert.ToString(Session["EmpNo"]));
        
        f. Assign Report parameter array to ServerReport
        sr.SetParameters(rp);


        g. Finally show the report and can manipulate the session timeout and zoom modes.
        ReportViewer1.ServerReport.Timeout = Session.Timeout;
        ReportViewer1.ZoomMode = ZoomMode.PageWidth;
        ReportViewer1.Visible = true;


Conclusion:


I believe this code will help you to show the SSRS reports in web form.

Happy Coding


Tuesday, May 31, 2011

How to avoid the error "Maximum Request Length Exceeded"

Scenario :


I had a requirement to develop a page which has to upload the file to the DB server. Uploading a file to the server is a very easy thing with the FileUpload control. By default the maximum size allowed to upload is 4MB and if you want you can increase or decrease in web.config settings.

Problem :

There won't be any problem, if you upload the file size of less than the specified size in web.config. If the size of the file is more than the limit specified, the runtime will be thrown with the message of "Maximum Request Length Exceeded". The thing is it won't be catched in button click of the File upload. Let us see how can we fix this. I found the solution in web and explaining for you.

Solution:  

I'm not sure this is the best way to do it. But this also a solution. We could catch this in Application_BeginRequest event of Global.asax. Normally whatever the client request for a page or file this application BeginRequest event will be fired and the control goes to the page events. Since its going for all the postback and initial load. We can calculate the content length of each post by the below lines,

            HttpContext context = ((HttpApplication)sender).Context;
            int PageContentLength = context.Request.ContentLength;

In addition with that, we need to calculate the actual size of the page and do some calculations. Look at the entire code below, which have to be added in Global.asax.

Event in Global.asax


The last line redirects the control to the same page with the url querystring. Based on the query string, we'll display the error message in Attachment page. Another thing here is as soon as you displayed the error message you need to remove the querystring value.

Conclusion:


This solution may not be better for performance wise since this event is keep calling for all the page requests as well file requests like .JS or .CSS. Let me know if you have better solution than this.

Happy Coding....