Ayo Softech

Monday 29 July 2013

How to Call Function in Client/Designing Side in asp.net?




Cliet Side
<asp:ListView ID="ListView3" runat="server">
     <LayoutTemplate>
         <tr id="ItemPlaceholder" runat="server">
         </tr>
     </LayoutTemplate>
     <ItemTemplate>
          <tr class="odd gradeX">
              <td>
                    <a href="#myModal1" role="button" data-toggle="modal">Anonymous Responses(<asp:Label ID="Label4" runat="server" Text='<%# Respons(Eval("ID").ToString()) %>'></asp:Label>)</a>
               </td>
          </tr>
     </ItemTemplate>
</asp:ListView>

Server Side

public string Respons(string ID)
        {
            string CID = "V" + ID.ToString();
            return DB.Responses.Where(p => p.CategoryID == CID).Count().ToString();
        }

Wednesday 10 July 2013

Navigate to previous page in Asp.net

There are various ways using which you can navigate back to the previous page. To keep the example short and simple, I will be using two pages and a few buttons to demonstrate the navigation. So let us get started:
Step 1: Create an ASP.NET Project with two pages, Page1.aspx and Page2.aspx.
Step 2: On Page1.aspx, drag and drop a button control. In the click event, use this code:

protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Page2.aspx");
}
Step 3: On Page2.aspx, we will be dragging and dropping 3 buttons. Each button will represent a method to go back to the previous page. Let us explore them one at a time:
Method 1 – Using a static variable and UrlReferrer
URLReferrer gets the URL of the previous page that linked to the current URL. To use this property, declare a static variable called ‘prevPage’ in Page2.aspx. Drag and drop a button, button1 on Page2.aspx. On the Page_Load, use the Request.UrlReferrer to populate the prevPage variable with its value. Then on the button1 click event, use this variable to go back to the previous page as demonstrated below :
// static variable
static string prevPage = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if( !IsPostBack )
{
prevPage = Request.UrlReferrer.ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect(prevPage);
}
Method 2 – Using Javascript
Drag and drop another button called button2 on the Page2.aspx. In the Page_Load event, add the following lines of code :

protected void Page_Load(object sender, EventArgs e)
{
Button2.Attributes.Add("onClick", "javascript:history.back(); return false;");
}
protected void Button2_Click(object sender, EventArgs e)
{
}
 
Note : Notice the ‘return false’ snippet used in the Button2.Attributes.Add method. Well this is used to cancel the submit behaviour that occurs on the button click. Since the Click event precedes over the other events, we need to return false to cancel the submit and go back to the previous page.
 
Method 3 – Using ViewState
If you do not intend to declare a static variable, you can use viewstate to go back to the previous page by using the same UrlReferrer property that we used in Method 1. To do so, drag and drop a third button, Button3 on Page2.aspx. In the Page_Load event, use the ViewState to store the value of the Request.UrlReferrer property. Then access the same value in the click event of the third button to go back to the previous page as shown below:
protected void Page_Load(object sender, EventArgs e)
{
if( !IsPostBack )
{
ViewState["RefUrl"] = Request.UrlReferrer.ToString();
}
}
protected void Button3_Click(object sender, EventArgs e)
{
object refUrl = ViewState["RefUrl"];
if (refUrl != null)
Response.Redirect((string)refUrl);
}

How to refresh a ASP.Net Page from CodeBehind ? OR Automatically Refresh aspx Page at Regular Intervals

We can refresh a webpage with the help of meta tags at regular intervals. When we place the below meta tag in head tag, it will refresh your webpage automatically every 100 seconds.
<meta http-equiv="refresh" content="100">

At times, we might want to conditionally refresh an ASPX page automatically from codebehind file.
With the introduction of ASP.Net 2.0, we can set Meta tags dynamically from codebehind class using HtmlMeta class.

To refresh our aspx page from the codebehind class we can use the following code,

public void RefreshPage()
    {
HtmlMeta meta = new HtmlMeta();
HtmlHead head = (HtmlHead)Page.Header;
meta.HttpEquiv = "refresh";
meta.Content = "5";
head.Controls.Add(meta);
}


The above code will emit appropriate meta tags similar to above to refresh the page automatically every 5 seconds.

What is the difference between autopostback and ispostback in Asp.Net?

Autopostback - Property of the control.

IsPostback - Property of the Page class.

Autopostback - get and set property to control postback on changes made for control.
for e.g.
this.ListBox1.AutoPostBack = true;
whenever user will select item the page will get post back.

IsPostback - get property of the Page class to check if page is post back i.e. if it is true then page has already executed Init function of the page else it is first time the page has requested to be executed.

Tuesday 2 July 2013

Interesting New Features of VS2012

Introduction

Usually we try and find distinctive function in the new release, but my article is to find simple yet useful features included in VS2012.

Features for this Article

Image Thumbnail:   

In the solution explorer, we can add Images. The moment you bring your pointer on the image you can its thumbnail image. It make easy to identify the images.

Page Inspector:   

When we have nested pages like if in MVC partial pages, in .net pages inside master page, it becomes very difficult to find with part of the code is responsible for the HTML being generated.  Here comes another useful feature if for a specific page u want to inspect, and then right click on the page. You can see the option "View in Page Inspector".
The moment we choose Inspector, we can see the page in this format:
Whatever we select in the browser window, its HTML is shown below it and the page responsible for that HTML is shown on the right. Earlier we use to run the code, then use tools like firebug to inspect it and for any change we have to stop the solution, apply the changes and run again to see its reflection. But with this option we can apply changes and see its reflections. For this feature we require IE9.

Color Picker: 

A feature which most of the developers need, as its difficult for them to remember the color name, if they get the color picker it’s easy to set the color. VS2012 provided inbuilt color picker for CSS. Just type # before the color and you can see the color picker. Select any color of your choice and the code gets added.

IIS Express:

VS2012 has IIS express as its default server.  IIS Express is a lightweight, self-contained version of IIS that contains all the core capabilities of the IIS web server role. In Visual Studio 2010 SP1, IIS Express was available as an option that you had to explicitly configure. IIS express following features
  • It does not run as a service or require administrator user rights in order to perform most tasks.
  • IIS Express works well with ASP.NET and PHP applications.
  • Multiple users of IIS Express can work independently on the same computer.
For more information visit IIS Express Overview

Tag completion when renaming tags: 

HTML Editor has a beautiful facility while renaming a tag. For example if you have added a <div id="div1">Name</div>. After writing you felt instead of div you must take a span, the moment to change the div word to span automatically the closing tag will be changed to </span>. This will help the developers from getting the UI issues because of the closing tag missing.

Extract to user control:  

When we have large web page, we can pick some control from the source view and create a user control for the same. This helps in improving the readability of the page.
Select the controls--> Right click your mouse and select Extract to User Controlà Give name to your control and the entire line of code will be replaced by one single control. 

Event Handler:  

The moment we add any Asp control and wants to manage its event handler, VS2012 IntelliSense displays <Create New Event>, which creates an event handler in the code view with the right signature.



AntiXSS Library: 

AntiXSS Library which was part of .net 4.0 but was external, now it’s being included in 4.5. If your page requires HTML-formatting then the page becomes insure and inorder to protect your page from cross-site scripting attacks you need to include AntiXss library.
The AntiXSS library in 4.5 include following external features:
  • HtmlEncode, HtmlFormUrlEncode, and HtmlAttributeEncode
  • XmlAttributeEncode and XmlEncode 
  • UrlEncode and UrlPathEncode (new)
  • CssEncode

Multiple browser support: 

All the browser’s installed in your system can be used to test the application. It becomes easy if your application is supporting multiple browsers. You can see the UI in all browsers supported. 

Round Tripping


A very important feature, this is required when we are upgrading from older version to new version say from VS2010 to VS2012 and you want your project should work in both VS2010 and VS2012. Round Tripping helps to work with existing Visual Studio 2010 projects, it’s easy to upgrade project to VS2012, and we can use both VS2012 and VS2010 at the same time. 

Summary

I have created a sample application using all the above mentioned features. It has become really very interesting when trying to go deep in these features and there are many more to explore. I have studied other features related to the data controls, validations. Will surely try to include them in my next extension of the article.
While writing the article, i have refered following site What's New in ASP.NET 4.5 and Visual Studio 2012

Continuation

Let's start with some more interesting features.

Background 

In my previous part, I tried to figure most and basic functions, yet I felt are very useful. In this article I am trying to cover some simple and some interesting features

JavaScript Matching Braces

If we are writing any function in JavaScript which has too many opening and closing braces, and if we miss one of the closing braces, then it becomes very difficult to identify which opening braces closing is missing. With .NET 4.5 we can select the braces and it tells its closing braces, so it becomes easy to identify the nesting structure.

JavaScript Code outlining:  

Till the previous versions outline was supported only for .cs or .aspx file, now outlining regions are available in JavaScript too. It helps us to collapse the file or function which is currently not the part of our focus.

Request Validation: 

Cross scripting is a security threat, when a developer is allowing script and HTML tags. But in many situations we need our page to support HTML and scripts. In such situations .NET 4.5 provides us with two features
Deferred "lazy" request validation- for selective part  Access to unvalidated request data Whenever a request is made, it’s always validated for the complete data and if it is turned off then it is not validated at all. Using Lazy request validation only required data will be validated. To enable lazy request validation set "requestValidationMode" attribute to "4.5" in "httpRuntime" element in web.config.

How this will work, let’s take a simple example if I wish to validate data when a particular button is clicked, in such scenario, I don’t want when the page load the request should be validated, it should be validated whenever the button is clicked. This was not possible with the earlier versions of .Net, but now lazy request validation will do the same in .NET 4.5.
 It can be used like:
  • Request.Unvalidated.Cookies["Name"]  
  • Request.Unvalidated.QueryString["VarName"] 
  • Request.Unvalidated.Form["Value"]   
Example: I have added two asp textboxes and one asp button. I have set the requestvalidationmode to 4.5. The moment I tried to enter the string with HTML tag. I get the error "Potential dangerous request………"
 
This is my code

    The moment I replace the asp textbox server control with simple HTML control and click the submit button. It works fine. The structure looks like this:
  Now lets access the same from the code: Again I get the same error "Potential dangerous request………" But again I try to access the page by a slight change in the code and it works fine.
Now coming back to asp textboxes that means server controls, .Net tries to use the posted data to maintain the view state, so will get the error. In order to avoid this .net has introduced "ValidateRequestMode" feature. We can set as "disabled" for the textbox for which we don’t want the server to request validation.
  After adding ValidateRequestMode, it works fine. This feature is important, as earlier we use to set validation request to false at the page level and the entire page becomes open for cross scripting. But with this feature only a part is open and remaining page is secure from XXS attacks.

CSS Editor:Hierarchy Indentation:  

The moment we create hierarchy with CSS it automatically gets indented and we can see the inheritance.  Hierarchical indentation is enabled by default, butif user wishes can even disable it. To turn off select Tools->Option->Text Editor->CSS-> Formatting 

In the figure below, you can see 3 level hierarchy, first level is the  div, then next is anchor inside div and third level is hover on anchor inside div.

Pin Tabs(files) that you use often to the left side of the Tab-well

This is a feature found in Productivity Power Tools for Visual Studio 2010 this allows you to pin tabs that you want to remain open and easily accessible. When you pin a tab it is stuck to the left most corner of the tab-well.



VisualStudio2012-PinTab


Search option in IDE windows

Many of the windows in Visual Studio 2012 will have a search option including Solution Explorer and Toolbox.



VisualStudio2012-Search-in-Windows

Find and Replace window changes

A minimalistic approach has been taken in designing the new find window present in Visual Studio 2012. The advantage is that the find window will not hide the code window much. Some may miss the old find window which shows shortcuts to turn on/off options like Match Case, Match whole word, etc. This resembles the search option found in modern browsers.
Visual-Studio-2012-Find


Visual-Studio-2012-Find1

Create Multiple Solution Explorer Instances

Nowadays, in most solutions you work on, the number of projects present are many, but you work only with few of them depending upon the role you play in the project. Visual Studio 2012 gives you a new feature of creating Solution explorer instances showing only a project or folder containing a set of files when you right click them as shown below.
Visual Studio 2012-Multiple Solution Explorer Windows
Visual Studio 2012-Multiple Solution Explorer Windows-Product Folder

Page Inspector

Page inspector is another new feature in Visual Studio 2012, it allows you to examine the html/css of a web page similar to IE Developer Tool Bar or Firefox’s Firebug add-on.
You can inspect a HTML element’s HTML and CSS, make edits and try out how it will look in the browser on the fly.
(click to enlarge)
Visual Studio 2012-Page Inspector

IIS Express replaces the ASP.NET Development server

In Visual Studio 2012, IIS Express replaces the ASP.NET Development server, more about IIS Express here.

HTML5 & CSS3 support

The Visual Studio 2012 editor supports development of HTML 5 and CSS 3 web sites by providing appropriate intellisense and code snippets, will write a future article about this.

Unmodified Visual Studio 2010 project files

Visual Studio 2010(SP1) project files are not converted when opened in Visual Studio 2012. So if some of your team members use Visual Studio 2010 and you use Visual Studio 2012 for some reason, then you all can share the same solution/project file without converting to Visual Studio 2012’s project file format.


How to check Email functionality without using SMTP Server ?

How to do That ?
Some situations arise when you need check email functionality without using SMPT server.So at that time you can use below mentioned configuration on web.config file. 
Just configure your .NET application to drop e-mails into a specified folder instead of sending them via SMTP server:

web.configuration File

<system.net>
   <mailSettings>
    <smtp deliveryMethod="SpecifiedPickupDirectory">
     <specifiedPickupDirectory pickupDirectoryLocation="c:\Test\" />
    </smtp>
   </mailSettings>
</system.net>
Note:
This will instruct SmtpClient class to generate mail message and save it as .eml file and drop it 
into c:\Test\  folder.

How to Improve jQuery Selector Performance ?

What is a jQuery ?
  • jQuery is a lightweight, "Write Less, Do More", JavaScript library.
  • The purpose of jQuery is to make it much easier to use JavaScript on your website.
  • jQuery takes a lot of common tasks that requires many lines of JavaScript code to accomplish, and wraps it into methods that you can call with a single line of code.
  • jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.
                              What is a DOM ?
                                      - Document Object Model
                                      - is the Backbone of every webpage
                                      - web browser parses HTML and Javascript and maintains
                                        a Data Model of what should be displayed to the user 

The jQuery Library Contains the Following Features:
  • HTML/DOM manipulation
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities
  • jQuery has plugins for almost any task out there.
What is a jQuery Selector?
  • A Selector identifies an HTML element tag that is used to manipulate with jQuery code. 
  • Selectors allow page elements to be selected

Selector Syntax 

$(Selector Expression)          OR      jQuery(Selector Expression)

What are the Types of jQuery Selectors?

1. Class Selectors
       $(".intro")  - All elements with class="intro"

2. ID Selectors
       $("#lastname")  - The element with id=lastname

3. Element Selectors
       $("p")   - All p elements

How to Caching jQuery Selectors ?

What is Happening When We use Selector ?
  • jQuery Traverses through all Elements of DOM every time

How Can Overcome this?
  • You should Always Cache your Selections to some variable
Its Like this :
      var myList = $('.myList');
      myList.text("cached");
When to Use ?
  • Using the Same Selection More than Once in your DOM Tree. 
  • e:g: Inside a jQuery Function Likes below
BAD Way
$(".myList").click( function() {
   $(".myList").hide(); 
});
BEST Way
var myList  = $(".myList");
myList.click( function() {
       myList.hide();  // No need to re-select .myList since we cached it
});

Performance of  jQuery Selector when Caching




More Tips for Optimizing jQuery Selector Performance :
1. Qualify your Selector strings when searching by class
       - give Selector's Context as 2nd Parameter
       - when the branches of your DOM tree become very deep 

                       What is a Context ?
                            - jQuery has an optional second argument called context
                            - Its Limit the search within a specific node
                            - Great when you have a very Large DOM tree and need to find
                             e.g: All the <p> tags within a specific part of the DOM tree
                            - You can check to see what is the context of Selector by using context
                               Property.
                              e.g:    $('p').context; //out put is => document
BAD Way
$(".your-class")
BEST Way

// get the node for the context
var context = $('#myContainer')[0];
$(".your-class", context )
                 
2. Don't Qualify your selector when searching by Id.
      - searching by Id uses the browsers native getElementById method (which is very fast)
BAD Way
$("div#your-id")
BEST Way
$("#your-id")

Performance of jQuery ID vs Class  Selectors

Conclusion
  • Always Try to use Id of a Selector when its possible
  • Always Do Caching for jQuery Selectors before it use
  • Always Use Context with class Selectors

I hope this helps to You.Comments and feedback greatly appreciated.

How to Disable a Button Using Jquery and CSS ?

How to Disable a Button ? :




Step 1:

Using Jquery attr Attribute :

$('.actionButton').attr('disabled', 'disabled');

Step 2:

Using Jquery addClass CSS Class :

$('.actionButton').addClass('disabled');

Step 3:

Then by Declaring CSS Style Class :

    <style type="text/css">
        .disabled
        {
            background: none repeat scroll 0 0 burlyWood;
            cursor: default !important;
        }
    </style>
Note : Important thing here is you have to give proper cursor style like above when button is in Disable State

How to Enable a Button Again ? :

Step 1 :

Using Jquery removeAttr Attribute :

$('.actionButton').removeAttr('disabled');
Step 2 :

Using Jquery removeClass CSS Class :

$('.actionButton').removeClass('disabled');

Conclusion
You can Disable or Enable a button which was disable earlier by using above methods easily.

How to Check Spelling in Visual Studio 2010 ?

What is HTML Spell Checker ?
  • It's a Free Product
  • It's an Extension for Visual Studio 2010
What Type of  Text Verification Spell Checker Supports ?

  • HTML and ASP.NET element content and attributes
  • HTML style Comments  <-- HTML -->
  • ASP.NET server side Comments  <%-- ASP.NET --%>
  • JScript, C# and C++ Comments  // C++ style comments
  • CSS and C style Comments   /* C style comments */
  • VB and VBScript style Comments  'This is VB comment

What are the Basic Requirements Needed for Run Spell Checker ?
  • Microsoft Visual Studio 2010 Any Edition Except Express Editions                          
  • Microsoft Word 2003, 2007 or 2010

How to Download Spell Checker?
  • You can Download from Here
  • Like Below
How to Install Spell Checker ?
Step 1. Close Visual Studio 2010
Step 2. Just Double Click what you have downloaded
Step 3.
Step 4.
How to Use Spell Checker ?
  • Run Visual Studio 2010
  • Open Your Web Project
  • Go to the Page Where You want to Do the Spell Checking
  • Then Click, Tools ---> Spell Checker

  • Now It's Like Word Document Spell checking
  • That's It.It is Very Simple and Elegant.
  • Enjoy it.
Do You need to Know More Details and Functions about Spell Checker ?
  • Spell Checker Home Here
  • Web Developments Tools Team Blog Post Here
  • How to Run Spell Checker on All ASP.NET and HTML Files in the Solution Here

Conclusion
  • It's a very simple Tool for Use and Configure
  • If you want, you can configure it for as Multi-Language spell checker
  • You can get more details about advance features of spell checker by using above mentioned Links

I hope this helps to You.Comments and feedback greatly appreciated.