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....




Thursday, May 26, 2011

Find from which page the master file is invoked

Scenario

We may sometimes need to know from which page, the master file is invoked. Based on the file, we'll do some operation not for the other pages. For example if the user name in session is empty, it has to redirect to the login page otherwise the requested page should be opened. But at the same time, if the user request a login page, it should not redirect to the same page again.

Solution


In the above said scenario, we have to identify from where the master page is being called. We have the below code to identify from which page its called,

this.Parent.TemplateControl.AppRelativeVirtualPath.ToString() 


If you put this code in master page file, you will get to know the page from where it's invoked. Its taking the parents relativevirtualpath.


Happy Coding...



Wednesday, May 25, 2011

Change the upload file size in ASP.NET application

Problem:


This is a scenario i faced when i worked in web application. Our application supports to upload the documents. When the user tries to upload the file more than 4MB, the browser shows error message and . Initially I did the work around, check the size of the file and notify the user to upload less than 4 MB document.

Solution

I found that thats not the correct solution. We may stop breaking the application and google the web and found a very simple solution to solve the problem.

We need to add the below line in web.config file under System.web tag
<httpRuntime maxRequestLength="5120"/>

The httpRuntime tag has the property called maxRequestLength, which is to be specified in KB. The above shows the 5 MB file can be uploaded.

If you are not specifying the httpRuntime in web.config..the default size is 4MB.

Conclusion:


With that above work around, user can able to upload more than 4 MB and we can fix the size.

Happy Coding... :)

Tuesday, January 25, 2011

JavaScript Error - Object Not Found

Problem:
When you refer JavaScript/css/images files, it will be referred properly and the code works fine in local machine. But you may get JavaScript error "Object Not Found" when deployed in web servers.


Solution:
Kindly use the  symbol to avoid this Object Not Found error to specify the root directory.


Sample Code:
The below code which generates "Object Not Found" JavaScript error,
<link href="/Content/Styles/MasterPage.css" rel="stylesheet" type="text/css" />
Or 
<link href="../Content/Styles/MasterPage.css" rel="stylesheet" type="text/css" />


Working Code:
Use  symbol before the / to refer the root level as shown below,
<link href="~/Content/Styles/MasterPage.css" rel="stylesheet" type="text/css" />
In addition, if you are working in MVC, use Url.Content to get absolute URL as shown below, 
<script src="<%= Url.Content("~/Scripts/jquery-1.4.4.js") %>" type="text/javascript">script>


Conclusion
Make a practice of referring any external files by using the ~ symbol in the root level to avoid Object Not Fund error.


Happy Coding


Thursday, December 23, 2010

"Object Expected" error in MVC JQuery autocomplete

Problem :-


I have been working in MVC and its very interesting to work with it. I just started working on JQuery. I have encountered this problem when implementing autocomplete to Text box in MVC with JQuery. The JavaScript error "Object Expected" will be coming when you reload the page. That means during first time load, there will be no problem. But if you click on paging and try to do autocomplete in text box. You could face this error in autocomplete statement.

Solution :-


Normally  we used to include the Jquery files by dragging to the page. When we drag the files, the following text will be added,

<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript">

The blue color text shows like the Scripts directory is placed inside one folder from the root. But its not like that. Its placed directly under the root.

So change that script include to the below one.

<script src="/Scripts/jquery-1.4.1.js" type="text/javascript">


This will solve your problem.


Conclusion :-


This may be the small issue but kill your time like anything. You won think the problem due to this script include tag. 


Happy Coding.. :)


Friday, November 26, 2010

Assign default text in Html.TextBoxFor


To assign textbox value in MVC view, use the following syntax.

<%= Html.TextBoxFor(x => x.EmployeeName, new { @Value = "Enter Employee Name"}) %>

Here the @Value case is must.

Wednesday, October 6, 2010

MVC Cascading dropdown, Jquery Grid and Resolving circular references

1. Look at the below link by Stephen Walther to work on Cascading dropdowns

http://stephenwalther.com/blog/archive/2008/09/07/asp-net-mvc-tip-41-creating-cascading-dropdown-lists-with-ajax.aspx

You may face this circular reference error due to referring one class in another class for foreign key relation,

can use the below link to solve that problem

http://blogs.telerik.com/atanaskorchev/posts/10-01-25/resolving_circular_references_when_binding_the_mvc_grid.aspx

2. jquery provides the Grid with paging and sorting. check with the below link

http://haacked.com/archive/2009/04/14/using-jquery-grid-with-asp.net-mvc.aspx

Thanks to respective authors..

Thursday, September 23, 2010

Deploy Webparts in Sharepoint Server 2007

Steps to deploy Webpart in Sharepoint Server 2007 


1. Copy themes files to C:\Inetpub\wwwroot\wss\VirtualDirectories\80\_themes if you have it in webpart.


2. Open web.config file under the port 80 C:\Inetpub\wwwroot\wss\VirtualDirectories\80\ 


3. Add assembly information to safecontrol tag 


    Ex. <<SafeControl Assembly="HelloworldWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5" Namespace="HelloworldWebPart" TypeName="HelloworldWebPart" Safe="True" />>


4. Move the webpart assembly file(.dll under bin folder) to GAC.


5. Restart IIS using iisreset command


6. Go to webpart Gallery and click New on the top.


7. You could find your webpart, select the webpart and click populate button to load the webpart to Gallery.


8. Eventually create a webpart page and add this webpart to the web page.


9. Hope you could see the result displayed in the webpage in the form of webpart.




Happy Coding...

Thursday, August 19, 2010

MVC Basics

Model View Controller [MVC]


MVC is a design pattern which separates the Business Logic, User Interface and Controlling user inputs. It consists of Model, View and Controllers. 


Let we see about each components...


Model


Model represents the data model which contains the all DB related operations including select, insert, delete and update. I have used Entity Data Model(edmx) to build model for my application. We can also have classes to represent the DB operations like DAL.


View


The view describes the user interface which will appears to the user. Normally the page files(.aspx) with html design is called views. It doesn't contain the code behind file. since its not event driven.


Controller  


Controllers are class file which should be derived from the base class Controller. Basically controllers determine which view should be called based on the URL routes. The default route is defined in the Application_Start() event of Global.asax.


Sample Application


I'd like to create one sample application so that you could understand more clearly how the model, view and controllers are interacting each other with real time scenario.


Purpose


To display all the Employees from Northwind database Employees table.


Step 1 : Creating ASP.NET MVC Web Application


Create ASP.NET MVC Web Application under .Net Framework 3.5. Note that we have created MVC Framework 1.0. Refer the below image how the solution looks,



If you look at the project structure, you could find Controllers, Models and Views folder to hold the respective files.

Step 2 : Add Controllers

Right click on the Controllers folder and select Add Controller menu, it will open a popup (see the below image) to give the controller name with suffix of controller.


It also has the check box to Add action methods for create, update and Details scenarios. If you check this box it will create controller action for the Create, update and details action.

Step 3 : SampleController File

After you click that Add button, it will add controller file to Controllers folder. Look at the below image how it looks like.


The Class contains Index method with the type of ActionResult and return View(). The controller is ready now. We have to create Model and View to make this work.

Step 4 : Create Model

Creating model is very easy as we are going to use Entity Data Model(edmx). Right click on the Model folder and select New Item. Select Data from Category then select ADO.NET Entity Data Model. A pop up will open and select Generate From Database

Click Next and select the server and database to create Model.You could find the Model1.edmx under Model folder.

Good.. Model is ready to consume the data from Database.

Step 5 : Add Code in Controller file

Add Model Namespace to controller file in order to get the classes from the Model.

public ActionResult Index()
{
NorthwindEntities nw = new NorthwindEntities();
var emp = nw.Employees;
return View("Index",emp);
}


Add the above code into method Index of the controller file created. The first line is creating the instance for the model which we have created from Northwind/any other DB. The Employees is a ObjectQuery which will return all the employees from the database. The var defines the Object which can be bind to the View. The last line return the View with the view name called "Index" and the datasource object.

Note: Here we are calling the view from Controller.

Step 6 : Creating View

Right click on the Above ActionResult Index and click Add View. Now you could see the below image...


The View name will come by default. Check Create a strongly-typed view and  you have to choose the Model from the Model(.edmx) class here am using Employees. In addition with select view content, We are going to display all the employees so select List. Note that the user can select the Master page for the view.

Finally click Add. 

Step 7 : Index View

If you look at the Views Folder, new folder has created with the controller name(Sample). Inside Sample folder, file named Index.aspx created with all the table fields to display the list of employees.

Its really amazing when see it first time. No need to drag and drop any controls or write any html code to build the tables. Simply all the html codes are in the view.If you look in deep you could see the binding has also been included in the html code.

Index View Code
It loop through all the items in the Model(The model selected for this view is Employees) and build the html table. The arrow indicates the loop and how the field has been binded with the table cell. Also note that the Edit/Details/Delete links are created for each row. This will help you to edit the particular row or to see the details about the row. Don worry about this at present. We have to build view to display the details/edit the row.

The Application is ready except one below configuration settings step. 

Step 8 : Configure in Global.asax

The Global.asax is located in the applications root directory and open it.

Global.asax
The Application_Start() call the RegisterRoutes method and pass the RouteTable.Routes as parameter. We are going to add the default route to the routes. The green color bordered area shows how to add MapRoute to the Routes. The "Default" is the route name, next one is format and last on is value for the format. For the above definition, the URL looks like http://localhost:1173/Home/Index. Home is a Controller and Index is a View. 

Step 8 : Run the Application

Run the application and this will display the default page (Home\Index.aspx)


If you want to access our page which we have developed, Change the URL to the below one,
http://localhost:1173/Sample/Index or http://localhost:1173/Sample is enough since Index is a default page.

Here is our First MVC output..


This is really nice to see the output without coding much...

Happy Programming...

Monday, July 19, 2010

Service unavailable error when browse pages in Windows 2003



Getting "Service unavailable" error when you try to access the web pages hosted in Windows 2003 server.

Resolution 1


Right click on website and click Properties menu. you could find "Web Site" tab.


Check for TCP Port Number. Change the port number which is not assigned to any other web site. The other virtual directories(web sites) may access the same port no.

Resolution 2

1. Right click on website and click Properties menu. Click on "Home Directory" tab.

2. Get "Application pool" name and verify whether that application pool service has started.

3. "Application Pools" exists above the websites folder.

Conclusion


I have faced the above said error and rectified using the resolution2.


.

Sunday, April 25, 2010

Gridview - Highlight selected row after Postback

Problem:

I have a gridview to display employee information. When user clicks on employee no /name the particular row should be selected and selected row color should be changed. This has to be done after the postback.














Solution:


Since we are doing it after postback, the control losts the data as well selected row. We can do this with linkbutton control to change the color of the selected row very easily.


code snippet:

If you look at the snippet in the first image, I have used the linkbutton inside the itemtemplate. The important thing here is the property CommandName as Select. This property will take care of the selected row color changes. The row selection color will be taken from the SelectedRowStyle styles from the gridview.

Conclusion:


Hope this will be easy for everyone rather than doing it after the binding the grid with some extra code.

Happy coding...

Thursday, April 15, 2010

Open a page in the same browser using JavaScript without Postback

Problem:

Had a requirement to open up a page in the same browser window without postback to the existing page.

Solution:

In JavaScript, window.Open(...) is there to open a page in a new window. With the value of _self as a second parameter to the Window.Open, we could open the page in the same browser window.

Code Snippet:

#1 Using Image Button


OnClientClick="Javascript:window.open('Format.aspx','_self',null,false);return false;" />

#2 Using href anchor tag


href="javascript:window.open('Format.aspx','_self');" style="text-decoration:underline" id="A1" >Click...Here

I have opened the page called "Format.aspx" using window.open with the second parameter as "_self" on the OnClientclick of ImageButton. Finally give the return false to not posted back to the existing page.

Reference:
Refer the below Microsoft knowledge base library for more info.



Wednesday, March 3, 2010

Windows ReportViewer - Change rdlc report files during runtime

Problem

I had faced the problem of assigning different rdlc report files to a single Reportviewer. It always shows the report which opened first.

Solution
  1. Clear the datasources of the LocalReport or ServerReport in ReportViewer
  2. Reset the ReportViewer control in the beggining of the function.
  3. Do assign the datasources Name and Value. The Datasources name from the dataset as string and value.
  4. Finally add the datasource to the reportviwer datasource in localreport or serverreport.
Sample c# code snippet to solve this problem

this.reportViewer1.Reset();
this.reportViewer1.LocalReport.DataSources.Clear();
reportDataSource.Name = "DataSet_usp_EmpFoodCouponMonthly";
reportDataSource.Value = this.DataSet.usp_EmpFoodCouponMonthly;
this.reportViewer1.LocalReport.DataSources.Add(reportDataSource);
this.reportViewer1.RefreshReport();


Monday, January 4, 2010

Difference between Postback and Callback

The OnPreRender won't be fired in the Callback event. Whereas in Postback, After the particular event handling, the PreRender will be invoked.

But all the controls will be created again in both Postback and Callback. The viewstate values will be reassigned to the controls again.