Google Search

Sunday, January 03, 2010

Set Page Position after asyncPostback

I will start this article, with one of the problem which I faced 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 1 . 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 because of 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..

Thursday, December 31, 2009

Visual Studio List of Some ShortCut Keys

Use these shortcut keys to save your time while working with Visual Studio.



Shortcut
Description
F3
Finds the next occurrence of the previous search text.
F5
Start debugging
F7
Jump to code behind file from .aspx files
F8
Moves the cursor to the next item, such as a task in the Task List window or a search match in the Find Results window. Each time you press F8, you move to the next item in the list.
F9
Toggle breakpoint
F12
Go to definition of identifier under cursor
Ctrl+F5
Start without debugging
Ctrl+F2
Jump to the Navigation Bar (hit TAB to get to the right side)
Ctrl+F3
Find word under cursor
Ctrl+TAB
Toggle between windows in Visual Studio
Ctrl+I
Incremental search (this is way better than Ctrl+F)
Ctrl+J
Force IntelliSense for field members
Ctrl+C (with nothing selected)
Copy whole line
Ctrl+Enter
Open line above line cursor is on
Ctrl-X or Ctrl-L (with nothing selected)
Cut whole line
Ctrl+]
Bounce cursor between matching parentheses/brackets/braces
Ctrl+PageDown
Toggle between Design and Source views in .aspx files
Alt+W, L
Close all windows
Ctrl+K, Ctrl+C
Comment out selection
Ctrl+K, Ctrl+U
Uncomment selection
Ctrl+K, Ctrl+D
Format document
Ctrl+K, Ctrl+X
Insert snippet (or just type in the snippet name and hit TAB, TAB)
Ctrl+K, Ctrl+S
Surround selected lines with snippet
Ctrl+K, Ctrl+K
Toggle bookmark on/off
Ctrl+K, Ctrl+P
Jump to previous bookmark
Ctrl+K, Ctrl+N
Jump to next bookmark
Ctrl+M, Ctrl+M
Open/close current fold
Ctrl+M, Ctrl+O
Fold all methods
Ctrl+R, Ctrl+R
Enables or disables word wrap in an editor.
Ctrl+Shift+B
Build solution
Ctrl+Shift+C
Displays the Class View window
Ctrl+Shift+Enter
Open line below line cursor is on
Ctrl+Shift+F
Global Search
Ctrl+Shift+F9
Delete all breakpoints
Ctrl+Alt+A
Displays the Command window, which allows you to type commands that manipulate the IDE.
Ctrl+Alt+I
Displays the Immediate window, where you can evaluate expressions and execute individual commands.
Ctrl+Alt+K
Displays the Task List window where you customize, categorize and manage tasks, comments, shortcuts, warnings and error messages.
Ctrl+Alt+L
Open the Solution Explorer (to find your file after you just closed them all)
Ctrl+Alt+T
View Document Outline
Ctrl+Alt+0
Displays the Output window to view status messages at run time
Ctrl+Alt+R
Open browser within VS.NET
Ctrl+Alt+U
Displays the Modules window, which allows you to view the .dll or .exe files used by the program. In multiprocess debugging, you can right-click and select Show Modules for all Programs.
Ctrl+Alt+X
Open Toolbox
Shift+Alt+Enter
View editor in full screen mode

Monday, November 30, 2009

Introduction to Jquery

Introduction

JQuery is a Java script libarary/ Java Script framework that simplifies the interaction process or access process of traversing in HTML document. It provides methods to make animations, add ajax interaction to the page, provides an easy way to apply CSS to any items and provides an easy mechanism for binding and unbinding events. Huge code written using Java script can easily replaced by few lines of code in JQuery.

History of JQuery

Initially it’s was released in January 2006 but the very first stable version of JQuery 1.0 was released in August 2006. This version had support for CSS, events and Ajax. After that many version of JQuery were released but the latest version is JQuery 1.3.2. You can download this from JQuery website.

What can be done using JQuery

1. Allows to access elements in the document

If one need to access the DOM tree without any JavaScript libarary, one has to write many lines of code. JQuery provides a selector mechanism to access any part of DOM.

2. Easily apply CSS

As it’s known that CSS is the most powerful and mostly used for good appreance of any webpage. JQuery provides CSS Selectors which allows to change the CSS classes or individual style for any portion of the document. This can be done even after the page is rendered.

3. Make Animation

For better user experience, animation can do the job for you. JQuery provides many methods to perform animations like show,hide, fade, wipe, start, stop etc. Doing all this with JQuery is fun as No huge lines of code, no complex logic.

4. Ajax Interaction

In today’s world, Ajax is one of the most popular technology used in almost every website for better user experience. Jquery provides support for ajax also which allows to access server side event without refreshing the web page.

5. API to change document’s content

JQuery provides API (Application Program Interface) which allows to change the content of the document. Changing Text, inserting images, ordering of list can be done with few keystrokes with JQuery API. Entire structure of HTML can be rewritten or extended.

6. Event handling

Any technology is a failure if it cannot responsed to the user when any event takes place. Jquerys’s event handling is one the decent feature. It quickly responsed to any event such as user clicking a button.

Demo

To start with JQuery, first download the Jquery from it’s official website (http://JQuery.com). Make sure you download the latest copy of the JQuery.

1<script src="Script/jquery.js" type="text/javascript"></script>

I have copied the jquery.js and placed it in script directory of the project. In this demo, I am going to show you how easily you can change the CSS and do animation.

Let’s first take a look at HTML

1<h2>
2History of JQuery</h2>
3<div id="content">
4Initially it's was released in January 2006 but the very first stable version of JQuery 1.0 was released in August 2006. This version had support for CSS,events and Ajax. After that many version of JQuery were released but the latest version is JQuery 1.3.2. You can download this from JQuery website.
5</div>

As you can see, I have placed a div tag with it’s ID set to content. Now, I will show you how you can find the div and apply CSS to it using JQuery.

01<style type="text/css">
02    .ApplyColor
03        {
04            background-color: Gray;
05            font-family: Arial;
06            font-size: 10pt;
07            color: White;
08        }
09    h2
10        {
11            font-size: 20pt;
12        }
13</style>
14 
15<script type="text/javascript" language="javascript">
16 
17    $(document).ready(function() {
18        $('#content').addClass('ApplyColor');
19    });
20</script>

.ready() is a jQuery event handler. This particular event handler will execute when the document is ready to be accessed and scripts have completed loading. A .ready() handler can be placed anywhere on the page and you can even have multiple ready handlers in the page.

Now, if you run this page, you will see the div with content id is having gray background and white color foreground.

Let’s go to the animation part with JQuery.

Place a button and some text in Paragraph tag. Using JQuery, I will add a click event handler.

1<asp:Button ID="btnShow" runat="server" Text="Show" />
2<p style="display: none;background-color:Red">
3    Hello
4</p>

Now add this Jquery code to document.ready event

01<script type="text/javascript" language="javascript">
02 
03    $(document).ready(function() {
04        $('#btnShow').click(function() {
05              $("p").show("");
06              return false;
07        });
08    });
09 
10</script>

Above code will find the btnshow and add a click event handler to it. When the button is click then Jquery will find the p tag and make a call to show function which will display the content of the p tag on the screen.

Like wise there are many more functions for animation. You can find the whole list over here.

Reference

http://jquery.com/

Conclusion

This is just an overview of starting with Jquery. Many more complex things can be done via jquery with ease. Go to this main page of Jqueryand learn as much as you can.

Happy Programming…

Virendra Dugar :)

Blogged with the Flock Browser

Difference between C# and VB.NET

This question is asked almost in every interview, if you have worked with both the language. There are syntax difference, keyword difference in both the language. But the interviewer is not looking for such answers. One need to explain the functional difference between both the languages.

Here are some key difference in C# and VB.NET other than syntax differences.

  1. In C#, using keyword is used to release unmanaged resources. (Not available in VB.NET)
  2. Optional parameter is supported in VB.NET. (Not available in C# 3.0 or below version).
  3. Structure and unstructured error handling (On Error GoTo) is supported in VB.NET. (Unstructured error handling is not supported in C#).
  4. Event gets bind automatically in VB.Net.
  5. VB.NET is not case sensitive where C# is.
  6. Shadowing: – This is a VB.Net Concept by which you can provide a new implementation for the base class member without overriding the member. You can shadow a base class member in the derived class by using the keyword “Shadows”. The method signature, access level and return type of the shadowed member can be completely different than the base class member.

    Hiding: – This is a C# Concept by which you can provide a new implementation for the base class member without overriding the member. You can hide a base class member in the derived class by using the keyword “new”. The method signature, access level and return type of the hidden member has to be same as the base class member.

    Comparing the two:-
    1) The access level, signature and the return type can only be changed when you are shadowing with VB.NET. Hiding and overriding demands these parameters as same.
    2) The difference lies when you call the derived class object with a base class variable. In class of overriding although you assign a derived class object to base class variable it will call the derived class function. In case of shadowing or hiding the base class function will be called.

  7. Visual Basic .NET can also force parameters to be passed by value, regardless of how they are declared, by enclosing the parameters in extra parentheses. There is no way to achieve this thing in C#.
    For Example:
    1Dim y As Integer = 5
    2Dim z As Integer
    3z = Add(y) //This will set both Y and Z to 6.
    4z = Add((y)) //This will set Z to 6 but Value of Y will not be change, as we have included extra parenthese while calling.

    The Add function:

    1Public Function Add(ByRef x As Integer) As Integer
    2x = x + 1
    3Return x
    4End Function

I know this is not a complete list, so if you know any other difference kindly post your comments.

Enjoy..

Friday, November 27, 2009

AsyncFileUpload Control - New Control in Ajax Control 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".
  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.
  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(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
    }

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

    Creating C# and VB.NET classes together using App_Code folder


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


    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

    public class Class1
    {
        public static string HelloWorld()
        {
            return "Hello World From C# Method";
        }
    }
    

    Similarly, add the following code in Class2.vb.

    Imports Microsoft.VisualBasic
    Public Class Class2
        Public Shared Function HelloWorld() As String
            Return "Hello World From VB.NET Method"
       End Function
    End Class

    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 tells us that we can not use different coding languages for the classes in App_Code folder. So does it mean that it's not possible. Well fortunately, there is a way to come over of this trap. First 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 what you want to do.

    <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 the following markup to it to web.config file:

    <compilation debug="true">
    <codeSubDirectories>
      <add directoryName="CSCode"/>
      <add directoryName="VBCode"/>
     </codeSubDirectories>
    </compilation>
    
    The section defines a set of sub-directories under the 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….

    Tuesday, March 31, 2009

    SessionID changes with every request in the asp.net 2.0 application

    For any web programmer, its obvious to think and believe that SessionId remains same through out the user session and it was right till asp.net1.1. But in asp.net2.0, this behavior has changed. In the asp.net application new sessionid is returned with the response to every request until session objects are not used.


    According to MSDN the reason/solution is:
    "When using cookie-based session state, ASP.NET does not allocate storage for session data until the Session object is used. As a result, a new session ID is generated for each page request until the session object is accessed. If your application requires a static session ID for the entire session, you can either implement the Session_Start method in the application's Global.asax file and store data in the Session object to fix the session ID, or you can use code in another part of your application to explicitly store data in the Session object."


    Click here to view the article.


    Enojy...

    Google Ads