Infolink

 

Search This Blog

Oct 31, 2012

Viewing and Editing the Server-Side Code

Visual Basic and client-side JavaScript programmers will certainly be familiar with the concept of events and event-driven programming. Most ASP programmers will probably have come across the event-driven programming paradigm as well. It is very important that you understand the event-driven programming model, as all ASP.NET applications revolve around this principle.

Building a Simple Web Form

This section is intended to demonstrate how to build a simple Web Form and also to explain some of how ASP.NET Web Forms work from the inside out. Along the way, you’ll be introduced to several new elements of the Visual Studio IDE.

Oct 30, 2012

Server Explorer

The Server Explorer in VS .NET may look very familiar to users of Visual InterDev. Visual InterDev shipped with a feature allowing developers to access and manipulate remote data sources, all in an integrated part of the IDE. The Server Explorer in VS .NET provides this functionality and adds a whole lot of its own. A full list of resources that you can access with the Server Explorer follows.

Class View

The Class View is displayed by selecting the Class View option from the View menu. The Class View shows all the classes that apply to the project, including those in the project’s References and Web References, as well as classes that the project itself owns (each Web Form is in itself a class).

The Class View is a powerful tool and provides a constructive and useful overview of a solution. Members of classes, such as methods and properties, are represented as child nodes in the Class View treeview, and their respective scopes are shown through the use of icons.

HTML View

The name “HTML view” is not entirely accurate. This view, which you access by clicking the HTML button at the bottom of the Web Form Designer as shown in Figure 4-5, shows the UI code for a Web Form. This code is primarily HTML, although there are several important differences between the UI code and vanilla HTML, which will be clearer later in this chapter and in the next chapter. Figure 4-6 shows the HTML view.

Exploring the IDE

The best way to familiarize yourself with some of the features of VS .NET is to have a hands-on tour. Visual Studio has a very substantial feature set, however, there are many features of Visual Studio that are commonly used and offer a great productivity boost if used effectively. This section aims to introduce those common items.   

Oct 29, 2012

Progressive Clock in C# windows Application

Introduction

The dialog box on this exercise displays three progress bars: one holds the value of the current hour, another holds the value of the minutes in the current hour, the last displays the seconds of the current minute. We also use a label on the right side of each progress bar to display its corresponding value.

The Free Office WPF Ribbon

So you want to use a Ribbon toolbar similar to Microsoft Word in your applications, but you don’t want to purchase one from a third party. Well if you haven’t heard already, you can get a free one directly from Microsoft. Yes, you heard me correctly, FREE, and FROM MICROSOFT. So where do you get this free Ribbon control?

Asp.net sending email with zip file as attachment (PART-12)

In this article I would like to explain how to send the compressed or zip document as an email attachments. You can find the c# source code sample how to send the email with zip format. If you are sending the html attachment or some JavaScript there might be change attachment get corrupted. If you are using the outlook web access (OWA) email client to read the email, there might be change of your html get corrupted because of OWA html filtering option.

Best solution is we can compress the file and attach to email as attachment.  We can find the different approachs to send the email, You can find the below best solution for attachment format.

Oct 28, 2012

Asp.Net Tutorial (PART-11)

Memory Management and Garbage Collection

In any object-oriented programming environment, there arises the need to instantiate and destroy objects. Instantiated objects occupy memory. When objects are no longer in use, the memory they occupy should be reclaimed for use by other objects. Recognizing when objects are no longer being used is called lifetime management, which is not a trivial problem. The solution the CLR uses has implications for the design and use of the components you write, so it is worth understanding.

Asp.Net Tutorial (PART-10)

Common Language Specification (CLS)

The CLI defines a runtime that is capable of supporting most, if not all, of the features found in modern programming languages. It is not intended that all languages that target the CLR will support all CLR features. This could cause problems when components written in different languages attempt to interoperate. The CLI therefore defines a subset of features that are considered compatible across
language boundaries. This subset is called the Common Language Specification (CLS).

Asp.Net Tutorial (PART-9)

Modules and Assemblies

A module is an .exe or .dll file. An assembly is a set of one or more modules that together make up an application. If the application is fully contained in an .exe file, fine—that's a one-module assembly. If the .exe is always deployed with two .dll files and one thinks of all three files as comprising an inseparable unit, then the three modules together form an assembly, but none of them does so by itself. If the product is a class library that exists in a .dll file, then that single .dll file is an assembly. To put it in Microsoft's terms, the assembly is the unit of deployment in .NET.

Asp.Net Tutorial (PART-8)

Common Type System (CTS)

The CLI specification defines a rich type system that far surpasses COM's capabilities. It's called the Common Type System (CTS). The CTS defines at the runtime level how types are declared and used. Previously, language compilers controlled the creation and usage of types, including their layout in memory. This led to problems when a component written in one language tried to pass data to a
component written in a different language. Anyone who has written Visual Basic 6 code to call Windows API functions, for instance, or who has tried to pass a JavaScript array to a component written either in Visual Basic 6 or C++, is aware of this problem. It was up to the developer to translate the data to be understandable to the receiving component. The CTS obliterates this problem by providing the following features:

Asp.Net Tutorial (PART-7)

.NET Framework

In the ASP/VB6 model, Microsoft had developers building a component and then calling it via an ASP. Microsoft realized that it would be a good idea to make the component directly callable over HTTP, so that an application anywhere in the world could use that component. Microsoft threw their support behind SOAP, Simple Object Access Protocol, which allows developers to call a component over HTTP
using an XML string, with the data returning via HTTP in an XML string. Components sport URLs, making them as easy to access as any other Web item. SOAP has the advantage of having been a cross-industry standard, and not just a Microsoft creation.

Asp.Net Tutorial (PART-6)

The Need for a New ASP Model

It was evident that Microsoft would require a fundamental change to bring ASP up to the standard of industrial-strength programming. Active Server Pages was a technology based on the foundations of COM. ActiveX and COM technology provided much of its strength, but also many of its limitations. Microsoft would need to have a long hard look at COM to see how it could improve, and these changes would be bound to affect ASP. At the same time,Microsoft realized that the developers' playing field was changing, with new standards arriving all the time, particularly in information-sharing and distributed applications using XML, such as Simple Object Access Protocol (SOAP) and XML-RPC.

Asp.Net tutorial (PART-5)

Major Changes with ASP 2

Moving to Active Server Pages 2 brought the developer into a more stable and feature-rich environment. All aspects of the technology were tuned and tweaked,and programmers really felt that things had settled into a stable technology.This newfound confidence was in part due to the evidence of successful transactional sites actually showing that the platform could deliver, but also the fact that the technology had been boosted under the hood with tighter integration with Microsoft Transaction Server (MTS).

In fact, IIS 4 was rebuilt to be a MTS application, and so ASP and MTS components were actually running in the same processes. Another improvement was the work with Microsoft Message Queue.This
allowed ASP and components to communicate across networks, ideal for largescale applications with complex backend requirements, for example, e-commerce systems integrating with existing legacy enterprise resource planning (ERP) infrastructures.

Asp.Net Tutorial (PART-4)

Why ASP Was Not Originally Embraced

Active Server Pages was not an overnight success, though understandably it did capture the imagination of a large sector of the development community, particularly those already well versed in Visual Basic programming or Visual Basic for applications scripting.

Others who did not have an investment in Visual Basic knowledge found the limitations of Visual Basic, and by extension Visual Basic Scripting, reasons to avoid the technology. Faults included poor memory management, the lack of strong string management abilities, such as Regular Expressions, found in other established languages.When compared to CGI with Perl,ASP was found lacking.

At that time, Internet Information Server was in its infancy, and take-up was low, despite Microsoft's public relations juggernaut going into full flow after the company's much-reported dramatic turnaround. In comparison to current versions of the software it seems very poor, but it was still competitive on performance.

Asp.Net Tutorial (PART-3)

History of ASP

You can trace the history of ASP right back to 1995 and the momentous occasion when Microsoft realized they were falling behind in a fundamental shift in the industry by not embracing the Internet. Up until that point Microsoft had been developing their proprietary technologies, tools, and network protocols for the Microsoft Network; all of a sudden they needed an Internet strategy and fast.

Microsoft has gone from a position of playing catch-up to one close to dominance, with the Internet Explorer Web browser having a strangle-hold on the Web browsing market, and Internet Information Server (IIS) installed at the majority of Fortune 1000 companies.

Asp.Net Tutorial (PART-2)

Separation of Code from Content

As I mentioned previously, a major drawback of ASP in certain instances is that there is no way to separate code from page content. In ASP.NET, due to the introduction of server controls and the event-driven model, the trend leans toward placing all the code in event handlers in one place in the file (normally at the top). If this isn't sufficient, it's also possible to totally separate code from content by placing all the code in a separate file (VS .NET does this by default).

Session State Management

ASP provided a special collection object where the programmer could store variables pertaining to a particular visitor's session. This was a commonly used feature, but it had three major shortcomings. First, it wasn't Web farm-friendly. Session state variables were stored in the IIS process space, and as such, they were tied to a specific machine. Thus, if a visitor to a site had a particular piece of information stored in a session variable on a particular request, and he or she was then sent to another server on the next request, the ASP code would not be able to retrieve the previously stored
value. Second, a disadvantage of storing session state in the IIS process space is that should the IIS service have to be restarted, the session information is lost. The third problem was slightly more subtle, but important nonetheless: ASP kept track of visitor IDs by using cookies, which aren't supported by all browsers, or are not guaranteed to be enabled in all user browsers.

Differences Between ASP and ASP.NET

ASP.NET isn't simply the next version of ASP it's a completely redesigned technology that takes the best aspects of ASP and merges them with the power of pure object-oriented programming (OOP), a powerful development framework, to give it a vast range of functionality and the advantages of a fully compiled execution environment. Because the changes between ASP and ASP.NET are so drastic, current ASP developers must "unlearn" many concepts that they became accustomed to in ASP in order to truly get the most out of ASP.NET.

Compiled Environment

One of the most dramatic changes in ASP.NET is that it's now a fully compiled environment. Microsoft has implemented this very intelligently and it would be very easy to dismiss ASP.NET as interpreted because, to the programmer and the end user, it appears as if ASP.NET works in exactly the same way as ASP: You modify your ASP.NET page, you refresh the page in the browser, and the changes are reflected. Nowhere are you required to run a compiler. Compilation actually occurs the first time a page is requested after it has been modified. This compiled copy is then kept until the page is modified and requested again. As I've already mentioned, this process is totally transparent to the user.

What is Asp.Net?

Introduction

The Internet has grown at an enormous rate over the past few years, and it has almost certainly affected the lives of most people who use computers. In only a few years, the Internet has evolved from a platform for publishing “online brochures” to an entire architecture for developing dynamic, distributed applications. Developing these applications was previously extremely difficult and tedious.

The potential was huge, but the tools consisted of nothing more than text editors in which applications would be coded from scratch. This method of writing Web applications required extensive knowledge of the “plumbing” of the Internet, and there were a very limited number of languages to use. These factors made Web application programming available only to dedicated programmers who had the time to invest in learning rudimentary interfaces and unfamiliar programming languages.

Oct 27, 2012

Combobox in c# windows application

This example explains How To Create Cascading ComboBox Dependent On One Another In WinForms Windows Forms Applications Using C# And VB.Net.

I have used Country, State, City tables from database to populate respective cascading combobox based on selection of country and state.

Drag 3 combobox controls from toolbar on the windows form, write following code to populate comboboxes.

Table schemas are shown below.



Remote Scripting with IFRAME

Before you can exchange data between frames, you must first get access to the iframe's document object. There are 3 ways of doing this:

Three Methods

Method 1 - The iframe page can use it's own javascripts to transfer and place the data into the parent.

Method 2 - The iframe page can pass its document object as an argument to a function in the parent, thereby allowing the parent to retrieve data from the iframe.

Method 3 - Place an onload event handler in the iframe tag in the parent document (this page). This method does not work with Netscape 6.

We'll look at each of the methods below. For the sake of clarity, the iframes used in the following examples will be visible. In practice, they would be hidden using the technique discussed in the previous page.

Method 1

The parent page contains a form with a list of States. When you select a State and the results are returned in iframe name="repIframe", the iframe moves the data up to div id="results1" in this page using this script:

<script>
// - this is the script in the iframe results page
var reps = document.getElementById('state_reps').innerHTML;
parent.document.getElementById('results1').innerHTML = reps;
</script>

Method 2

Once again, we're going to use the form below to get a list of State Representatives. This time, however, when the results load in the iframe, this script will call the parent function showReps(doc) :

<script>
 // - this is the script in the iframe results page
 parent.showReps(document);
</script>

The showReps(doc) function in the parent (this page) uses the document reference to retrieve the table in the iframe and put it into div id="results2". The script looks like this:

<script>
 // - this is the script in this page
function showReps(doc){
 var x = doc.getElementById('state_reps').innerHTML;
 document.getElementById('results2').innerHTML = x;
}
</script>

Method 3

Method 3 uses the onload event handler to gain access to the document object of iframe name="repIframe3" source page using window.frames['repIframe3'].document.

This method will NOT work with Netscape 6.

Here's how this example works: place the event handler onload="getIframeDoc()" in the iframe tag. Next, choose a State from the select object in form name="list3". When the page loads in the iframe it will exectue the getIframeDoc function.

<iframe name="repIframe3" src="blank.html" onload="getIframeDoc()"></iframe>

<script>
 function getIframeDoc(){
  var iframeDoc = window.frames['repIframe3'].document;
  var sr = iframeDoc.getElementById('state_reps');
  if (sr){
   var reps3 = sr.innerHTML;
   document.getElementById('results3').innerHTML = reps3;
   }
 }
</script>

PARSENAME in Sql

DECLARE @t TABLE (A varchar(25))

INSERT @t values ('77.88.99.100') 

SELECT
  PARSENAME(A,1) AS 'First selected'
, PARSENAME(A,2) AS '2nd selected'
, PARSENAME(A,3) AS '3rd selected'
, PARSENAME(A,4) AS '4th selected'
 from @t

The question is: (select 1)

a. Are the values returned  First selected 77,  2nd selected 88,3rd selected 99,4th selected 100'

b. Are the values returned first selected 100,  2nd selected 99,3rd selected 88, 4th selected 77

c. No values are returned.

Oct 23, 2012

Custom validator with Javascript

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="UsingCustomValidator" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Using a CustomValidator</title>
</head>
<body>
    <form id="form1" runat="server">
   
    Enter a date:<br />
    <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
    <asp:CustomValidator ID="custDate" runat="server"
       ControlToValidate="txtDate"
       ValidateEmptyText="false" 
       Text="Enter a valid future date"
       OnServerValidate="custDate_ServerValidate" />  
   

   <script type="text/javascript">
     function validateOrFields(source, args){
       var sUser = document.form1.<%= txtUser.ClientID %>.value;
       var sEmail = document.form1.<%= txtEmail.ClientID %>.value;
      
       if (sUser == "" && sEmail == "")
       {
          args.IsValid = false;
       }
       else
       {
          args.IsValid = true;
       } 
       return; 
     }
   </script>
  
   Enter user name:<br />
   <asp:TextBox ID="txtUser" runat="server"></asp:TextBox>
   <br />
   Enter email:<br />
   <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>

   <asp:CustomValidator ID="OrFieldValidator"
                        runat="server"
                        Text="Enter either a user name or a email"
                        ClientValidationFunction="validateOrFields"
                        OnServerValidate="OrFieldValidator_ServerValidate" />  
  

  
   <asp:Button ID="btnSubmit" Text="Click this to test validation" runat="server" />
  
   </form>
</body>
</html>
<script type="text/javascript">
  ValidatorHookupControlID("<%= txtUser.ClientID %>",document.getElementById("<%= OrFieldValidator.ClientID %>"));
  ValidatorHookupControlID("<%= txtEmail.ClientID %>",document.getElementById("<%= OrFieldValidator.ClientID %>"));
</script>
 File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class UsingCustomValidator : System.Web.UI.Page
{
   protected void custDate_ServerValidate(object source, ServerValidateEventArgs args)
   {
      string sEnteredDate = args.Value;
      DateTime dt;
      bool convertSuccessful = DateTime.TryParse(sEnteredDate, out dt);
      if (convertSuccessful && dt >= DateTime.Today)
         args.IsValid = true;
      else
         args.IsValid = false;
   }

   protected void OrFieldValidator_ServerValidate(object source, ServerValidateEventArgs args)
   {
      if (txtUser.Text.Length <= 0 && txtEmail.Text.Length <= 0)
         args.IsValid = false;
      else
         args.IsValid = true;
   }
}

Postback With Javascript

Entire form tag of the asp.net page

<form id="form1" runat="server">
    <asp:LinkButton ID="LinkButton1" runat="server" /> <%-- included to force __doPostBack javascript function to be rendered --%>

    <input type="button" id="Button45" name="Button45" onclick="javascript:__doPostBack('ButtonA','')" value="clicking this will run ButtonA.Click Event Handler" /><br /><br />
    <input type="button" id="Button46" name="Button46" onclick="javascript:__doPostBack('ButtonB','')" value="clicking this will run ButtonB.Click Event Handler" /><br /><br />

    <asp:Button runat="server" ID="ButtonA" ClientIDMode="Static" Text="ButtonA" /><br /><br />
    <asp:Button runat="server" ID="ButtonB" ClientIDMode="Static" Text="ButtonB" />
</form>

Entire Contents of the Page's Code-Behind Class

Private Sub ButtonA_Click(sender As Object, e As System.EventArgs) Handles ButtonA.Click
    Response.Write("You ran the ButtonA click event")
End Sub

Private Sub ButtonB_Click(sender As Object, e As System.EventArgs) Handles ButtonB.Click
    Response.Write("You ran the ButtonB click event")
End Sub
The LinkButton is included to ensure that the __doPostBack javascript function is rendered to the client. Simply having Button controls will not cause this __doPostBack function to be rendered. This function will be rendered by virtue of having a variety of controls on most ASP.NET pages, so an empty link button is typically not needed

What's going on?

Two input controls are rendered to the client:

<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />

    __EVENTTARGET receives argument 1 of __doPostBack
    __EVENTARGUMENT receives argument 2 of __doPostBack

The __doPostBack function is rendered out like this:


function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
As you can see, it assigns the values to the hidden inputs.

When the form submits / postback occurs:

If you provided the UniqueID of the Server-Control Button whose button-click-handler you want to run (javascript:__doPostBack('ButtonB',''), then the button click handler for that button will be run.

What if I don't want to run a click handler, but want to do something else instead?

You can pass whatever you want as arguments to __doPostBack

You can then analyze the hidden input values and run specific code accordingly:

If Request.Form("__EVENTTARGET") = "DoSomethingElse" Then
    Response.Write("Do Something else")
End If
another Solution
<script type="text/javascript">
     <!--
     //must be global to be called by ExternalInterface
         function JSFunction() {
             __doPostBack('<%= myUpdatePanel.ClientID  %>', '');
         }
     -->
</script>

Oct 21, 2012

How to Detect Errors of Our ASP.NET MVC Views on Compile Time

I have simple ASP.NET MVC 4 internet application which we get out of the box (Things that I will show can be applied with ASP.NET MVC 3 as well). Then I will put a bug inside the index view of my home controller :

@{
    var poo = "bar"
    }

<h3>We suggest the following:</h3>
As you can see it is not a valid code. So it should fail on both compile time and runtime, right? Let’s build the project first :

Error1

Display custom messages or images when there is no records in GridView Data Source

Display custom messages or images when there is no records in GridView Data Source

This is a very frequent requirements to display Custom Messages or Images when there is no records in Grid View. I found people used custom code to achieve this. But ASP.NET Gridview having some inbuilt features to do the same.   You can use EmptyDataTemplate using GridView to display any custom message or Images or even web controls to add new records or whatever you want as per your requirements.


How to Convert DataTable to Collection of Custom Class object

Imagine you have a DataTable with Records and you want to Convert that to a List of your Custom class objects ? how do you do that ?

The normal -straight forward way is to Loop through  each DataRow, Create a new instance of Custom class object, read the column values of the current row(iterator) in the loop and Set the Proerties of the object..

The below code shows looping the DataRows and Creating an object of our Custom Customer Class and Setting the Properties and Adding to the Collection of Customer objects.

We can avoid this handwritten ForEach loop by using some LINQ syntax.  Generally LINQ queries works on data sources which implement the IEnumerable<T>/ IQueryable<T> Interface. But DataTable does not
implement any of these. So we can not directly apply LINQ queries on a DataTable. 

But DataTable class has an extension method called AsEnumerable which returns an IEnumerable collection of DataRow. So we can apply the AsEnumerable function on a DataTable and then play with some LINQ on the resulting collection.

So we can replace our previous version of code with the below one which make use of LINQ

 



When to use ViewModel in mvc3

In asp.net mvc, a controller can pass single object to the corresponding view. This object may be a simple object or a complex object. ViewModel is a complex object that may contain multiple entities or objects from different data models or data source. Basically ViewModel is a class that specify data model used in the strongly-typed view. It is used to pass data from controller to strongly-typed view.

Designing the model

public class UserLoginModel
{
[Required(ErrorMessage = "Please enter your username")]
[Display(Name = "User Name")]
[MaxLength(50)]
public string UserName { get; set; }
[Required(ErrorMessage = "Please enter your password")]
[Display(Name = "Password")]
[MaxLength(50)]
public string Password { get; set; }
}


Working with Enums and Templates In ASP.NET MVC

Imagine you have the following types defined.

public class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }
    public MovieGenre Genre { get; set; }
}

public enum MovieGenre
{
    Action,
    Drama,
    Adventure,
    Fantasy,
    Boring
}

If you want to display MovieGenre, the DisplayFor helpers generally give you what you expect (i.e. @Html.DisplayFor(m=> m.Genre) displays "Adventure"), but EditorFor will only give you a text input because the framework treats an enum the same as a string.

Oct 20, 2012

Configuring Multiple End points for WCF Service

Sample Service with multiple End Points

Step 1

Create a WCF Service Application. Open Visual studio and create new project selecting WCF Service Application project template. In VS2008, you will get WCF Service Application project template inside WEB tab whereas in VS2010, you will get WCF Service Application project template inside WCF tab.

Step 2

Delete the default code getting created for you by WCF. Delete all the code from IService1 and Service1. If you are using VS2008, comment out whole System.ServiceModel from Web.Config file. And if you are using VS2010 then comment out Multiple Host Binding.

Step 3

Oct 19, 2012

Gridview Paging using C#

A GridView is most often used to display the data retrieved from the database in Tabular form with features of Gridview like data paging, sorting and auto formats.

You can use C# code to bind the SQL data with GridView control and follow the following simple steps to make your ASP.Net GridView control with paging enabled.

First of all drag the GridView control from Data controls menu. It will add the GridView control HTML source code as given above. Now click on GridView control to load the control properties at right side panel.

Tooltip User Control

I have created Tooltip control that replaces standard browsers' tooltips with custom ones. You can write your own html template to customize it's look and feel.

The control derives on the client from Sys.UI.Control, and is implemented as WebControl on the server.

It is really easy to use it and it gives really nice experience.

Here is a source for a very simple page showing how to use it:


ASP.NET Trace

Trace.Write helps diagnose problems in ASP.NET. It determines what is actually running in an ASP.NET application. We review the basics of tracing in ASP.NET. We use the C# language to easily benchmark sites.

First we must add the trace markup to our Web.config file. The sample values in the markup I show can and should be changed by you. I encourage you to flip the attribute values and see what they do as much as possible. Here's how to add the markup.

Open Web.config file. Your ASP.NET project should have a Web.config file. If it doesn't, add one through the Website > Add New Item.... menu. This is an XML file used by ASP.NET to store website configuration settings.

Oct 18, 2012

How to use C# HashTable Class

Hashtable in C# represents a collection of key/value pairs which maps keys to value. Any non-null object can be used as a key but a value can. We can retrieve items from hashTable to provide the key . Both keys and values are Objects.

The commonly used functions in Hashtable are :

  Add                   : To add a pair of value in HashTable
  ContainsKey    : Check if a specified key exist or not
  ContainsValue  : Check the specified Value exist in HashTable


Remove : Remove the specified Key and corresponding Value

Add : To add a pair of value in HashTable

Syntax : HashTable.Add(Key,Value)
  Key : The Key value
  Value : The value of corresponding key
  Hashtable ht;

ht.Add("1", "Sunday");

Generics classes Overview in C#.Net

Generics main benefit is eliminating boxing and unboxing that is true, there are also other benefits like type safety, by using generics you eliminate type ambiguitiy.

  1. Generics provide type safety without the overhead of multiple implementations. Ex. We can create a linked list of string. LinkedListlinkList=new LinkedList(); There is no need to inherit from a base type and override members.The linked list is ready for immediate use.
  2. There is no need to write code to test for the correct data type because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced.
  3. Generic collection types generally perform better for storing and manipulating value types because there is no need to box the value types
  4. Generic delegates enable type-safe callbacks without the need to create multiple delegate classes.  

Understanding Garbage Collection in the .NET Framework

In this article we will explore the Garbage Collection feature in the .Net framework and the activities required in applications to manage resources complementing the Garbage Collector.

Garbage Collection in Various Environments

One of the new features inherently available in the .Net framework is automatic garbage collection. The term garbage collection can be defined as management of the allocation and release of memory in an application. In C++, developers are responsible for allocating memory for objects created in the application and releasing the memory when the object is no longer needed. COM introduced a new model for memory management - Reference counting. Programmers were only responsible for incrementing the reference count when the object is referenced and decrementing the counter when the object goes out of scope. When the object's reference count reaches zero, the object is deleted and the memory gets freed. Both these schemes are dependent on the developer and result from time to time in memory leaks and application exceptions - conditions that occur at run-time and are not detectable at compilation.

A generic way to find ASP.NET ClientIDs with jQuery

I’ve been using a small hack to deal with the ASP.NET naming container morass that is so prevalent in client side development with ASP.NET. Particularly in Master Pages all server control IDs are basically munged  because the master page place holders are naming containers.

To recap – the problem is that if you are dealing with something as simple as this:

<div class="contentcontainer"  runat="server" id="PageContent">
    <h2>Stock Quote Lookup</h2>
   
    <div class="labelheader" style="margin-top: 20px;">Enter a stock symbol:</div>
    <asp:TextBox runat="server" ID="txtSymbol"  />
    <input type="button" id="btnGetQuote" value="Go" />
   
    <div id="divStockWrapper">
        <div id="divStockDetail">       
        </div>
        <img id="imgStockChart"  />
    </div>
</div>

Oct 17, 2012

C# KeyNotFoundException

A KeyNotFoundException was thrown. This is likely caused by an invalid usage of the Dictionary collection. As always we want a quick way to fix the problem.

Example

First, here we see some code that looks correct, but actually has a severe flaw. The problem is that you cannot look up a key that doesn't exist in the Dictionary and try to assign your variable to its value.

The KeyNotFoundException here is thrown on the final line of try-block. The string "test" doesn't exist in the collection.

Program that throws KeyNotFoundException [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
    try
    {
        //
        // Create new Dictionary with string key of "one"
        //
        Dictionary<string, string> test = new Dictionary<string, string>();
        test.Add("one", "value");

        //
        // Try to access key of "two"
        //
        string value = test["two"];
    }
    catch (Exception ex)
    {
        //
        // An exception will be thrown.
        //
        Console.WriteLine(ex);
    }
    }
}

Output

System.Collections.Generic.KeyNotFoundException:
    The given key was not present in the dictionary.
at System.ThrowHelper.ThrowKeyNotFoundException()

Fix

Here we look at how you can fix this exception by using the TryGetValue method on the Dictionary constructed type. Note that could use ContainsKey instead of TryGetValue, but the below code preserves the intention of the previous code.

Program that does not throw [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
    Dictionary<string, string> test = new Dictionary<string, string>();
    test.Add("one", "value");
    //
    // Use TryGetValue to avoid KeyNotFoundException.
    //
    string value;
    if (test.TryGetValue("two", out value))
    {
        Console.WriteLine("Found");
    }
    else
    {
        Console.WriteLine("Not found");
    }
    }
}
Output

Not found

You always have to use the if statement when testing values in the Dictionary, because there is always a possibility that the key won't exist.

We saw how to raise and catch the KeyNotFoundException during runtime. We then saw how to avoid causing the exception. We discussed alternatives, such as TryGetValue and ContainsKey, and looked at a program that does not have this problem.

What is Entity Framework?

asfasfThe Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals.

Oct 16, 2012

Scrollable Gridview with fixed headers in asp.net

Copying Gridview into divHeaderRow show only header,hide all rows and applying style to it so that divHeaderRow placed onto the top of the Gridview header row.

If isFooter is true then Copying Gridview Footer row into divFooterRow and applying style to divFooterRow.

Copy and paste given bellow javascript code inside the <head> tag.

ASHX handler in Asp.Net

An ASHX handler allows you a discrete http handler without the overhead of processing a page request (an ASPX file).

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        var fileName = "must.sql";
        var r = context.Response;
        r.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        r.ContentType = "text/plain";
        r.WriteFile(context.Server.MapPath(fileName));

    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}
 Now, You have to create button in your .aspx page write the code as following

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("Handler.ashx");
    }
 

Stop default Auto-Complete of ASP.net TextBox on all browser

If you use textBox properties AutoCompleteType="Disabled" it disables the autocompletes of textBox on only Internet explorer. There's another way to stop auto-complete on all browsers. Use autocomplete="off" on from tag instead of AutoCompleteType = "Disabled". Again you can use the TextBox1.Attributes.Add("autocomplete", "off"); to stop auto-complete on only specific TextBox control.

So, my findings are use the following code to stop autocomplete on specific control

Activity logging and Error logging in ASP.NET

There are lots of error logging providers available such as log4Net, AnLogger, etc. they are easy to use as well, but just to keep it simple, I have written my own. I call it "Activity and Error Logger", it stores the data in XML format, request by request and session by session, you can actually create the user behaviour maps if you properly call the activity log at while performing any major operations. It also takes care of the concurrency, two threads will not overwrite each other. It logs the errors on page in try catch block and also at global level, in Application_Error event in global.asax.

Converting an ASP.NET site into a SharePoint site

Introduction

There are a lot of ASP.NET web developers who are moving to SharePoint site creation. This article will explain in detail how an ASP.NET webpage developed in Visual Studio can be converted into a SharePoint site. If there is a requirement for a website created in Visual Studio, just the old fashioned way with the code-behind logic and other layers like Data Access and Business Logic, to be converted into a SharePoint site, and still make it work the same way with the same code-behind, you are in the right place. This article deals with right that.

Scenario

There is an ASP.NET website solution that contains three layers viz. Code-Behind Layer, Business-Logic Layer, and the Data-Access Layer. The website has functionality implemented in all these layers. The Business-Logic and the Data-Access layers are in a different Class Library project. We have to convert this website into a SharePoint site. Also, we want to use the same look and feel of the SharePoint site. So, we have to use the SharePoint master page instead of the one that we are having (we can also use our own master page; just that you have to add some default Place Holders that are required for the SharePoint functionalities). In this article, we are dealing with a website with the same look and feel as a SharePoint site.
Steps Overview

C# Use Zip Archives without External Libraries

Introduction

I found a lot of articles on how to access Zip archives in C# but all with significant disadvantages. The main problem is that Microsoft has Zip archives implemented in the operating system but there is no official API that we can use. In C# for example, we have the System.IO.Compression.GZip but there is no adequate System.IO.Compression.Zip class.

Oct 15, 2012

RAISERROR statement in SQL server

RAISERROR statement is used to return error messages to the business applications that executes SQL statements. The usual errors returned by the SQL server may not make much sense to the business applications users hence we overwrite it by using RAISERROR to display meaningful messages. The statement uses same format as a system error or warning messages generated by SQL server.

You can return a user-defined error message by using RAISERROR.  The general syntax is as below

Oct 14, 2012

Spell as you Type plug-in

Full clientside spell checker for IE 6.0+ users that underlines misspellt words as you type into a textbox or textarea. Right click to see a list of suggested corrections.

Browsers such as Firefox and Chrome have spell as you type built in, this plugin will not have any effect in other browsers.

Use the dictionary supplied or create you own (plain text file, one word per line) using the dictionary builder application. The dictionaries supplied are over 500k each, so enable caching (and compression if available) on the server.

User Control Example

In this example I show that how easily we can create User Control and then use it in asp.net. Here first I create a User Control name CalendarUserControl.ascx, then place it Default.aspx web form. Here is the source code of both files.

Creating a UserControl

we will be building a UserControl for displaying information about a community user.
First of all, let's add a UserControl to our project. In your Visual Studio or Visual Web Developer, you should be able to right click on your project and select Add new item.. A dialog will pop up, and you should select the Web User Control from the list of possible things to add. Let's call our UserControl UserInfoBoxControl, with the filename of UserInfoBoxControl.ascx. Make sure that you have checked the checkbox which places code in a separate file, the so-called CodeBehind file.

You should now have a UserInfoBoxControl.ascx and a UserInfoBoxControl.ascx.cs in your project. The first is where we put our markup, and the second is our CodeBehind file. Now, if UserInfoBoxControl.ascx is not already open and selected, do so now. You will see only one line of code, the UserControl declaration. As mentioned, this control will be displaying information about a user, so let's get started adding some markup to do so:

ASP.net Ajax

ASP.net Ajax is Microsoft's free framework for creating Ajax (Asynchronous Javascript and XML) web applications. At its simplest, it lets ASP developers do this - or add Ajax controls to their existing applications - without leaving their familiar drag-and-drop environment, and without having to understand Javascript or asynchronous communication with the host. According to the O'Reilly Network, it protects developers from "the underlying gibberish that makes it [Ajax] all work".

Oct 10, 2012

View State Rendering

The problem in earlier versions is that the viewstate is rendered at the bottom of the page.
If the page is posted back before the entire page is loaded, the viewstate that is being submitted back to the server is incomplete and thus invalid.

This was fixed with .NET 3.5 SP1.

But You can Fix it by below Render function in earlier version of .NET

Oct 7, 2012

How to avoid deadlocking on your SQL Server


Deadlock:

Deadlocking occurs when two user processes have locks on separate objects and each process is trying to acquire a lock on the object that the other process has. When this happens, SQL Server ends the deadlock by automatically choosing one and aborting the process, allowing the other process to continue. The aborted transaction is rolled back and an error message is sent to the user of the aborted process. Generally, the transaction that requires the least amount of overhead to rollback is the transaction that is aborted.


Oct 3, 2012

The major difference between convert.ToString() and ToString() is that,

convert.ToString() handles null but ToString() does not handles null.

Please see below two set of code:

This code will run successfully, no exception will be raised for that:

    string name = null;

    string abc = Convert.ToString(name);

Below code will give an exception, unhandled Exception:NullReferenceException

    string name = null;

    string abc = name.ToString();
Related Posts Plugin for WordPress, Blogger...