Banner Ad

Showing posts with label ASP.Net. Show all posts
Showing posts with label ASP.Net. Show all posts

Tuesday, May 3, 2016

Conventional File Uploading in ASP.Net

By Francis   Posted at   5:12 PM   ASP.Net No comments
This post is going to give some basic ideas about file uploading in ASP.Net. Mostly every data driven web site will provide this feature. Also, every ASP.Net developer face this kind of requirement at least once in his/her developer life.



Note:
      The file upload control renders slightly/completely different from browser to browser. If you want to give a consistent UI, you can check my previous post here.

If you want to upload a file in ASP.Net, it is very simple. You need to include “File Upload” control on your form and place a command button, which triggers the upload process and save the respective file in the specified location on the server.


<div> 
           <asp:FileUpload runat="server" ID="fileUploader" AllowMultiple="false" /> 
           <br /> 
           <asp:Button runat="server" Text="Upload" ID="btnUpload" OnClick="btnUpload_Click" /> 
</div>

On the code behind you should include the below lines:

protected void btnUpload_Click(object sender, EventArgs e)    
       {     
           if(fileUploader.HasFile)     
           {     
               fileUploader.SaveAs(Server.MapPath(@"~\UploadedFile\")+ fileUploader.FileName);     
           }     
       }     


Note:
In the above code snippet, when you click the button, it will save the file in a specified location on the server. As per the above code, it looks for the directory “UploadedFile” in the server. So you need to create the directory on your application, before executing the code, otherwise the application will throw an error while run.

Upload specific File Types:
In some cases, we may want to force the user upload only the specific file types. This is an inevitable scenario for the professional programmers. In this case, we should validate the file types, if it pass then we can go with upload. Otherwise, the user will be notified by an “error” message. In order to validate, I’m going to use the built-in ASP.Net validation control.

<div> 
            <asp:FileUpload runat="server" ID="fileUploadExcel" AllowMultiple="false" /> 
            <br /> 
            <asp:Button runat="server" Text="Upload" ID="btnUploadExcel" OnClick="btnUploadExcel_Click" /> 
            <asp:RegularExpressionValidator runat="server" ControlToValidate="fileUploadExcel" 
                ValidationExpression="^.*\.xls[xm]?$" 
                ErrorMessage="Please upload excel file only"></asp:RegularExpressionValidator> 
</div>


The code behind not much changed compare to the previous one.

protected void btnUploadExcel_Click(object sender, EventArgs e)    
        {     
            if (fileUploadExcel.HasFile)     
            {     
                fileUploadExcel.SaveAs(Server.MapPath(@"~\UploadedFile\") + fileUploadExcel.FileName);     
            }     
        }

Restrict File Size:
In some cases, we need to restrict the file size. Say for example, we may need to force the user to upload an excel file not more than 1 MB. At this case, we should validate this one from the server as shown below:

protected void btnUploadExcel_Click(object sender, EventArgs e)    
      {     
          if (fileUploadExcel.HasFile)     
          {     
              int fileSize = fileUploadExcel.PostedFile.ContentLength;     
              if (fileSize <= 1048576)     
                  fileUploadExcel.SaveAs(Server.MapPath(@"~\UploadedFile\") + fileUploadExcel.FileName);     
              else     
              {     
                  lblError.Text = "File size exceeds more than 1 MB.";     
              }     
          }     
      } 

Upload Multiple Files:
In some cases, we may need to upload multiple files. ASP.Net gives an easy way to achieve this. The file upload server controls had a property called “AllowMultiple”, which is a boolean value (either true or false). By turn it as “true”, the file upload control control allows you to select multiple files.

<div> 
<asp:FileUpload runat="server" ID="fileUploadMultiple" AllowMultiple="true" /> 
<br /> 
<asp:Button runat="server" Text="Upload" ID="btnUploadMultiple" OnClick="btnUploadMultiple_Click" /> 
<asp:RegularExpressionValidator runat="server" ControlToValidate="fileUploadMultiple" 
ValidationExpression="^.*\.doc[x]?$" ID="RegularExpressionValidator1" 
ErrorMessage="Please upload word file only"></asp:RegularExpressionValidator> 
<asp:Label runat="server" ID="Label1" Style="color: red;"></asp:Label> 
</div>

In the code behind, the code like below. It get the files and loop thru the selected files and check the file size then store it in the particular path.

protected void btnUploadMultiple_Click(object sender, EventArgs e)    
{     
    if (fileUploadMultiple.HasFile)     
    {     
        HttpFileCollection files = Request.Files;     
        for (int i=0;i < files.Count;i++)     
        {     
            HttpPostedFile file = files[i];     
            if(file.ContentLength >0)     
            fileUploadMultiple.SaveAs(Server.MapPath(@"~\UploadedFile\") + file.FileName);     
        }     
    }     
}    


I hope this post gives an some basic understanding and standard validations during the File upload in ASP.Net. Let me know your thoughts as comments. Happy Coding! Smile

Monday, September 14, 2015

How to improve the performance of an ASP.Net Web page?

By Francis   Posted at   9:22 PM   Webpage No comments
Performance         
                     This is the most common question from asp.net forum to any interview. In this post I’m going to point out some of the important points that may help to improve the performance.
                      Here I used the word “improve performance” in the sense to decrease the loading time of the page. There are various reason behind. Some of them we look into from the “backend side” (Database side) and rest of them we need to take care in “front-end” ((UI) side.
For illustrative purpose, you have a ASP.Net Web site, one of the aspx page take much time to load. Also as a backend I assume that you are using SQL Server. Through out this article, we are going to see how to decrease the loading time.
Back End (DB):
Below are the points that you need to consider to fine tune the DB:
1) Try to check the Query performance, that is how much time the query will take to execute and pull the records from DB. The Use SQL Server Profiler and Execution plan for that query. So that you can come to the conclusion in which part it took much time.
2) Check in every table (who are all part of the query) Index is created properly.
3) If your query involves an complex Stored procedure, which in turn use lot of joins, then you should focus on every table. In some cases, sub-query perform better than the joins.
4) If your web page, involves paging concepts, try to move the paging concepts to SQL Server. I meant that based on the page count the SP will return the records, instead of bring the records as a whole.
Front End (UI):
1) If your page displays a lot of records, try to introduce “paging”. Say for example your page displays 1000 record in a page. Instead of pulling 1000 records as a whole, by introducing paging such that page size as 10, you need to pull 10 records only!
2) Try to choose “tabless” design, that is try to avoid “table” to design the webpage. In order to achieve this use should use “div” tag.
3) If you want to design responsive pages, try to use existing (proved) frameworks such as Bootstrap, instead of trying your own code.
4) Also if your webpage deals with lot of images or videos to display, then consider to use appropriate CDN (Content Delivery Network).
5) Use bundling and minification techniques, which reduce the server calls to load the javascript and CSS files, which in turn reduce the loading time.


Readers!! Do you thing that I have missed out anything? Let me know your thoughts in comments! Smile

Sunday, December 21, 2014

An easy way to construct the Connection String in ASP.Net

By Francis   Posted at   7:26 AM   Connection String 2 comments

Connection strings are necessary when you want to interact with any databases like SQL Server, MSAccess etc. Most probably if you are using ADO.Net Concepts to interact with Database then you can aware about the connection string. In this article I am going to share how it can be easily constructed.

 

Step 1:

Open Visual Studio and create sample web form application.

 

Step 2:

Switch over to “Design Mode” and in the tool box, just drag and drop a “Gridview” control in to the web form.

DesignMode-1

 

Step 3:

Select “New Data Source”.

DesignMode-2

Step 4:

In the “Data Source Configuration Wizard”, select your database click “OK”.

Datasource-1

Step 5:

In the next step of the wizard, Click “New Connection”.

Datasource-2

Step 6:

It will provide a pop-up dialog box to select “Data Source”, in that select “Data Source” and select data provider from “Data Provider” dropdown list, then click “Continue”.

Datasource-3

Step 7:

In “Add Connection” modal dialog, select your “Server Name” (if not available, first click “Refresh” button, still it not available type your “SQL Server Name” manually on it).

You can either use, “Windows Authentication” or “SQL Server Authentication” to login to your SQL Server.

As a next step, select your database, that is available on your SQL Server. Finally, click “Test Connection”, to check whether the connection is established successfully or not.

Datasource-4

 

Datasource-5

Step 8:

As a final step, you will get the Connection string, which can be used on your web/windows application to connect the DB.

Datasource-6

Happy Coding!

Sunday, October 5, 2014

ASP.Net Forums–FAQ #6: ASP.Net Session Expired Problem

By Francis   Posted at   12:29 AM   IIS Tips and Tricks 1 comment
session_expired
Most of the asp.net application using session, especially data driven applications. Mostly these kind of application using “Inproc” mode of session. During development the developer does not face any kind of problem with the session. When deploy the application the problem arise one by one. In this post I just want to share some thoughts and my professional experience on this issue.

Thursday, September 12, 2013

Code Obfuscation

By Francis   Posted at   1:47 PM   Dot Net Obfuscator No comments

          In this post I’m going to discuss about Reverse engineering and Code Obfuscation. In modern programming trends, when we publish a website or dll file to a client machine, there are lot of chance to theft our code. That is if we publish a class library as a dll, there are lot of tools available for simply reverse engineer that dll. So that the person can see the source of such files, which is a potential thread for software companies who does not want to share the source code to the end user.

Below are the some tools which is used to decompile the dll:

Dot net reflector – From Redgate
Dot net decompiler (Dot Peek) – From Jetbrains
Just Decompile – Free tool From Telerik 

What is Obfuscation?
                   Obfuscation is a process to convert the (source code or machine) code into a difficult form which cannot easily read by humans.
Eventhough, obfuscation does not guaranteed 100 % of code safety. However it will make the process too hard, that is getting the source from the dll or exe. In my professional life, I have experienced with DeepseaObfuscator tool.

Here are the list of Obfuscation Tool for .Net:


Hope this helps!

Friday, March 8, 2013

ASP.Net Server Controls – An Overview

By Francis   Posted at   11:27 AM   Server Controls No comments


What is Server Controls?
                 In ASP.Net there 2 types of Controls available. One is Client Control and another one is Server side controls. Client Controls are basic HTML controls like button, text boxes, check box etc. which can be easily constructed by HTML elements. 

Monday, February 11, 2013

Validators in ASP.Net – Part 5 : Custom Validator Control

By Francis   Posted at   11:51 AM   Validators in ASP.Net No comments
Custom validator Control:

In my previous posts, I have explained 4 validation controls. In this post I’m going to explain Custom validation control. In some situations we need to customization on validations. At this time Custom validator comes in to picture.


             Custom Validator provides 2 ways to do your validation. One is Client side and another one is Server side.  User can achieve the Server side validation by using the property “OnServerValidate” property. In this property user must give the server side function name which handles the validation.

Wednesday, January 23, 2013

Validators in ASP.Net – Part 4 : Regular Expression Validator

By Francis   Posted at   11:15 AM   Validators in ASP.Net No comments

Regular Expression Validator:
                  In my previous posts, I have covered about 3 types of validators. In some situations the above 3 validators are helpful till some extend. Such that they may provide the flexibility to cover basic validation functionality. Regular Expression validator provide a step ahead functionality. 
                 For example if you want to validate to check the text box, to accept a valid Email address or phone no in a particular format at these times Regular Expression validator comes to picture.

Thursday, January 17, 2013

Validators In ASP.Net - Part 3 : Compare Validator

By Francis   Posted at   12:03 PM   Validators in ASP.Net No comments
Compare Validator
 
In this article, I’m going to explain about the compare validator. The compare validator is used to compare the values entered in a one input control with another constant value or value entered against in another control.


Friday, January 11, 2013

Validators in ASP.Net – A word about WebResource.axd

By Francis   Posted at   11:11 PM   WebResource.axd No comments

A word about WebResource.axd:

          Its time to speak about the resource files, (As validation controls concern) which is included whenever the validation controls included in a aspx page.

 In older version of ASP.Net, the file “WebUIValidation.js” has been directly pointed out thru <script> tag. As we all know “WebUIValidation.js” is resides on the web server’s .Net installation folder,

Thursday, January 10, 2013

Validators in ASP.Net – Part 2

By Francis   Posted at   12:36 PM   Validators in ASP.Net
Range Validator:
In my Previous post, I have explain about the Required Field Validator. In this article I’m going to explain about the Range Validator.Like Required Field Validator, Range validator is a server side control, which is used to validate a value falls between 2 values.

Friday, January 4, 2013

Validators in ASP.Net - Part 1

By Francis   Posted at   9:00 AM   Validators in ASP.Net

For any application, validation performs a key role. For this Microsoft provides the following types of validators:
1. Required Field validator
2. Regular Expression Validator
3. Range Validator
4. Compare Validator
5. Custom Validator
6. Validation Summary

Connect with Us