Friday, September 12, 2008

Redirect user back to his previous page

Calling this funtion will redirect user to his last visited page after logging in.


protected void RequestLogin()
{
this.Response.Redirect(FormsAuthentication.LoginUrl +
"?ReturnUrl=" + this.Request.Url.PathAndQuery);
}

Get Base URL Snippet

public string BaseUrl
{
get
{
string url = this.Request.ApplicationPath;
if (url.EndsWith("/"))
return url;
else
return url + "/";
}
}

My Favorite Pic

GoogleDesktopPhotosPluginWallpaper

Saturday, August 23, 2008

What Great .NET Developers Ought To Know

Everyone who writes code
  • Describe the difference between a Thread and a Process?
  • What is a Windows Service and how does its lifecycle differ from a "standard" EXE?
  • What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?
  • What is the difference between an EXE and a DLL?
  • What is strong-typing versus weak-typing? Which is preferred? Why?
  • Corillian's product is a "Component Container." Name at least 3 component containers that ship now with the Windows Server Family.
  • What is a PID? How is it useful when troubleshooting a system?
  • How many processes can listen on a single TCP/IP port?
  • What is the GAC? What problem does it solve?

Mid-Level .NET Developer

  • Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.
  • Describe what an Interface is and how it’s different from a Class.
  • What is Reflection?
  • What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?
  • Are the type system represented by XmlSchema and the CLS isomorphic?
  • Conceptually, what is the difference between early-binding and late-binding?
  • Is using Assembly.Load a static reference or dynamic reference?
  • When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate?
  • What is an Asssembly Qualified Name? Is it a filename? How is it different?
  • Is this valid? Assembly.Load("foo.dll");
  • How is a strongly-named assembly different from one that isn’t strongly-named?
  • Can DateTimes be null?
  • What is the JIT? What is NGEN? What are limitations and benefits of each?
  • How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization?
  • What is the difference between Finalize() and Dispose()?
  • How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?
  • What does this useful command line do? tasklist /m "mscor*"
  • What is the difference between in-proc and out-of-proc?
  • What technology enables out-of-proc communication in .NET?
  • When you’re running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003?

Senior Developers/Architects

  • What’s wrong with a line like this? DateTime.Parse(myString);
  • What are PDBs? Where must they be located for debugging to work?
  • What is cyclomatic complexity and why is it important?
  • Write a standard lock() plus “double check” to create a critical section around a variable access.
  • What is FullTrust? Do GAC’ed assemblies have FullTrust?
  • What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?
  • What does this do? gacutil /l | find /i "Corillian"
  • What does this do? sn -t foo.dll
  • What ports must be open for DCOM over a firewall? What is the purpose of Port 135?
  • Contrast OOP and SOA. What are tenets of each?
  • How does the XmlSerializer work? What ACL permissions does a process using it require?
  • Why is catch(Exception) almost always a bad idea?
  • What is the difference between Debug.Write and Trace.Write? When should each be used?
  • What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?
  • Does JITting occur per-assembly or per-method? How does this affect the working set?
  • Contrast the use of an abstract base class against an interface?
  • What is the difference between a.Equals(b) and a == b?
  • In the context of a comparison, what is object identity versus object equivalence?
  • How would one do a deep copy in .NET?
  • Explain current thinking around IClonable.
  • What is boxing?
  • Is string a value type or a reference type?
  • What is the significance of the "PropertySpecified" pattern used by the XmlSerializer? What problem does it attempt to solve?
  • Why are out parameters a bad idea in .NET? Are they?
  • Can attributes be placed on specific parameters to a method? Why is this useful?

C# Component Developers

  • Juxtapose the use of override with new. What is shadowing?
  • Explain the use of virtual, sealed, override, and abstract.
  • Explain the importance and use of each component of this string: Foo.Bar, Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d
  • Explain the differences between public, protected, private and internal.
  • What benefit do you get from using a Primary Interop Assembly (PIA)?
  • By what mechanism does NUnit know what methods to test?
  • What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;}
  • What is the difference between typeof(foo) and myFoo.GetType()?
  • Explain what’s happening in the first constructor: public class c{ public c(string a) : this() {;}; public c() {;} } How is this construct useful?
  • What is this? Can this be used within a static method?

ASP.NET (UI) Developers

  • Describe how a browser-based Form POST becomes a Server-Side event like Button1_OnClick.
  • What is a PostBack?
  • What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState?
  • What is the element and what two ASP.NET technologies is it used for?
  • What three Session State providers are available in ASP.NET 1.1? What are the pros and cons of each?
  • What is Web Gardening? How would using it affect a design?
  • Given one ASP.NET application, how many application objects does it have on a single proc box? A dual? A dual with Web Gardening enabled? How would this affect a design?
  • Are threads reused in ASP.NET between reqeusts? Does every HttpRequest get its own thread? Should you use Thread Local storage with ASP.NET?
  • Is the [ThreadStatic] attribute useful in ASP.NET? Are there side effects? Good or bad?
  • Give an example of how using an HttpHandler could simplify an existing design that serves Check Images from an .aspx page.
  • What kinds of events can an HttpModule subscribe to? What influence can they have on an implementation? What can be done without recompiling the ASP.NET Application?
  • Describe ways to present an arbitrary endpoint (URL) and route requests to that endpoint to ASP.NET.
  • Explain how cookies work. Give an example of Cookie abuse.
  • Explain the importance of HttpRequest.ValidateInput()?
  • What kind of data is passed via HTTP Headers?
  • Juxtapose the HTTP verbs GET and POST. What is HEAD?
  • Name and describe at least a half dozen HTTP Status Codes and what they express to the requesting client.
  • How does if-not-modified-since work? How can it be programmatically implemented with ASP.NET?
    Explain <@OutputCache%> and the usage of VaryByParam, VaryByHeader.
  • How does VaryByCustom work?
  • How would one implement ASP.NET HTML output caching, caching outgoing versions of pages generated via all values of q= except where q=5 (as in http://localhost/page.aspx?q=5)?

Developers using XML

  • What is the purpose of XML Namespaces?
  • When is the DOM appropriate for use? When is it not? Are there size limitations?
  • What is the WS-I Basic Profile and why is it important?
  • Write a small XML document that uses a default namespace and a qualified (prefixed) namespace. Include elements from both namespace.
  • What is the one fundamental difference between Elements and Attributes?
  • What is the difference between Well-Formed XML and Valid XML?
  • How would you validate XML using .NET?
  • Why is this almost always a bad idea? When is it a good idea? myXmlDocument.SelectNodes("//mynode");
  • Describe the difference between pull-style parsers (XmlReader) and eventing-readers (Sax)
  • What is the difference between XPathDocument and XmlDocument? Describe situations where one should be used over the other.
  • What is the difference between an XML "Fragment" and an XML "Document."
  • What does it meant to say “the canonical” form of XML?
  • Why is the XML InfoSet specification different from the Xml DOM? What does the InfoSet attempt to solve?
  • Contrast DTDs versus XSDs. What are their similarities and differences? Which is preferred and why?
  • Does System.Xml support DTDs? How?
  • Can any XML Schema be represented as an object graph? Vice versa?

Monday, August 4, 2008

Conceptual diagram of .NET Framework


Singleton Vs Static Classes

Static classes can have only static variables which will not participate in Serialization.
Singleton classes are best in that case.

We cant always depend on order of Static Initialization. By explicitly initializing our singleton classes we can be sure that someone doesn’t destroy our carefully crafted static initialization bootstrap code by accidentally calling something when it shouldn’t be.

You can't extend static classes, but singletons you can.

For library code static classes can be nice, such as the static System.Math class in C#.

With Singleton, you can keep track of who's using it easily. This is because you need to call the getInstance() or whatever method which returns an instance of the class.

Also, because of the above, you can control the amount of actual instances. In some special cases, it might be useful to have multiple instances of the singleton class, for example for load balancing.

Static classes are stateless. If state is required Singleton can be used.

1. You can control the number of instances. ie, it's not actually *Single*ton.
2. You can sub-class a Singleton while it doesn't make sense to sub-class a class with only static methods.
3. You can control the creation of the actual instance whereas a static approach wouldn't give that flexibility.

DLL Vs EXE

exe file is a excutable file which runs in a seperate process which is managed by OS,where as a dll file is a dynamic link library which can be used in exe files and other dll files

DLL - inprocess
DLL runs along with the application which is sharing that particular DLL. If we interrupt that application that DLL also affected which in turn affects all onter applications which is using that application.

EXE - outprocess
EXE runs seperately.

In short the EXE is not resuable in other application, while the DLL is.

DLL stands for dynamic-link library and is Microsoft’s implementation of a shared library. This means that many different programs can use this library to do their tasks making it easier on the programmers so that they do not have to keep reinventing the wheel each time they write software. In simple terms a .DLL file will contain logic that other programs will use.

EXE stands for executable and denotes that a program is executable. This just means that if you double click on the file a program will run, normally with some kind of interface for a user to interact with. The file formats for EXE and DLL actually the same.

DLL: Doesn't have own main entry point, handled by other method(s).
EXE: Have own entry point, handled by OS.

Response.Redirect vs Server.Transfer

Response.Redirect should be used when:
  • we want to redirect the request to some plain HTML pages on our server or to some other web server
  • we don't care about causing additional roundtrips to the server on each request
  • we do not need to preserve Query String and Form Variables from the original request
  • we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if its necessary)
Server.Transfer should be used when:
  • we want to transfer current page request to another .aspx page on the same server
  • we want to preserve server resources and avoid the unnecessary roundtrips to the server
  • we want to preserve Query String and Form Variables (optionally)
  • we don't need to show the real URL where we redirected the request in the users Web Browser

HTTP Vs HTTPS

The HyperText Transfer Protocol is an application layer protocol, which means it focuses on how information is presented to the user of the computer but doesn’t care a whit about how data gets from Point A to Point B. It is stateless, which means it doesn’t attempt to remember anything about the previous Web session. This is great because there is less data to send, and that means speed. And HTTP operates on Transmission Control Protocol (TCP) Port 80 by default, meaning your computer must send and receive data through this port to use HTTP.

Secure HyperText Transfer Protocol (HTTPS) is for all practical purposes HTTP. The chief distinction is that it uses TCP Port 443 by default, so HTTP and HTTPS are two separate communications. HTTPS works in conjunction with another protocol, Secure Sockets Layer (SSL), to transport data safely. Remember, HTTP and HTTPS don’t care how the data gets to its destination. In contrast, SSL doesn’t care what the data looks like. People often use the terms HTTPS and SSL interchangeably, but this isn’t accurate. HTTPS is secure because it uses SSL to move data.
HTTPS differentiates one sender and receiver from another. SSL takes the data, going or coming, and encrypts it. This means that SSL uses a mathematical algorithm to hide the true meaning of the data. The hope is that this algorithm is so complex it is either impossible or prohibitively difficult to crack

The encryption begins when the owner of the Web site purchases a time-sensitive certificate from a trusted certificate authority such as VeriSign. You can get a certificate anywhere, or even make your own, but is it trusted? Your browser will let you know. This certificate is a security code created specifically for that one user, or even for that one Web site. The code is so complex that no one else on Earth should have a duplicate.

Getting a certificate can be an involved task. All types of information must be recorded so the issuer of the certificate can be a reliable authority on the certificate’s owner. Information that must be provided includes the name of the site and even the name of the server that hosts the site. Complexity makes counterfeiting incredibly difficult.

This makes the issuer a trusted third party. When your browser sees the secure Web site, it uses the information in the certificate to verify that the site is what it claims to be. Browsers commonly indicate security by presenting a picture of a shiny closed lock at the bottom of the screen. This process is not always perfect because of human error. Maybe 53.com is a valid banking site, but 53RD.com is not. We call that phishing. Unscrupulous people phish for careless people. So be cautious. After the identity of the Web site is accepted, the encryption is negotiated between the browser and the Web server, and the data is all but locked up tight.

Stored Procedures Vs User Defined Functions

  • Stored procedures are called independently, using the EXEC command, while functions are called from within another SQL statement.
  • Stored procedure allow you to enhance application security by granting users and applications permission to use stored procedures, rather than permission to access the underlying tables. Stored procedures provide the ability to restrict user actions at a much more granular level than standard SQL Server permissions. For example, if you have an inventory table that cashiers must update each time an item is sold (to decrement the inventory for that item by 1 unit), you can grant cashiers permission to use a decrement_item stored procedure, rather than allowing them to make arbitrary changes to the inventory table.
  • Functions must always return a value (either a scalar value or a table). Stored procedures may return a scalar value, a table value or nothing at all.
  • UDFs can't change the server environment or your operating system environment, while a SPROC can.
  • Operationally, when T-SQL encounters an error the function stops, while T-SQL will ignore an error in a SPROC and proceed to the next statement in your code (provided you've included error handling support).
  • You'll also find that although a SPROC can be used in an XML FOR clause, a UDF cannot be.

Saturday, July 26, 2008

Advantages and Disadvantages of Thread pool

Benefits of Using the Thread Pool

Using the thread pool is the easiest technique you can use to create a multithreaded application for the following reasons:

  • You do not have to create, manage, schedule, and terminate your thread, the thread pool class do all of this for you.

  • There is no worries about creating too many threads and hence affecting system performance. Thread pool size is constrained by the .NET runtime. The number of threads you can use at the same time is limited.

  • You need to write less code, because the .NET framework manages your thread internally with a set of well tested, and bug free routines.

Limitations of Using the Thread Pool

Despite the ease of use, the thread pool has the following limitations or disadvantages when compared to manually managing your threads:

  • With thread pool, you have no control over the state and priority of the thread.
  • With thread pool, you can not give a stable identity to your thread and keep tracking it.
  • When submitting a process to the thread pool, you have no idea when the process will be executed. Your process may be delayed when there are high demand on the thread pool.
  • The thread pool is not suitable when you want to run two tasks or processes using two threads, and need these two tasks to be processed simultaneously in a deterministic fashion.
  • The .NET framework uses the thread pool for asynchronous operations, and this places additional demand on the limited number of available threads.
  • Despite of robust application isolation, there are situations where your application code can be affected by another application code.
In situations where you can not use the thread pool because of its limitations, you can create new threads manually and manage them yourself. This technique is much more complex than using the thread pool, but it gives you more control over your threads.

Thread Pool

Instead of creating a thread each time we need one, and then destroying it after finishing, the .NET framework introduces the concept of thread pool. In the thread pool technique, and instead of creating a new thread whenever you need one, your application will obtain a thread from the thread pool. After that obtained thread completes its task, it will be returned to the thread pool instead of destroying it - waiting for the next acquiring. This reusability increases the overall application performance, and reduces the cost of excessive thread creation and termination.

To make use of this technique, you need to use the System.Threading.ThreadPool class. The thread pool will be created the first time you use it. The number of total threads in this pool is restricted by default to 25 threads. This means that all of these 25 threads may be busy at some point. If you need to acquire a new thread at this point, your task will be scheduled waiting for a thread to finish its task and return to the pool.

In the "default.aspx.vb" file, import the "system.Threading" name space as shown in the following line of code.

1
Imports System.Threading

Create a time consuming method that will be executed in background in a separate thread. To be able to assign this method to the thread pool, it must have the same signature as the "WaitCallBack" delegate. This delegate has the following declaration:


Public Delegate Sub WaitCallback(ByVal state As Object)

This delegate represents a callback method to be executed by a thread pool thread. The "state" parameter represents the information that will be used by your time consuming method if you need to pass information to it.

So, our time consuming method will be as indicated in the following code snippet:


17
Private Sub LongTimeTask(ByVal s As Object)
18
19 Dim i As Integer
20 Dim str As String
21 str = s.ToString
22
23 For i = 0 To 1000
24 str = str + "--" + str
25 Next
26
27 End Sub

Now, in the button click handler type the following lines of code:


5
Protected Sub Button1_Click(ByVal sender As _
6 Object, ByVal e As System.EventArgs) Handles Button1.Click
7
8 If ThreadPool.QueueUserWorkItem( _
9 New WaitCallback(AddressOf LongTimeTask), TextBox1.Text) _
10 Then
11 Label2.Text = "Queued successfully"
12 Else
13 Label2.Text = "Failed"
14 End If
15
16 End Sub

In the line #8 of the above code, we used the ThreadPool.QueueUserWorkItem function to queue our time consuming method for execution in a separate thread from the thread pool. The first parameter to this function is a new instance of the WaitCallBack delegate that represents the method to be executed. In our case, the method to be executed is the 'LongTimeTask' method. The second parameter is the parameter to be passed to the 'LongTimeTask' method itself. In our case this parameter is the text entered by the end user in the text box control. This function returns 'True' when the queuing operation succeed, or 'False' when it fails.

Now, run your application and enter any text into the text box, then click the button, and observe the results.

It will be much better to enter long text in the text box, or to increase the number of loop iterations to get better feeling of this operation. You can also add a new text box control to the "default.aspx" page, so you can test your user interface responsiveness while you run the time consuming task at background.

That's it ...

As you can see it is so easy to use this technique to solve your annoying time consuming tasks problem. Be warned then! This ease will cost you.

MultiThreading

Multithreading is a technique that can be used to perform time consuming tasks in a separate additional thread other than the main application thread.

When you, for example, have a time-consuming function, you may need to call this function as a response of a button click. Now, instead of freezing all your application waiting for this function to return / to finish, you can create a new thread and assign this function to. When you do this, your application interface will not be blocked and you can use it to perform other tasks. At the same time, your time-consuming task is being carried out in the background.

You can think of it as the two threads: the main one, and the newly created one. Both are running in parallel, and this improves the performance and responsiveness of your application.

Advantages and Disadvantages of Using Multithreading

Despite improving your application's performance, and avoiding unresponsive user interface, multithreading has the following disadvantages:

  • There is a runtime overhead associated with creating and destroying threads. When your application creates and destroys threads frequently, this overhead affects the overall application performance.
  • Having too many threads running at the same time decreases the performance of your entire system. This is because your system is attempting to give each thread a time slot to operate inside.
  • You should design your application well when you are going to use multithreading, or otherwise your application will be difficult to maintain and extend.
  • You should be careful when you implement a multithreading application, because threading bugs are difficult to debug and resolve.

Notes:

  • Each time a thread is created, a certain amount of memory is consumed to hold this thread context information. Hence, the number of threads that can be created is limited by the amount of available memory.

  • More threads does not mean a faster responsive application, instead it can decrease the performance of your application.

Sealed Classes

Classes can be declared as sealed. This is accomplished by putting the sealed keyword before the keyword class in the class definition. For example:

public sealed class classSealed
{
// Class members here.
public string ID;
public double Price;

}
In the following code listing the implementation of a sealed class has been tested.

classSealed sc=new classSealed();
sc.ID=”C1”;
sc.Price=500.00;
double Samt=sc. CalculatePrice();
Response.Write(“Total Net Price of Product : “ +” “+sc.ID +” “+is+” “+Samt);
Response.Write(“
”);


A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster. Sealing a class means one can not derive from it. Sealing a method means one can not override it. In C# structs are implicitly sealed; therefore, they cannot be inherited. If we try to inherit from a sealed class in another class we will get compile time error about Inconsistent accessibility (code is shown in following code listing).

public class TestClass : classSealed
{
}

In C# a method can not be declared as sealed. However when we override a method in a derived class, we can declare the overridden method as sealed as shown below. By declaring it as sealed, we can avoid further overriding of this method.

public class testClass
{
public int x;
public int y;
public virtual void testMethod(){

}

}

public class TestClass: testClass
{
public override sealed void testMethod()
{

}
}

Abstract Classes or Interfaces

An abstract class only allows other classes to inherit from it and cannot be instantiated. When we create an abstract class, it should have one or more completed methods but at least one or more uncompleted methods and these must be preceded by the key word abstract. If all the methods of an abstract class are uncompleted then it is the same as an interface, but there is a restriction that it cannot make a class inherit from it, which means it can not work as a base class.

An interface is defined by the key word interface. An interface has no implementation; it only has the definition of the methods without the body. When we create an interface, we are basically creating a set of methods without any implementation. A class implementing an interface must provide the implementation of the interface members. All the methods and properties defined in an interface are by default public and abstract

Abstract classes can add more functionality without destroying the child classes that were using the old version. Abstract classes provide a simple and easy way to version our components. By updating the base class, all inheriting classes are automatically updated with the change. In an interface, creation of additional functions will have an effect on its child classes due to the necessary implementation of interface Methods in classes. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes. Say there are two classes, bird and airplane, and both of them have methods called fly. It would be ridiculous for an airplane to inherit from the bird class just because it has the fly() method. Rather, the fly() method should be defined as an interface and both bird and airplane should implement that interface. If we want to provide common, implemented functionality among all implementations of component, we should use an abstract class. Abstract classes allow us to partially implement classes, whereas interfaces contain no implementation for any members. So the selection of interface or abstract classes depends on the needs and design of our project. We can make an abstract class, interface, or combination of both depending on our needs.

The most likely situation in which we make a class or method sealed will be if the class or method is internal to the operation of the library, class, or other classes that we are writing. Because any attempt to override some of its functionality will cause problems. We can mark a class or method as sealed for commercial reasons, in order to prevent a third party from extending our classes. For example, in the .NET base class library string is a sealed class.

We should not use the sealed key word on a method unless that method is itself an override of another method in some base class. If we are defining a new method and we don’t want anyone else to override it, we should not declare it as virtual in the first place. If however, we have overridden a base class method, the sealed keyword provides a way of ensuring that the override supplied to a method is a “final” override that means no one else can override it again.

As given in MSDN

Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.

  • If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
  • If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
  • If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
  • If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.



Suppress Finalization

After the Dispose method has been called on an object, you should suppress calls to the Finalize method by invoking the GC.SuppressFinalize method as a measure of performance optimization. Note that you should never change the order of calls in the finalization context (first Dispose(true) and then GC.SupressFinalize) to ensure that the latter gets called if and only if the Dispose method has completed its operation successfully.

The following code illustrates how to implement both the Dispose and Finalize pattern for a class.

   public class Base: IDisposable
{
private bool isDisposed = false;

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!isDisposed)
{
if (disposing)
{
// Code to dispose the managed resources
// held by the class
}
}
// Code to dispose the unmanaged resources
// held by the class
isDisposed = true;
base.Dispose(disposing);
}
~Base()
{
Dispose (false);
}
}
You should not reimplement IDisposable for a class that inherits from a base class in which IDispose has already been implemented. The following code snippet may help you understand this concept:

   public class Base: IDisposable
{
private bool isDisposed = false;

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!isDisposed)
{
if (disposing)
{
// Code to dispose managed resources
// held by the class
}
}
// Code to dispose unmanaged resources
// held by the class
isDisposed = true;
base.Dispose(disposing);
}
~Base()
{
Dispose (false);
}
}

public class Derived: Base
{
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Code to cleanup managed resources held by the class.
}

// Code to cleanup unmanaged resources held by the class.

base.Dispose(disposing);
}
// Note that the derived class does not // re-implement IDisposable
}
In the preceding code, what if the Dispose method were to throw an exception? In that case, the Finalize method would exit prematurely, and the memory would never be reclaimed. Hence, in such situations, it is advisable to wrap the Dispose method in a try-catch block. This will prevent finalization exceptions from orphaning the object.

Note the following points when implementing disposable types:

  • Implement IDisposable on every type that has a finalizer
  • Ensure that an object is made unusable after making a call to the Dispose method. In other words, avoid using an object after the Dispose method has been called on it.
  • Call Dispose on all IDisposable types once you are done with them
  • Allow Dispose to be called multiple times without raising errors.
  • Suppress later calls to the finalizer from within the Dispose method using the GC.SuppressFinalize method
  • Avoid creating disposable value types
  • Avoid throwing exceptions from within Dispose methods
In a managed environment, the GC takes care of freeing unused objects. In contrast, in unmanaged languages such as C, developers had to release unused objects explicitly that were created dynamically in the heap. However, a proper understanding of both the Dispose and Finalize methods goes a long way toward designing efficient applications.

The Dispose/Finalize Pattern

Microsoft recommends that you implement both Dispose and Finalize when working with unmanaged resources. The correct sequence then would be for a developer to call Dispose. The Finalize implementation would run and the resources would still be released when the object is garbage collected even if a developer neglected to call the Dispose method explicitly.

Dispose/Finalize pattern should be used only when your type invokes unmanaged code that
allocates unmanaged resources (including unmanaged memory) and returns a handle that you must use eventually to release the resource. Both dispose and finalize must chain up to their parent objects by calling their parent's respective methods after they have disposed or finalized
their own members".

Simply put, cleanup the unmanaged resources in the Finalize method and the managed ones in the Dispose method, when the Dispose/Finalize pattern has been used in your code.

As an example, consider a class that holds a database connection instance. A developer can call Dispose on an instance of this class to release the memory resource held by the database connection object. After it is freed, the Finalize method can be called when the class instance needs to be released from the memory. According to MSDN, "Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose"

How to use Dispose method

Unlike Finalize, developers should call Dispose explicitly to free unmanaged resources. In fact, you should call the Dispose method explicitly on any object that implements it to free any unmanaged resources for which the object may be holding references. The Dispose method generally doesn't free managed memory—typically, it's used for early reclamation of only the unmanaged resources to which a class is holding references. In other words, this method can release the unmanaged resources in a deterministic fashion.

However, Dispose doesn't remove the object itself from memory. The object will be removed when the garbage collector finds it convenient. It should be noted that the developer implementing the Dispose method must call GC.SuppressFinalize(this) to prevent the finalizer from running

Note that an object should implement IDisposable and the Dispose method not only when it must explicitly free unmanaged resources, but also when it instantiates managed classes which in turn use such unmanaged resources. Implementing IDisposable is a good choice when you want your code, not the GC, to decide when to clean up resources. Further, note that the Dispose method should not be called concurrently from two or more different threads as it might lead to unpredictable results if other threads still have access to unmanaged resources belonging to the instance.

The IDisposable interface consists of only one Dispose method with no arguments.

   public interface IDisposable
{
void Dispose();
}
The following code illustrates how to implement the Dispose method on a class that implements the IDisposable interface:

   class Test : IDisposable
{
private bool isDisposed = false;

~Test()
{
Dispose(false);
}

protected void Dispose(bool disposing)
{
if (disposing)
{
// Code to dispose the managed resources of the class
}
// Code to dispose the un-managed resources of the class

isDisposed = true;
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}



In the preceding code, when the Boolean variable disposed equals true, the object can free both managed and unmanaged resources; but if the value equals false, the call has been initiated from within the finalizer (~Test) in which case the object should release only the unmanaged resources that the instance has reference to.

Dispose & Finalize

Finalization is the process by which the GC allows objects to clean up any unmanaged resources that they're holding, before the actually destroying the instance. An implementation of the Finalize method is called a "finalizer." Finalizers should free only external resources held directly by the object itself. The GC attempts to call finalizers on objects when it finds that the object is no longer in use—when no other object is holding a valid reference to it. In other words, finalizers are methods that the GC calls on "seemingly dead objects" before it reclaims memory for that object.

The GC calls an object's finalizer automatically, typically once per instance—although that's not always the case. You should never rely on finalizers to clean up managed resources. A class that has no finalizer implemented but is holding references to unmanaged objects can cause memory leaks, because the resources might become orphaned if a class instance is destroyed before releasing the unmanaged objects.

The time and order of execution of finalizers cannot be predicted or pre-determined. This is why you'll hear that the nature of finalization is "non-deterministic." Further, due to the non-deterministic nature of finalization the framework does not and cannot guarantee that the Finalize method will ever be called on an instance. Hence, you cannot rely upon this method to free up any un-managed resources (such as a file handle or a database connection instance) that would otherwise not be garbage collected by the GC.

Note that you cannot call or override the Finalize method. It is generated implicitly if you have a destructor for the class.

class Test
{

// Some Code

~Test
{
//Necessary cleanup code
}
}

In the preceding code, the ~Test syntax declares an explicit destructor in C#, letting you write explicit cleanup code that will run during the finalize operation.

The framework implicitly translates the explicit destructor to create a call to Finalize:

   protected override void Finalize()
{
try
{
//Necessary cleanup code
}
finally
{
base.Finalize();
}
}


Note that the generated code above calls the base.Finalize method.

You should note the following points should when implementing finalizers:

  • Finalizers should always be protected, not public or private so that the method cannot be called from the application's code directly and at the same time, it can make a call to the base.Finalize method
  • Finalizers should release unmanaged resources only.
  • The framework does not guarantee that a finalizer will execute at all on any given instance.
  • Never allocate memory in finalizers or call virtual methods from finalizers.
  • Avoid synchronization and raising unhandled exceptions in the finalizers.
  • The execution order of finalizers is non-deterministic—in other words, you can't rely on another object still being available within your finalizer.
  • Do not define finalizers on value types.
  • Don't create empty destructors. In other words, you should never explicitly define a destructor unless your class needs to clean up unmanaged resources—and if you do define one, it should do some work. If, later, you no longer need to clean up unmanaged resources in the destructor, remove it altogether.
Finalize() is a non-explicit way to clean up resources. Because you can't control when (or even if) the GC calls Finalize, you should treat destructors only as a fallback mechanism for releasing unmanaged resources. Instead, the approved way to release unmanaged resources is to make your class inherit from the IDisposable interface and implement the Dispose() method


Tuesday, June 3, 2008

ASP.NET 3.5 Features

Integrated ASP.NET AJAX support

ListView control - ListView is update to DataList and Repeater controls

DataPager control - Free standing paging Interface. It renders a paging interface with Next Previous first last buttons and is tied to a data web control.
It works only with web controls that implements IPageableItemContainer interface, which currently includes only ListView control

3.5 framework has LINQ - Language Integrated Query.

LINQ makes SQl Like syntax allowing developers to work work with data.
Ex:

List<string> ProductNames = from p in products
where p.productid = 1
select p.productname

LINQ statements operate on Database , XML or an Object Layer.
VS 2008 gives Intellisense support to LINQ Syntax

VS 2008 New Features

Visual Studio 2008 is Multi Targeted. That is, we can choose which framework to work on from a dropdownlist. (2.0, 3.0, 3.5).
That is with 2008 we can start working 2.0 also.

Improved Designer experience - Split Screen feature
If some control is dropped on to the page source view automatically gets changed.
But the reverse is not true. You have to save page or click on refresh in designer.

Javascript Debugging
Itellisense features
Advanced CSS editing options

Programming Practices

Refactor Large methods.
Do not share Member variables.
Use Try Catch and Finally block.
Close objects once its work is over.
Open database connection just before executing query and close in finally block.
Create Business Objects.
Sepearte Presentation, Business Logic and Data Access layers.
Do not send database objects to presentation layer.
Use Generics.
Catch exceptions, give proper message to user and store info in log file.
Store ConnectionString in Web.Config file encrypted
Use Page.IsValid before submitting your page when you are using Server side validation controls
when any browser doesnt support javascript, Page.IsValid avoids submitting data
Use StringBuilder than String

Use Custom Base Page class when there is a need to change some value for all pages
Do not forget to change Debug property to False before Deploying application into production
Always use dataReaders with "using" like
Using (SQLdataReader dr = cmd.ExecuteReader())
{
While(dr.read())
{
Response.Write(dr.GetString(0));
}
}

Use dataReader when datspeed is a concern
Whenever data is retrieved from database to a variable check for null
Use ObjectDataSource than SQLdataSource
Use CSS instead of formatting controls in page itself
If page is CrossPosted check if PreviousPage != null
If you want to resue inside a single project Web User Control is the fastest way.
Do not store heavy objects in ViewState

Speed Optimization

Paging - Do not use User Interface Paging. Use ObjectDataSource's CanPage property.
Turn off session state where it is not used - <%@ Page EnableSessionState="False" %>
Viewstate can be turned off when not required .

Use Caching
Use SqlDataReaders
Use Stored Procedures

Monday, May 12, 2008

ADO.NET

ADO.NET (ActiveX Data Objects) is set of classes that expose data access services to the .NET application.
It uses 2 types of objects to access data from database.
a. Datasets
b. .NET Data Provider Objects - Data Adapters, Commands , Connections

Dataset holds entire database int it. So we can have the data inserted, updated in it though the connection is lost from the datasource. this is referred to as Disconnected architecture.

DataAdapter serves as a bridge between dataset and a datasource for retrieving and saving data
Used to exchange data between datasource and dataset.

To trnasmit a database table of dataset to the datastore, dataadapters Update method can be used. When thos method is invoked, it executes whatever SQl INSERT, UPDATE, DELETE statements are needed depending on the affected record is new, changes or deleted.

Connection pooling enables an application to use a connection from a pool of connections that do not need to be re established for every use. Once connection has been created and placed in connection pool, application can reuse the connection without performing the complete connection creation process.

Web Services

A Web Service is a Software component stored in one machine that can be accessed by another application in another machine over a network.

Methods in Web Service are invoked through a Remote Procedure Call(RPC).

SOAP (Simple Object Access Protocol) is a platform independant protocol that uses XML to make Remote Procedure Calls.

When a program invokes a Web Method , the request and all relevant info is packaged in a SOAP message and sent to the server where Web Service resides.
A Web Service receives SOAP message, parses its contents to determine the method program wishes to execute and method parameters.
After a web service parses a SOAP message a proper method is called and response is sent back to the client in another SOAP message.

Client and a Web Service communicate using messages, specifically SOAP messages by default. Client sends a SOAP request to a Web Service, and a Web Service method typically returns a SOAP response. Web Services define the type of messages they accept using operations, defined by Web Services Description Language (WSDL). The data that is eventually communicatedover the network must be serialized into XML.

A Web Method tells the .NET that perticular public method should be exposed as a Web-Callable method.

WSDL is written in XML. It is an XML document. It si used to describe Web Services. Used to locate Web Services.

Four major parts of WSDL document
a. WSDL Ports - describes operations that can be performed, messages that are involved.
b WSDL Messages - Defines the data elements of an operation.
c. WSDL Types - Defines the datatype that are used by the Web Service.
d. WSDl Bindings - Defines message format and protocol details for each port.

Sunday, May 11, 2008

.NET Framework

The .NET Framework is a development and execution environment that allows different programming languages & libraries to work together seamlessly to create Windows, Web, or Mobile applications that are easier to build, manage, deploy, and integrate with other networked systems or as stand alone applications.

AJAX

Asynchronous Javascript and XML
1. Is combination of technologies that allows content of a web page to be updated or changed without the entire page being re loaded.
2. AJAX can be implemented in Browsers that do not support XMLHTTPRequest object. possible using remote scripts.
3. AJAX technology is independant of web servers. AJAX is client Technology.
4. AJAX is supported in IE 5 and above, Netscape, Opera, safari, Firefox
5. responseText and responseXML are properties
6. overrideMimeType(), setRequestHeader(), getResponseHeader() are the methods
7.
ASP.NET Ajax is a free framework for quickly creating efficient and interactive web applications that word across all popular browsers
8. AJAX Control toolkit can be downloaded for ASP.NET 2.0. But is a part of ASP.NET 3.5 framework
9. Version 1.0.20229 for .NET 1.0 and 2.0
10. Version 3.5.20229 for .NET 3.5
11. Dojo is modular open source Javascript toolkit designed to ease the rapid development of AJAX based applications
12. Multiple AJAX requests can be made by creating multiple XMLHHTTPRequest objects.
13. ScriptManager is a server side control that sits on your web form and enables core of ASP.NET AJAX.
14. Its primary role is the arbitration of all other ASP.NET AJAX controls on the web form and addition of the right scripting libraries to the web browser so that client portion of ASP.NET AJAX can function
a. Managing all resources on a web page
b. Managing partial page updates
c. Download AJAX script library to the client
d. Interacting with UpdatePanel and UpdateProgress controls
e. Register script (Using RegisterClientScriptBlock)
f. Providig access to web service methods by registering web services with the ScriptManager control.
g. Providing access to ASP.NET Authentication, role and profile application services from client script after registering these from ScriptManager control.
h. Enable culture specific display of client side script.
i. Register server controls that implement IExtenderControl and IScriptControl interfaces
15. Multiple ScriptManager controls cannot be used in a web page

Differences between 1.1 and 2.0

1. Generics are introduces in 2.0
2. Master Pages introduced in 2.0
3. Nullable datatypes introduced in 2.0
4. Profile Object introduced in 2.0
5. 2.0 Has built in Web Server
6. This article outlines changes to the code model, compilation, page lifecycle, and more - http://msdn2.microsoft.com/en-us/library/ms379581(VS.80).aspx

Saturday, May 10, 2008

Helpful Points

1. Master Pages are not available in ASP.NET 1.1
2. Datareader can be provided as datasource for GridView in web applications only, but paging and sorting will be difficult. Also data cannot be updated.
3. In ADO.net for Command Object you have 3 methods
a.ExecuteReader - Select statements
b.ExecuteNonQuery - DML statements(Insert,Update and Delete)
c.ExecuteScalar - Returns a single value from Aggragate functions like SUM,AVG,COUNT etc
4. machine.config settings are applicable to all the applications running on that server, web.config settings are applicable to only that application
5. An application can havemore than 1 web.config file, but they should be in different directories of that web application also the sub directory that uses it must be a virtual directory.
6. One website can have 20 cookies with 4kb per cookie.
7. To Maintain viewstate of Dynamic controls, bind them in Init event. because if done in Page Load, it would have already set default values.
8. There are three types of JIT compilers
a. Pre: This JIT compiles the whole application
b. Econo: This compiles the modules called at RunTime
c. Normal: This compiles modules called at runtime and keep it in cache
9. Caching is the technique of persisting data in memory for immediate access to requesting program calls.
10. This is considered as the best way to increase performance of the application
11. Caching is of 3 Types
a. Output Caching : Caches the whole page.
b. Fragment Caching : Caches only a part of the page.
c. Data Caching: Caches the data.

12. Authntication is giving access to the site
13. Authorization is giving access to perform some operations in site
14. Request.ServerVariables["SERVER_SOFTWARE"] gives which version of IIS application is using.
15. Permanent cookie can be created from following code
HTTPCookie c = new HTTPCookie ("MyCookie", "MyText");
c.Expires = DateTime.MaxValue;
Respon.Cookies.Add(c);
16. In ADO.NET data is sent in XML format hence easily sent across firewalls whereas in other languages data is sent in binary format which firewall poses problems
17. When AutoEventWireup is true ASP.NEt need not require events to specify event handlers like Page_Init, Page_Load. Means handles keyword not required in VB.
In the case where AutoEventWireup attribute is set to false (by default), event handlers are automatically required for Page_Load or Page_Init. However, when we set the value of the AutoEventWireup attribute to true, the ASP.NET runtime does not require events to specify event handlers like Page_Load or Page_Init.
18. ASP.NET application can be run without WEB.CONFIG since all the settings required for an ASP.NE application is available in MACHINE.CONFIG
19. WEB.CONFIG if present for any application overrides settings in MACHINE.CONFIG for that application.
20. Garbage Collector is mainly used for Automatic Memory Management. Monitor leaked or unused memory objects that are loaded into memory. Garbage Collector releases memory objects. Cannot say when this runs. but can be called programmatically
system.gc.collect(); but not recommended
21. Reflection is used for Late Binding of Objects in .NET. By using reflection one can use COM components and create objects of them at Runtime. It invokes properties and objects of that COM.
22. DataSet.Clone() creates new instance of same object.
23. DataSet.Copy() Copies content of data to another object without creating new instance
24. Web parts allows the user to customize how site looks. Present only in 2.0
25. Web Services used SOAP and HTTp protocols. message is first converted to XML and serializes and sent through HTTP protocol to the server. In Server again it deserializes and from XML file it gets info it wanted. As message is sent as XML it is platform independant.
Remoting allows us to enjoy the same power of web services when the platform is same. We can connect directly to server over TCP and send binary data without having to do lots of conversation.
26.


ASP.NET Web Services

.NET Remoting

Protocol

Can be accessed only over HTTP

Can be accessed over any protocol (including TCP, HTTP, SMTP and so on)

State Management

Web services work in a stateless environment

Provide support for both stateful and stateless environments through Singleton and SingleCall objects

Type System

Web services support only the datatypes defined in the XSD type system, limiting the number of objects that can be serialized.

Using binary communication, .NET Remoting can provide support for rich type system

Interoperability

Web services support interoperability across platforms, and are ideal for heterogeneous environments.

.NET remoting requires the client be built using .NET, enforcing homogenous environment.

Reliability

Highly reliable due to the fact that Web services are always hosted in IIS

Can also take advantage of IIS for fault isolation. If IIS is not used, application needs to provide plumbing for ensuring the reliability of the application.

Extensibility

Provides extensibility by allowing us to intercept the SOAP messages during the serialization and deserialization stages.

Very extensible by allowing us to customize the different components of the .NET remoting framework.

Ease-of-Programming

Easy-to-create and deploy.

Complex to program.

Important Points to Note 2

1. inetinfo.exe is the microsoft IIS server running, handling ASP.NET requests. When an ASP.NET request is received, the ISAPI filter aspnet_isapi.dll takes care of it by passing the request o the actual worker process aspnet_wp.exe
2. Page Load events
a. Init()
b. Load()
c. PreRender()
d. UnLoad()
3. ViewState is available after Init() and before Page_Load().
4. A Web Page is an instance of System.Web.UI.Page
5. Information about users locale is stored in System.Web.UI.Page.Culture
6. Codebehind="MyCode.aspx.cs" and Src="MyCode.aspx.cs", Codebehind is used only in Visual Studio .NET
7. range Validator supports Integer, String, Date datatypes
8. All User input data should be validated at server side. additionally client side code can be provided for richer and more responsive experience for the user
9. Server. Transfer transfers page processing from one page to another without making round trip back to the client browser. This provides faster response and little less overhead on the server. It does not update history list.
10. Response.redirect performs a round trip back to the clients browser where client browser is redirected to new page . Users history list is updated
11. ADO.NET
a. can represent an entire relational database, tables, relations, views
b. can work without continuing connection with the datasource
c. data in dataset is bulk loaded, ather than loading on demand
d. No concepts of cursors in dataset
e. No current record pointer, can use for each to loop through records
f. Can store many edits in dataset and write them to original datastore in single operation

12. Global.asax is used to implement application and session level events.
13. Diffgram is one of the 2 XML formats that can be used to render dataset object contents to XML file. Useful when reading database data and sending it to WebService through XML.
14. MSIL allows the .NET Framework to JIT compile the assembly on the installed computer.
15. data cannot be edited in Repeater control
16. ControlToValidate and Text property are the 2 common properties found in all Validation controls
17. A single .NET DLL can contain many classes
18. SOAP - Simple Object Access Protocol is the protocol used to call a Web Service.
19. Web Service can be written in any language
20. WSDL stands for - Web Services Description Language
21. ViewState allows the state of serializable objects to be stored in a hidden field on a page.
It is transported to the client and back to the server.
It is not stored in server or any other external Source
It is used to retain the state of server side objects between postbacks
22. ASP.NET provides In-Process and Out-of-Process state management.
In-Process stores the session in memory in Web Server. It requires "sticky-server" (no load balancing) so that the user is always reconnected to the same web server.
Out-of-Process sesion state management stores data in an external data source. Exernal device may be SQl Server or State Server service.
Out-of-Process state management requires all objects stored on session are serializable

Important Points to Note

1. Every class is derived from System.Object
2. Immutable - Data value may not be changed. variable value may be changed, but the original immutable data is discareded and new data value is created in memory.
3. Finally block will be executed even though the exception occurs.
4. "Sealed" keyword prevents your class from being inherited.
5. You can make class public but method as sealed will prevent method from being overridden
6. "Abstract Class" - Class cannot be instantiated. So it must be Inherited
7. Multiple interfaces can be implemented, but multiple classes cannot be inherited
8. Inside interface access modifiers cannot eb specified as all methods has to be implemented by class. So they all must be public and hence they are public by default.
9. Difference between Interface and Abstract class.
Interface Abstract
a. all methods are abstract Some methods can be concrete
b. there is no implementation implementations can be present
c. no accessibility modifiers allowed allowed
10. "Virtual" keyword says method or property can be overridden
11. Delegate object encapsulates a reference to a method. mainly used in events.
12. Debug class can be used for Debug builds, Trace can be used for both Debug and Release builds.
13. DLL Hell - Assembly versioning allows applications to specify not only lirary it needs to run, but also the version of the assembly
14. Floowing are different ways of deplyong assembly
a. MSI Installer
b. CAB Archive
c. XCOPY Deployment
15. When we write Multi Lingual applications and want to distribute core application seperately from the localized modules, the localized assemblies that modify the core application are called
16. Assembly is the smallest unit of execution in .NET
17. System.Globalization and Sstem.resources namespaces are neccessary to create localized applications
18. You should not call Garbage collector. However, you caould call garbeg collector when you are done using a large object to force the garbage collector to dispose of those very large objects from memory. But still this is usually not a good practice.
19. Using Boxing Value Type can be converted into Reference Type
20. Since Boxing converts value type to reference type object will be stored in Heap
UnBoxing converts reference type to value type so, object will be stored in Stack

Saturday, April 12, 2008

Using Yahoo Search in your Application

embeding Yahoo Search in our applications is very easy .

Yahoo.API.dll can be downloaded from below link

http://developer.yahoo.com/download/download.html

Add this as reference in your solution and use below code:


protected void Search()
{
// Search Code
string strSearch = "web services";

Label1.Text = "Search Result for " + strSearch + " ";

Yahoo.API.YahooSearchService yahoo = new Yahoo.API.YahooSearchService();
Yahoo.API.WebSearchResponse.ResultSet resultSet;
resultSet = yahoo.WebSearch("YahooExample", strSearch, "all", 10, 1, "any", true, true, "en");
StringWriter sw = new StringWriter();

foreach (Yahoo.API.WebSearchResponse.ResultType result in resultSet.Result)
{
sw.WriteLine("{0}
", result.Title, result.ClickUrl);
sw.WriteLine("{0}
", result.Summary);
sw.WriteLine("{0}
", result.Url);
sw.WriteLine("
");
}
txtContent.Text = sw.ToString();
}

Web Crawler

Using System.Net.WebClient class, we can easily send data to or recieve data from an URI.

Below is a simple example of a web crawler using System.Net.WebClient class.
This will check for anchor tags in specified URI and adds all links to a ListBox. After getting the link, we can use it for whatever purpose.


ASPX.CS
________
protected void btnSubmit_Click(object sender, EventArgs e)
{
string strURL = txtLink.Text;
System.Net.WebClient wc = new System.Net.WebClient();
byte[] data = wc.DownloadData(strURL);
mshtml.HTMLDocumentClass ms = new mshtml.HTMLDocumentClass();
string strHTML =System.Text.Encoding.ASCII.GetString(data);
mshtml.IHTMLDocument2 objMyDoc = (mshtml.IHTMLDocument2)ms;
objMyDoc.write(strHTML);

mshtml.IHTMLElementCollection ec = (mshtml.IHTMLElementCollection)objMyDoc.links;

for (int i = 0; i < ec.length; i++)
{
string strLink;
mshtml.HTMLAnchorElementClass objAnchor;
try
{
objAnchor = (mshtml.HTMLAnchorElementClass)ec.item(i, 0);
strLink = objAnchor.href;
lstLinks.Items.Add(strLink);
}
catch
{
continue;
}

}
}

where txtLink is textbox where we enter URI
ex: http://www.google.com // URI - starts from http://
lstLinks is ListBox and btnSubmit is Button

for getting System.Net.WebClient add reference to Microsoft HTML Object Library on your solution

Monday, April 7, 2008

Using ajax we can place any control inside AJAX Update panel and by raising events we can get the data from server without posting whole page. Suppose a textbox is placed in an AJAX Update panel with Autopost back property = true and having textchanged event. then when text is changed textChanged event is raised and if any logic is written that will be processed and only that control is rendered but not the whole page..

Only thing to be noticed is that in Triggers tag we cant give client side events like OnKeyPress.
But when some data to be fetched on key press we need to call RaiseCallBackEvent to call server side code having placed TextBox inside Update panel. this way server side code is executed which binds the grid. That grid and Textbox both should be inside panel.
From this post onwards i will keep on adding the problems i faced while developing applications, how i solved them, where did i search for solutions, was it helpful and lot of stuff....

First thing

The first thing i did after creating blog is copied the URL and pasted in my ToDo list text file.. :)

Narasimha