public knowledge blog_load(sender Virendra)

                                                                                                                          Nothing shocks me, I am a Software Engineer.

Archive for the ‘ASP.NET’ Category

Set Page Position to Default after asyncPostback in AJAX

Posted by Virendra Dugar on January 20, 2010

Introduction

I will start this article, with one of the problem which I come across recently.

Background

I was working with a page. The page is divided into two parts.

1. Add/Update/Delete (I call it Area 1)
2. Listing of records (I call it Area 2)

I have used Repeater control with no paging (Though the records are more but my client hates paging.). Above the repeater control, there were some textbox, dropdowns, checkbox, listbox etc. were placed used for add/update operations. There is a link button in the repeater control for every row, which when clicked opens the records in update mode. It fills all the control with data placed on Area.
*Everything is placed in an UpdatePanel.

Problem

There were more than 10000 records listed in the repeater. When I click the very last record for editing, asynchronous postback happens and data is loaded for editing in Area 1 . But the problem was with the page position. I was not able to see the control’s of Part1, as page was maintaining it’s scroll position after async postback. This is what I don’t want. As it’s not at all user friendly. End-User will never come to know that record has been opened in edit mode. I set the “MaintainScrollPositionOnPostback” property to false but it was not working due to AJAX. Somehow, I want page position to be set to (0,0) so that I can see Area 1 controls.

Solution

The solution was to set Page position back to 0,0, at the end of ajax request. Here is what I did. See below code.

<script type="text/javascript">
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_endRequest(EndRequestHandler);
    function EndRequestHandler(sender, args) {
        window.scroll(0,0);
   }
</script>

Javascript provides a function scroll() which basically scrolls page position to the specified value. It takes two arguments Top and left. I passed it 0,0 and it worked for me.

Enjoy..

Advertisements

Posted in Ajax, ASP.NET | Tagged: , | Leave a Comment »

AsyncFileUpload Control – New Control in Ajax Control ToolKit

Posted by Virendra Dugar on October 6, 2009

I have already posted an article on new release of AjaxControl ToolKit.

Ajax Control Toolkit is not new for every dotnet developer. A new version of the AJAX Control Toolkit is now available for download from the CodePlex website. This new version of the AJAX Control Toolkit contains two new controls:

SeaDragon Java Script Code (SJC) – The SJC control allows you SeaDragon scripts are used to display an image, and to zoom in and out of that image using mouse button keys without resizing the window. I saw the demo and it’s really cool control.

AsyncFileUpload – Finally, we have a control which uploads file asynchronously. This new control enables you to perform file uploads without doing a postback. The control displays a throbber image during upload and raises client and server events when the upload is complete. Check the live demo here.

In this article, we are going to take a look at AsyncFileUpload control.

Note: This control will only work with .NET 3.5 or higher version.

AsyncFileUpload Control Features

As we know, File Upload control of ASP.NET does not work with in update panel. If we want to place it in update panel, then also postback trigger is required to upload the file. This cool control allows you to upload the file in asynchronous manner. Below are few key points about this control:

  1. It works within the Update Panel.
  2. Uploads the file without any postback.
  3. Provides Client Side and Server side events.
  4. Different coloring options for showing file upload. As for example, it shows green color if upload is successful, otherwise it shows red if there is unsuccessful upload.
  5. You can show the loading image while file uploading is in progress.

But it also comes with certain disadvantages.

  1. When I was working with the control, once the file is uploaded there is no way to clear the content of file upload control.
  2. I went into the source code of this control and noticed that the control stores the file in Session. It never clears the session, which means every time to navigate back to the page it loads the last file uploaded into the text box.
  3. There is no way to cancel the upload.
  4. There is no way to monitor the progress (How much % is completed) of uploading.
  5. Uploading starts as soon as you select the file. It stores the files in the session.

Besides, these disadvantages control looks good.

Now let’s go thru some of the properties of this control.

Properties and Methods

Some Available Properties

  1. CompleteBackColor : This Property set the background color of the control on successful upload. Default Value is “Lime”.Image1
  2. ErrorBackColor : This Property set the background color of the control on unsuccessful upload. Default Value is “Red”.

  3. UploadingBackColor : This Property set the background color of the control when file uploading is in progress.Image2
  4. UploaderStyle : There are two options available for styling of the control. Traditional and modern. Default is “Traditional”.

  5. ThrobberID : ID of control that is shown while the file is uploading. It will be used to display the loading/in progress image.

  6. HasFile : Returns a bool value which indicates control has a file or not.

Available Events:

  1. OnClientUploadError : This is a client side event. If there is an unsuccessful upload then specified JavaScript function will be executed.

  2. OnClientUploadStarted : This is also a client side event. Specified JavaScript function will be called when the uploading start. This event will be called before uploading and once this function is executed, uploading will start.

  3. OnClientUploadComplete : This is also a client side event. If there is successful upload then specified JavaScript function will be executed.

  4. onuploadedcomplete : This is a server side event which will be executed once the uploading is complete. One thing to notice over here is, as soon as you select the file, uploading starts but it remains in session. It is not stored on any physical location. In this event, we can specify the path and save the file into physical location.
    Things will be clear once we go thru the code.

Available Methods:

  1. SaveAs() : This method saves the file on specified path.

Demo

Let’s create a new website and add reference of newly downloaded AjaxControl ToolKit dll. On default.aspx page, Place a script manager and register the ajax control toolkit dll.

Now let’s place the AsyncFileUpload control.

< cc1:AsyncFileUpload ID="AsyncFileUpload1" Width="400px" runat="server"

OnClientUploadError="uploadError" OnClientUploadStarted="StartUpload"

OnClientUploadComplete="UploadComplete"

CompleteBackColor="Lime" UploaderStyle="Modern"

ErrorBackColor="Red" ThrobberID="Throbber"

onuploadedcomplete="AsyncFileUpload1_UploadedComplete" UploadingBackColor="#66CCFF" />

We can place this within update panel or outside the update panel. As you can see, I have set the most of the properties and events which I have already explained above. Let’s place the Throbber control to show in progress image. It is not compulsory to have ThrobberID. If it is set then it will display the content of the control.

< asp:Label ID="Throbber" runat="server" Style="display: none">;
          <img src="Images/indicator.gif" align="absmiddle" alt="loading" />;
</asp:Label>

I have also placed a label on the page, which shows the status of the uploading. Value of this control get’s updated via Client Side function.

< asp:Label ID="lblStatus" runat="server" Style="font-family: Arial; font-size: small;"> < /asp:Label>

Let’s place the JavaScript functions.

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

function uploadError(sender,args)
{
  document.getElementById('lblStatus').innerText = args.get_fileName(), "&lt;span style='color:red;'&gt;" + args.get_errorMessage() + "&lt;/span&gt;";
}

function StartUpload(sender,args)
{
    document.getElementById('lblStatus').innerText = 'Uploading Started.';
}

function UploadComplete(sender,args)
{
  var filename = args.get_fileName();
  var contentType = args.get_contentType();
  var text = "Size of " + filename + " is " + args.get_length() + " bytes";
  if (contentType.length &gt; 0)
  {
    text += " and content type is '" + contentType + "'.";
  }
  document.getElementById('lblStatus').innerText = text;
}
</script> 

The UploadComplete function displayes the file name, it’s size and content type on the screen.
Below is server side code of UploadedComplete event.

protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
    System.Threading.Thread.Sleep(5000);
    if (AsyncFileUpload1.HasFile)
    {
	string strPath = MapPath("~/Uploads/") + Path.GetFileName(e.filename);
	AsyncFileUpload1.SaveAs(strPath);
    }
}

That’s it. We are good to go now. Now just run the application.

Conclusion

This is a cool control which some good user experience but as stated above I cannot find a way to clear the content of the control even if you refresh the page. Another thing that is quite annoying is as soon as you select any file, it starts uploading. Another lacking feature is it does not show the progress in percentages. Despite, few disadvantages, I found this control pretty useful. Hope to see some enhancement in this tool.

Enjoy..

Posted in Ajax Control Toolkit, ASP.NET | Tagged: , | 3 Comments »

Execute Web Service via GET Method

Posted by Virendra Dugar on September 8, 2009

When we created any web service via Vistual Studio, we always get a default method named “Hello world”.

When you hit this URL in your browser, http://localhost/SampleWebService/Service.asmx, it shows list of all the web method. Click on Hello World and then Invoke. It gives following output:

I am assuming that you have hosted your web service in IIS.

<?xml version=”1.0″ encoding=”utf-8″ ?>
<string xmlns=”http://tempuri.org/“>Hello World</string>

Looks good. Now let’s go and modify our service.cs file and add a new method which takes one parameter.

[WebMethod]
public string HelloWorldWithParam(int a)
{
return "Hello World " + a.ToString();
}

Now, hit this URL http://localhost/SampleWebService/Service.asmx. It is showing both the methods.

WebService

Click on HelloWorldWithParam. It asks for parameter value. Without giving any value just click invoke.

WebService1

It shows following error:

Error1

Above error is coming as method is expecting a value, and method tries to convert null value to string. If you refresh your browser then following error comes:

Error

Now let’s provide the parameter value via URL only. Hit this URL, http://localhost/SampleWebService/Service.asmx/HelloWorldWithParam?a=1 , and then also you will receive the above error.

Reason: By default, Web service created via Visual Studio executes through HTTP Post method. When Post method is used, querystring is not visible. We need to configure our web service, so it works with HTTP GET and POST method. How can we do this?

Go to web.config and add this code in system.web section.

<webServices>
      <protocols>
        <add name=”HttpGet”/>
        <add name=”HttpPost”/>
      </protocols>
</webServices>

Good to go now. Hit this URL again and this time you will see “Hello World 1”.

Enjoy….

Posted in ASP.NET | Tagged: | 1 Comment »

Difference between Theme and StylesheetTheme attribute

Posted by Virendra Dugar on August 31, 2009

Learn new ASP.NET Core 1.0 Framework

The Page directive includes the attribute Theme and StylesheetTheme.You can use both to apply themes to a page. So, the question is: If you have a Theme attribute and a StylesheetTheme attribute for the Page directive, what is the difference between the two?

The StylesheetTheme attribute works the same as the Theme attribute. The difference is that the when attributes are set locally on the page within a particular control, the attributes are overridden by the theme if you use the Theme attribute. They are kept in place, however, if you apply the page’s theme using the StylesheetTheme attribute. Suppose you have a text box control like the following:

 

In this example, the ForeColor settings is overridden by the theme if you have applied theme using the Theme attribute in the Page directive. If, you applied the theme using the StylesheetTheme attribute in the Page directive, the ForeColor settings remain in place, even if they are explicitly defined in the theme.

Quick summary of what’s changed in ASP.NET Core 1.0

Enjoy…

Posted in ASP.NET | Tagged: | 1 Comment »

Access ViewState Across the Pages

Posted by Virendra Dugar on July 2, 2009

Before I start this article, Let me ask you something. Is it possible to access the ViewState variable of one page to another page? I don’t know what is your answer. Well, frankly speaking, My answer was  also “NO”  before writing this article As it is said that ViewState is page specific that means it is available on the same page only on which it is created. Once you redirect to another page, previous page viewstate is no more accessible. But that is not true.Yes, we can access the viewstate variables across the pages. This is only possible if Cross Page Posting or Server.transfer is used to redirect the user on other page. If Response.redirect is used then ViewState can not be accessed across the pages.

Before you go down, Please read these articles on Cross Page Posting and Server.transfer.

Ok, So all set now.. I will demonstrate this using the demo created by me. You can download the demo from here.

I have created two .aspx page named
1. ViewStateContainer.aspx : This page set the ViewState variable and transfers the user to another page using Server.transfer.
2. AccessViewState.aspx : This page access the ViewState variable of ViewStateContainer.aspx Page.

This is the code of ViewStateContainer.aspx Page :

ViewState Container Page

As you can see, I have set a ViewState variable in Page Load and transfers the user to AccessViewState.aspx page using Server.transfer() method.
This page also contains a method ReturnViewState() which actually returns the ViewState of this page to the calling function. Return type of the method is StateBag Class.

StateBag Class : This class is the primary storage mechanism for all HTML and Web server controls. It stores attribute/value pairs as strings associated with the control. It tracks changes to these attributes only after the OnInit method is executed for a page request, and saves the changes to the page’s or control’s view state.

Now let’s take look at AccessViewState.aspx Page code:

Access View State

Whenever we use Server.transfer or Cross Page Posting, We can get the previous page object via PreviousPage Property. Using Previous Page, we can find the controls of previous page. As for example, One can access Label control placed in ViewStateContainer Page in Current Page.

Looking at the code, I have created a PreviousPageViewState property in this page, which returns the previous page’s ViewState. It first checks whether PreviousPage is null or not, if it’s not null then create an object of the previous page. Now using Reflection, we can invoke the method of the previous class. Using MethodInfo class, I have invoked the ReturnViewState() method of ViewStateContainer Page.

In Page_Load event, I am able to access the ViewState variable of  ViewStateContainer Page. You can access all the viewstate variables set in ViewStateContainer Page.

Enjoy..

Posted in ASP.NET | Tagged: | Leave a Comment »

Get size of a file placed on any web server

Posted by Virendra Dugar on June 25, 2009

Download Source Code

This post demonstrate you that how can you find the size of file which is placed on any webserver.

I have placed a label, a textbox and a button on an aspx page.  Textbox will be having valid URL with the file name.
i.e. http://www.abc.com/xyz.pdf

On button click, Place this code

Code

That’s it..

Enjoy…..

Posted in ASP.NET | Tagged: | Leave a Comment »

Using C# and VB.NET classes together in the App_Code folder

Posted by Virendra Dugar on June 15, 2009

Download Source Code

Learn new ASP.NET Core 1.0 Framework

In ASP.NET 2.0 one can mix web forms coded in C# and VB.NET together in a single web site. This works great for web forms. However if you want to code classes from App_Code folder in different languages? Such mixing of classes coded in different languages is not allowed with default settings. You can, however,configure your web site to get this done. This article is going to explain you that how one can do that.

Creating sub folders and classes

First of all, Create a new webSite in VS.NET 2005. Add App_Code folder to it. You can do so easily by right clicking on the web site in the Solution Explorer and choosing Add ASP.NET Folder” option (see below).

Different Language

Once you add the App_Code folder add two class files – Class1.cs and Class2.vb. Note that one class file must be in C# where as the other must be in VB.NET. Add the following code in Class1.cs.
C# Code

Similarly, add the following code in Class2.vb.

VB.NET Code

Both of these classes contain a method called HelloWorld() that simply return a string to the caller.

Now try compiling the web site. What happens? You will get an error as shown below:

Error 1 The files ‘/VBandCSharptogether/App_Code/Class2.vb’  and ‘/VBandCSharptogether/App_Code/Class1.cs’ use a
different language, which is not allowed since they need to be compiled together.

The error message bluntly tells us that you can not use different coding languages for the classes in App_Code folder. Fortunately, there is a way to get out of this trap. Firstly you need to put C# and VB.NET classes in separate sub-folders under App_Code. Secondly you need to add some markup in the web.config file to tell ASP.NET compiler about your intention.

<codeSubDirectories> Section

Create two folders under App_Code filder named CSCode and VBCode. Move Class1.cs inside CSCode folder and Class2.vb inside VBCode folder.

Add a web.config file to your web site and add the following markup to it:

Web Config Code

Here, we added <compilation> section. The <codeSubDirectories> section defines a set of sub-directories relative to App_Code folder that are compiled at run time. The directoryName attribute points to the sub-folder of App_code. Each sub folder is compiled separately and hence each can have classes coded in different languages. We added our CSCode and VBCode folder in this section. This way the compiler will compile classes from CSCode and VBCode folders separately.

After configuring the web site try to compile it. This time it compiles successfully.

Enjoy….

Quick summary of what’s changed in ASP.NET Core 1.0

Posted in ASP.NET, C#, VB.NET | Tagged: , , | 17 Comments »

Exception Handling Best Practices in .NET

Posted by Virendra Dugar on June 10, 2009

Check out this cool article on code project by Daniel Turini on best practice of Exception Handling in .NET.

A very good article indeed.

Enjoy…

Posted in ASP.NET | Tagged: | Leave a Comment »

Textbox with autopostback and regularexpression validator

Posted by Virendra Dugar on June 5, 2009

Quick summary of what’s changed in ASP.NET Core 1.0

Suppose you have a textbox on your aspx page that has a autopostback set to true and It makes a call to server side function on TextChanged Event. You have also placed a RegularExpression Validator which validates the textbox value against the validation expression.

For example: You want to allow only numeric characters in the text box and you have placed a regular expression validator to achieve this. And you also want to do some server side operation on text change.

 TextBox and RegularExpression Validator
When you run the application and if you type any alphabets in the textbox, the regular expression validates the input, it shows the error message but the weird thing is it also does the post back and call the server side text change event and error message is gone. This is what you don’t want. TextChange event must be called only when inputs are correct. Then how do you do this?

A very simple solution. Just set the CausesValidation="true" for the textbox and you are done.

Enjoy…

Learn new ASP.NET Core 1.0 Framework

Posted in ASP.NET | Tagged: | 11 Comments »

ASP.NET Best Practices

Posted by Virendra Dugar on May 29, 2009

Check out these articles that explains the best pratices for ASP.NET to improve application performance.

Enjoy…

Posted in ASP.NET | Tagged: | 1 Comment »

 
%d bloggers like this: