live wid knowledge :)

Interview Questions (Scott Hanselman) & Answers (Muhammad Adnan Amanaullah) :)

 Let’s answer Scott Hanselman interview questions.

First of all, I would like to clear, purpose of this post is only educational/sharing knowledge. May be i am wrong and i would love if any1 of you correct me through commenting to this post with authentic references. i will really appreciate the contributors.

Many days back I saw Scott hanselman website and kept reading his many other blogs and I found a list of interview questions which he said, he asked usually and he thinks should be known by .net guys at different levels. I got many (some wrote and answered as well) interview questions and put them at single platform just for knowledge sharing @ http://interviewquestion.wordpress.com . Actually I always like to be part of interviews questions so I decided to write answer of them according to my little knowledge.

I can say now, it’s really great learning/evaluation experience when I was thinking/writing their answers as to just skim them is another thing than to answer them.

Hmmm now let me tell you I didn’t answer 100% and didn’t know answer 100% as well so I just tell you how much I answered by my brain and how much I couldn’t. I have divided answers in three categories. 1 I knew (with following emoticon) :) . 2 I didn’t know with this emoticon :( . 3 I know but not sure with this emoticon ;) so took either help or wrote according to my littleeeeeee knowledge.

At the end of each question I have mentioned emoticon to mention which I knew and … if you are interested to know which I knew or not, it would help you to know rather pinging me on msn :D

Let me make stats for my knowledge vs questions :P

Total Questions: 84
I knew: 61 (I think if I dind’t count wrong)
I was not sure about 16
I didn’t know 7

What Great .NET Developers Ought To Know

Everyone who writes code

  • Describe the difference between a Thread and a Process? :)
  • Thread is minimum unit for processor to execute. Collections of threads make process. By dividing process into threads, processor achieves multi tasking (by running threads concurrently not parallel). Threads can share memory but processes can’t share memory. Threads can communicate with each other of same process without any middle layer but process can’t they required inter process communication kind of thingy.
  • What is a Windows Service and how does its lifecycle differ from a “standard” EXE? ;)
  • Windows service is windows based background process which has no user interface like any other service (aka daemon in UNIX based environment). Windows service needs to be installed before executing unlike EXE. Windows service used to perform such tasks which doesn’t required user interaction but system status based events like performing tasks at specific intervals or at different state of system like alarm user when disk is about to get full to clean up. Windows service is controlled by Service control manager (SCM) and it started automatically even user didn’t login to his/her windows account (as SCM already has account credentials so SCM knows if system start which service needs to start and by which account), where as EXE is controlled by OS and runs only when user get login using windows account.
  • 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? ;)
  • Single process on windows can address different amount of memory as it depends upon systems (32bit/64bit processor) and OS as well. Yes process memory consumption size can be different from maximum virtual memory size. If software/process code is written by keeping 64 bit processor (as 64 bit processor support more than double memory) then it won’t be able to run that process on 32 bit system.
  • What is the difference between an EXE and a DLL? :)
  • Exe is executable and independent program/process to run which has its own reserved memory space whereas DLL (Dynamic Link Library) is neither executable and not even independent, it used by other DLL/program.
  • What is strong-typing versus weak-typing? Which is preferred? Why? :)
  • Strong typing means a person who has great typing skills and that chat do too much chatting :D just joking. Strong typing means when code compiles, type rules enforced strictly according to their data assigned to them whereas weak typing is quite opposite of this definition. JavaScript/C/C++ is weak typing but .net based languages are strongly typed. Strong typing is preferred by means of less run time errors risk and efficient during execution of program but not during compile time.
  • Corillian’s product is a “Component Container.” Name at least 3 component containers that ship now with the Windows Server Family. ;)
  • I am not sure either I understood this question in correct way. I think answer would be Windows Shell, Windows Explorer, IIS (happy guessing)
  • What is a PID? How is it useful when troubleshooting a system? :)
  • PID is Process ID which is unique to identify any process within a system. Whilst troubleshooting we can kill process through its PID.
  • How many processes can listen on a single TCP/IP port? :)
  • I think single process can only hold handler of any port at a time means can listen on single port. Once I got error when I ran my web application as another application (skype) was using that port. It make sense as well, ports are like doors if two people talk on specific door and third one comes up then no privacy :-D (divorce ratio would be dramatically raised)
  • What is the GAC? What problem does it solve? :)
  • GAC stands for Global Access Cache where shareable/public assemblies (DLL) stored to be used by multiple programs. It gives a shared platform for programs to use single assembly and can store same assembly (of same name) with different versions and can help to solve DLL HELL.

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

· An interface is strictly a Contract without implementation means interface can only declare properties or methods. Class can have implementation of its methods, can have different level of access identifiers whereas interface’s properties or methods can have only public access identifier and can implement class and multiple interfaces.

· What is Reflection? :)


Reflection is mechanism to load dynamically assembly at runtime and using assembly Meta data can access its namespace, class and their properties, methods and even events.

· What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP? :(

· Remoting assumes the other end is .NET. This is because .NET remoting using SOAP uses the SoapFormatter to serialize data. SoapFormatter embeds the type information required to deserialize the object into the message itself. This requires that the client and the server must have access to this assembly. Remoting believes in the .NET Type System. Remoting believes in sharing types and assemblies. Remoting can support DCOM style Client Activated Objects which are stateful. The use of CAOs though have to be carefully thought about because CAOs cannot be load balanced. ASMX model does not assume that the other end is .NET. ASMX uses XmlSerializer to serialize data. Xmlserailizer believes that the XML Type System, that is the XSD is superior and works on serializing data conforming to a schema. In other words XML Web Services believe in sharing schema and contracts over types and assemblies. This makes the Web Services interoperable. ASMX services are usually stateless. Ref

· Are the type system represented by XmlSchema and the CLS isomorphic? ;)

· No, there is some impedence mismtach. That’s the reason you ned IXmlSerializable to help the XmlSerializer. XSD is not a type system in the traditional sense. Ref

· Conceptually, what is the difference between early-binding and late-binding? :)

· Early binding means compiler get information of type calling/path execution during compilation of code and in late binding compiler doesn’t get that information but this information determined at runtime/execution time.

· Is using Assembly.Load a static reference or dynamic reference? :)

· Its dynamic load (Reflection)

· When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate? ;)

· Difference is only about binding. LoadFrom is flexible and if it doesn’t get assembly where it was pointing then it can be redirect to another path on the other hand LoadFile points/depends upon strictly to reference/path of the assembly defined, don’t redirect in case of failure.

· What is an Asssembly Qualified Name? Is it a filename? How is it different? :)

· Assembly qualified name contains assembly name, version, token key whereas filename is simple file name physically on file system. Assembly names store as Meta data as is very important by means of defining scope.

· Is this valid? Assembly.Load(”foo.dll”) :)

· Ofcouse NOT :D as its file name not Assembly qualified name which is required.

· How is a strongly-named assembly different from one that isn’t strongly-named? :)

· Strongly named assembly have strong names due to public token key so can be stored in GAC (shared environment) and can be referred by multiple programs whereas non-strongly name can’t be stored in GAC.

· Can DateTimes be null? :)

· Before .net 2.0 it was not possible as datetime/integer… are struct/value types which can’t be null but due to nullable types now its possible.

· What is the JIT? What is NGEN? What are limitations and benefits of each? ;)

· I remember, once I was being interviewed at very big name (company), interviewer asked me about .net IL compilation… I start telling and talked about JIT as well after listening me he said hmmm JIT exist in Java technologies not .net technologies, I said no I read about it and it does but he kept negating me so I got quite and said Ok. Anyhow JIT stands for Just in time compiler it compiles code into native code to execute by processor in three different techniques. It compiles code just before code required to be run which makes execution little slow (depends) so to avoid that we use NGEN which converts IL into native code like JIT but during deployment. It comes with large image which also includes that codes compiled version which is not being calling frequently.

· How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization? ;)

· Object life time divides into three different generations, 1 short term and 2 long terms so manage accordingly. Non deterministic finalization means GC calls finalize method of object not right after object goes out of scope rather when GC got idle time to prioritize it.

· What is the difference between Finalize() and Dispose()? :)

· Finalize called by GC and Dispose called by programmer to free up resources.

· How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization? :)

· Using statement is quite handy and makes code quite efficient as right after end of using statement object created/declared in that statement disposed automatically means dispose method get called in deterministic way to free up memory. IDisposible is interface which classes implements to dispose unmanaged resources in deterministic manner.

· What does this useful command line do? tasklist /m “mscor*” ;)

· It will list down all the processes that have loaded modules which start from mscor… hosting by the .net environment.

· What is the difference between in-proc and out-of-proc? J

· As name implies in proc means loading in the same process memory domain of invoker/host, it is fast technique but less reliable than out proc in case of any fault/exception occurs. Out proc is opposite to in proc definition and as loading out of the host process so is not depending and could be safe in host process failure for some reason.

· What technology enables out-of-proc communication in .NET? ;)

· .net remoting through marshalling

· When you’re running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003? :)

· Aspnet_wp.exe in case of winxp and win2k but w3pw.exe in case of win2k3.

Senior Developers/Architects

· What’s wrong with a line like this? DateTime.Parse(myString); :)

· There is nothing wrong necessarily but could be wrong means no error no exception but some logical error like unexpected result could be produce due to lack of locale/culture info.

· What are PDBs? Where must they be located for debugging to work? :)

· PDB stands for Program database store debugging symbols and meta information for debugging. Normally they are located at bin or debug folder.

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

· Object objLock; bool isLocked = true; if (isLocked) {lock(objLock){if (isLocked) {//bingooooo}}}}

· What is FullTrust? Do GAC’ed assemblies have FullTrust? :)

· FullTrust means newly happily marriage :D and in .net it means Assembly have full access of system resources (which is quite dangerous and in shared hosting domain only medium trust level is allowed). YES GACed assemblies have fulltrust.

· What benefit does your code receive if you decorate it with attributes demanding specific Security permissions? :)

· It let user know what your code/program required to do so and either it’s allowed to do operation or not so it becomes user friendly by means of security permissions.

· What does this do? gacutil /l | find /i “Corillian” :)

· I knew about gacutil only not about any other parameters but I think I can guess so I think gacutil /l means list of assemblies in GAC (as gacutil used to install/uninstall assemblies in gac and I did that operation ONLY) find /I “Corrilian” seems to look for Corillian named assemblies and not sure about /I but I think in other commands it means ignore case hope it means same here too ;)

· What does this do? sn -t foo.dll :)

· SN stands for strong name and used to generate strong names of assemblies but not sure about –t param here but my searching told me its for Token Key.

· What ports must be open for DCOM over a firewall? What is the purpose of Port 135? :(

· DCOM is distributed COM technology which used to remote procedure call and it used port 135 by default. 135 is port of Remote procedure call Service and as DCOM is OO based RPC mechanism so no wonder about it ;) by the way good question can kill any 1J

· Contrast OOP and SOA. What are tenets of each? :)

· OOP tenets are Polymorphism, inheritance, abstraction…. And SOA tenets would be (not much sure) as it based on services so discovering/access, interoperatibility, security, distributeable

· How does the XmlSerializer work? What ACL permissions does a process using it require? :(

· XmlSerializer used read/write interfaces to deserialize/serialize respectively xml based data so it’s understood that it uses reflection.

· Why is catch(Exception) almost always a bad idea? :)

· Catch(exception) is always a time consuming and somehow it means programmer knows/expecting there would/can be some exception so better approach is to use checks as much as programmer can rather catch exception but ofcourse its unavoidable.

· What is the difference between Debug.Write and Trace.Write? When should each be used? :)

· As names implies .write means printing something and debug would be used whilst debugging and Trace is useable at release mode and according to my knowledge during release mode if debug statement is used it would be ignored gracefully so chill.

· What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not? :)

· Debug build contains debug symbols in (pdb) files and debugging related meta information which release build doesn’t that’s why more compact and efficient.

· Does JITting occur per-assembly or per-method? How does this affect the working set? :)

· JITing occue per method as NGEN make image of whole assembly at once. JITing degrade efficiency if method is very highly coupled means dependent upon other methods (call/invoke other methods which were not JIT)

· Contrast the use of an abstract base class against an interface? :)

· Aaaaah typical interview question but thanks there is something typical scott asked :D . abstract class can have implementation of methods at different access levels whereas interface can have only declarations of methods and must be public, abstract class is inheritable. I think interesting and bit difficult contract would be between PURE abstract class and interface. Sounds good?

· What is the difference between a.Equals(b) and a == b? :)

· Equals checks type as well as it compares on heap to objects whereas == doesn’t, it just check value on stack.

· In the context of a comparison, what is object identity versus object equivalence? ;)

· Identity means two references on stack point to same address of heap whereas object equivalence means objects has same value.

· How would one do a deep copy in .NET? :)

· Normally I hate typical interview questions as this but in this (scott) case I am more than happy to hear. Anyhow Implement ICloneable simple.

· What is boxing? :)

· To convert value type into reference type is called boxing.

· Is string a value type or a reference type? :)

· It’s not even again typical interview question but also for heaven sake scott it’s not suppose to be known by some senior/architect level of .net guru. Anyhow string is reference type due to its any length of size.

· 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? :)

· Ofcourse they are not encouraging as out keyword is somehow violating the rule of returning single value which keep function easy to readable and debuggable as we know only there is single point to return value and somehow caller can send any vulnerable value which always should be validate. Anyhow there are many solutions like using array (if return values are of same type or ENUM if feasible or Collection or Class with multiple properties…)

· Can attributes be placed on specific parameters to a method? Why is this useful? ;)

· Yes I have seen that being using in case of .net remoting but didn’t use/need much sooo.

C# Component Developers

· Juxtapose the use of override with new. What is shadowing? ;)

· Overriding means giving implementation of virtual/abstract/overrideable method in derived class and if we use new it means it can’t be access through by any other class ref/object. Shadowing is somehow opposite to overriding as it lets redefine method implementation with signature as well.

· Explain the use of virtual, sealed, override, and abstract. :)

· Through Virtual keyword, we enforce programmer of derive class to override this function. Sealed make sure that class won’t be able to inherit (you may say Such mother who can’t birth a baby :D ) and through abstract class, we are able to define methods as abstract to make them must overrideable by child classes and don’t let anyone to instantiate it.

· Explain the importance and use of each component of this string: Foo.Bar, Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d :)

· Foo.Bar Assembly name, Version defines its version in following pattern (Major, Miner, Build) to track version number of that assembly, Culture specifies culture for locale settings and publickeytoken makes it unique so could be kept and accessed in shared environment.

· Explain the differences between public, protected, private and internal. :)

· Public is shareable so anyone can access no matter out of the class/assembly/assembly. Through Protected you can only access within class or from child classes and through internal you can access within the assembly only.

· What benefit do you get from using a Primary Interop Assembly (PIA)? :(

· —————————–?????????????????

· By what mechanism does NUnit know what methods to test? :)

· Using attributes

· What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;} :)

· Throw also return stack trace which throw e doesn’t

· What is the difference between typeof(foo) and myFoo.GetType()? ;)

· First 1 takes type name and return result at compile time whereas 2nd 1 takes object and return type at runtime using reflection ofcourse.

· Explain what’s happening in the first constructor: public class c{ public c(string a) : this() {;}; public c() {;} } How is this construct useful? :)

· First one calls the base contructor.

· What is this? Can this be used within a static method? :)

· this keyword points to current object and as static methods can’t be invoked through object sooo

ASP.NET (UI) Developers

· Describe how a browser-based Form POST becomes a Server-Side event like Button1_OnClick. :)

· I am not certain but I think when we need to submit some information or manipulate data at server side we use POST method which transmit client side information to server side in Request object and send the information to server and server perform task according to information given by client so in this case Button1_OnClick is transferred to server and it’s handler called the relevant method.

· What is a PostBack? :)

· Postback is way to send client side information to server after loading it.

· What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState? :)

· ViewState stores information so it could be accessible after postback and information could be persisted after any number of postbacks but only within the scope of page. It encoded into Base64 format. It can be encrypted. Controls uses viewstate to store control state and data to be preserved after postback.

· What is the <machinekey> element and what two ASP.NET technologies is it used for? :)

· machinekey defines unique key which could be use by session and cache so if site is cluster based or single sign on based then it’s very useful.

· What three Session State providers are available in ASP.NET 1.1? What are the pros and cons of each? :)

· In-proc, out-proc, sqlserver

· What is Web Gardening? How would using it affect a design? :)

· If server has multiple processors and requests traffic is dividing accordingly that is called web gardening. If server is using external resources (like sql server, web services, logging) then it could be very useful.

· 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? :)

· HTTPApplication object with single key based would be only 1 per worker process so in case of single processor box ONLY 1, in case of dual processor box without webgardening there would be only 1 single worker process so again single object but in case of web gardening two worker process means 2 objects. So need to have machine key otherwise … :D

· Are threads reused in ASP.NET between reqeusts? Does every HttpRequest get its own thread? Should you use Thread Local storage with ASP.NET? :)

· ASP.NET is MTA based so multiple threads are possible but I remember once I tried to call methods through callback based async delegates which makes it run on separate thread so when I tried that I lost httpcontext L in that thread. So each thread gets its own thread and usage is depends upon need.

· Is the [ThreadStatic] attribute useful in ASP.NET? Are there side effects? Good or bad? ;)

· I never used it but I think I got my just above mentioned problem’s solution that we can share httpContext through this attribute in multiple threads ;)

· Give an example of how using an HttpHandler could simplify an existing design that serves Check Images from an .aspx page. :)

· We can simply make httphandler for such specific requirements as .aspx are nto specialized for images based web page which we could make and make things efficient and manipulate response according to our need. If page is based upon images only and needs to show loads of images thumbnail and such features we can make specific httpHandler for such pages to customize response and have more command on request.

· 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? :)

· HTTPModule subscribe to Request life cycle kinds of events like beginRequest,EndRequest,Session,… They are useful to manipulate Request and generate Response according to state and lifecycle. They are separate DLL which are referred by asp.net application and if we change HTTPModule and recompile it we don’t need to recompile our whole application. So they are plugged like plugins ;)

· Describe ways to present an arbitrary endpoint (URL) and route requests to that endpoint to ASP.NET. ;)

· I am sure either I interpreted this question in right way but here is the answer according to my understanding about this question. URL could be define in couple of ways relative path and absolute path and request could be route in multiple ways using Redirect, Transfer, URL Rewrite…

· Explain how cookies work. Give an example of Cookie abuse. :)

· Cookie stored at client side and readable by any user if it’s not encrypted, if you stored some important information about client data at server any other site could read cookies and get that information.

· Explain the importance of HttpRequest.ValidateInput()? :)

· It checks integrity of data in Request object (Form, Querystring, Cookies), you can prevented by XSS types of attacks and validate request data to see so there is no malicious input ;)

· What kind of data is passed via HTTP Headers? :)

· HTTP Header contains information about browser and some of page like browser name, version, page size, mime type, cookies

· Juxtapose the HTTP verbs GET and POST. What is HEAD? J ;)

· Get is used when we don’t need to do manipulation at server side and have nothing really secret information to send in querystring as it send information through querystring which is limited so input can’t be very long like article :D but it’s pretty fast as compare to POST as post sends information in hidden fields and preferred in case of manipulation at server side. Using Head we just send page header information not the actual contents/body.

· Name and describe at least a half dozen HTTP Status Codes and what they express to the requesting client. :)

· Very famous I just remember like 404 error page (page not found) 200 for OK, 500 Server not found

· How does if-not-modified-since work? How can it be programmatically implemented with ASP.NET?
Explain <@OutputCache%> and the usage of VaryByParam, VaryByHeader.
:)

· No idea about the if-not-modified thingy but can tell about OutputCache which is directive used for caching contents and tells server that Header information could be change by VaryByHeader Param and Parameter could be change in query string using VaryByParam so it get different versions for different header (like browsers) and parameters respectively.

· How does VaryByCustom work? :)

· Can output different pages from cache on the basis of change of state of any control or value or object within that page

· 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)? :)

· <@OutputCache VaryByParam=”q” %>

Please dont’ forget to correct me if I am wrong and please give references as well with your answers.

Thanks

Use true Ajax from scratch

Make Script based web service which could be called by JavaScript

 

I remember the days when I need to call web service from JavaScript using some HTML component called webservice.htc. It was a pain to consume web service using that component as compare to current solution provided by Asp.net Ajax team of Microsoft. I must say, Hats off to Microsoft for making life easier of the developers of their technologies. Following are few factors for using “calling web service from JavaScript”.

 

When you need to:

 

  • Call web server and perform some operation on server like updating database or some File I/O operations or have to queue the requests and have less to do on client side like just need to show Operation completed or data based updated.
  • Send request to web server asynchronously and don’t want to put user on wait for completion of request
  • Perform operation on server side more efficiently as you wont follow page life cycle

 

When you don’t need to:

 

  • Initiate Page object and/or need to follow page life cycle
  • Post back page and Render page automatically
  • Send request to web server synchronously and put user on wait of completion of processing
  • Submit form
  • Use cache, session or need to access any asp.net intrinsic object

 

Aforementioned points tells simply, when to call web service from JavaScript and when not.

For more details and better understanding please visit following link http://worldofasp.net/tut/ajax_webservice/Ajax_enabled_web_service_237.aspx

Thanks

 ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

XMLHTTPRequest

 

Normally, when you have to do some operation at server side, say some database oriented operation like any of well known CRUD (create, retrieve, update and delete) operations. You will submit whole form/page to server and get a whole new page from server to re paint on your browser. In very few, situations that are ok but mostly its not required at all.

 

Suppose, you have header image, left navigation bar, footer links like (contact us, about us, privacy policy…) and in middle of page some textboxes and one submit button.

 

You fill those textboxes and want to save given information in database and then clear the textboxes. Sounds good!

 

But what happen, when you click on submit button, all the contents on the web page will go to the server like header, footer, navigation bar and your textboxes. Purpose of submit button was to save information given in database then why header, navigation bar and footer being sending to server. I guess, it doesn’t make sense until they are needed to update.

 

So, if you want to send your specific controls data only to server and want to update those controls at browser side, then here comes “XMLHTTPRequest” object.

 

XMLHTTPRequest is JavaScript object which used to send request to server and receive response from server. Through XMLHTTPRequest, you can communicate with server synchronously and asynchronously as well. It depends upon your need of communication. If your next step(s) relying on server response then you need synchronous communication pattern but if don’t want to keep user on wait, don’t want to freeze User Interface (UI) at user side and can proceed without having result on next line of call then you can use asynchronous communication pattern.

 

For more details and better understanding please visit following link http://worldofasp.net/tut/XMLHTTPRequest/XMLHTTPRequest_236.aspx

Thanks

 

Kindly feedback :)

 

Design patterns

 

Design patterns are considered to be best solution for application design based problems. When we design application or have to implement any task. We have multiple ways to perform that task but we should try to perform that task in best way. There are many tasks/problems, we face frequently whilst development or designing application so there are best solutions for such common problems given by gurus. Design patterns help a lot to minimize frequent and complex problems.

 

Following are few examples (problems), which could help you in understanding what kind of problems are resolved by design patterns.

 

  • You want to undo work done by user one or multiple times
  • Suppose you don’t need to let create multiple objects of same class at a time in any case.
  • You don’t know exact class type of which you would need to create object whilst programming/coding.
  • You need to change behavior of object without changing of class implementation.
  • You might need to have different behavior of same object on change of state of object.

 

Aforementioned points are just to give you sense of types of problems/tasks, you could have whilst application development and designing.

for complete article on design patterns please click on following link where i have uploaded my article http://www.worldofasp.net/tut/designpattern/Design_Patterns_210.aspx

My Sharepoint Blogs

Hi guys, recently i started to write on sharepoint at following platform

 

http://sharepointboy.wordpress.com

Asp.net HTTP Module & Delegates

 Delegate

Being a programmer, it’s almost daily routine to write such methods which take plenty of processor cycles/time to perform some action. For example some database operation/transactions, while using web services or Remote Procedure Calling (RPC), File I/O operations, etc.

To call such functions or methods which take plenty of time, user needs to wait for process to complete and some time in exceptional cases application hangs up if process couldn’t get complete for some reason. But in both cases user gets annoy and User Interface (UI) gets freeze until process completed if you have to call them synchronously.

In synchronous way of communication, caller process/thread needs to wait until called process/thread got complete but in case of asynchronous caller just need to send request to perform operation and get back means. It doesn’t need to wait for called process/thread completion.

Thanks to .Net team as they provide managed code Type-Safe mechanism to point any method or function and introduced Delegate. Delegates are like Function Pointer in C/C++ but Type-Safe, flexible by means of inheritance and powerful by means of referencing multiple methods as well as powerful by means of asynchronicity and supporting callback and calling them.

To read complete article please click here or paste the following link into your browser’s address bar

http://www.worldofasp.net/tut/prjDelegate/Delegates_173.aspx

Asp.net HTTP Module

HTTP Modules use to intercept HTTP requests for modifying or utilize HTTP based requests according to needs like authentication, authorization, session/state management, logging, modifying Response, URL rewriting, Error handling, Caching….

HTTP Modules are activated/called/invoked before and after HTTP Handler execution.

HTTP Modules are integral part of ASP.NET framework now and heavily being used as it cater grips upon request and let developers to generate response in a customized way, according to user requirement. Web development is all about playing with request from client to server and response from server to client.

When any request goes to web server, request passes through different phases and then at last response gets generate for client.

HTTP Modules are .Net based components/Plugins and programmed by implementing System.Web.IHTTPModule interface of .Net.

To read complete article please click here or paste the following link into your browser’s address bar

http://www.worldofasp.net/tut/prjaspxmod/ASPNET_HTTP_Modules_168.aspx.

Thanks

Improve web site performance

my 1 more article has published, i.e, about web site performance improvements. i have mentioned several points which should be considered to have good website by means of performance :)

please click here to get that article

kindly give your feedback there at the end of the page. thanks :)

direct link: http://dotnetslackers.com/articles/aspnet/ImproveWebApplicationPerformance.aspx

scott guthrie...... in punjabi and urdu :D

 I believe there would be hardly anyone we can find out who is regular user of www.asp.net or its other community site and doesn't know

Mr. Scott Guthrie (Corporate Vice President in the Microsoft Developer Division).
 
he run the development teams that build the following products/technologies:

  • CLR and the core .NET Base Class Libraries
  • ASP.NET 
  • Silverlight
  • WPF
  • IIS 7.0
  • Visual Studio Tools for ASP.NET, WPF and Silverlight

Actually people who know Scott Guthrie and know Urdu OR Punjabi surely smile to know if they could get scott's blogs in these languages :D

Yesterday Mr. Joe Stranger aka Microsoft's Opinionated Misfit Geek gave me opportunity to write for the community who wanted to read technical articles of Scott Guthrie in URDU and PUNJABI

 I 'll try my best to start writing as soon as possible.

Blogs links are:

http://weblogs.asp.net/scottguurdu for URDU

http://weblogs.asp.net/scottgupunjabi for Punjabi (my fav lang.)

 

 


 

 

 

 

Synchornous communication of client (browser) and server (IIS)

To make communication between client and server, we use XMLHTTPRequest object, same object used in AJAX, CALLBACK techniques and where ever we have to send request to server from client (browser).

XMLHTTPRequest communicate with server asynchronously, means invoker/caller doesn't wait for completion of completion of that function/subroutine/method, which it called so proceed but what if we have DEPENDENCY on result of the method/function which we invoked through XMLHTTPRequest object and suppose to proceed only when we get result and on the base of that result, we have to code further like:

Suppose i need to make functionality of SIGNIN  means Authenticate User. User enter his/her username and password and press Sign In and on SignIn we call javascript function which call server side function through XMLHTTPRequest object and that server side function check either user exist in DB or not if Yes then return True if no then return False and return that result back to client side and if True then redirect to WelcomePage if False then take to Error Page. Here you can see until we don't get result (either True or False).

so the solution is following code/snippet which you need to have along your code :)

<script type="text/javascript">
    var __xmlHttpRequest = window.XMLHttpRequest;
    window.XMLHttpRequest = XMLHttpRequest = function() {
        var _xmlHttp = null;
        if (!__xmlHttpRequest) {
            try {
                _xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(ex) {}
        }
        else {
            _xmlHttp = new __xmlHttpRequest();
        }
       
        if (!_xmlHttp) return null;
        
        this.abort = function() {return _xmlHttp.abort();}
        this.getAllResponseHeaders = function() {return _xmlHttp.getAllResponseHeaders();}
        this.getResponseHeader = function(header) {return _xmlHttp.getResponseHeader(header);}
        this.open = function(method, url, async, user, password) {
            return _xmlHttp.open(method, url, false, user, password);
        }
        this.send = function(body) {
            _xmlHttp.send(body);
            this.readyState = _xmlHttp.readyState;
            this.responseBody = _xmlHttp.responseBody;
            this.responseStream = _xmlHttp.responseStream;
            this.responseText = _xmlHttp.responseText;
            this.onreadystatechange();
        }
        this.setRequestHeader = function(name, value) {return _xmlHttp.setRequestHeader(name, value);}
    }
</script>

 

It will work either you are using XMLHTTPRequest or AJAX or even ASP.NET CALLBACK butttttttttt in case of ASP.NET CALLBACK you can avoid that snippet,  when you register/embed client side method signature in "GetCallbackEventReference"

String cbReference = scriptMgr.GetCallbackEventReference(this"arg", "ReceiveServerData", "", TRUE|FALSE);
TRUE for Async and FALSE for Sync communication. 
ref: http://aspalliance.com/1573_Working_with_Callback_and_Control_Rendering.all listing 3

 

'__pendingCallbacks[...].async' is null or not an object: callback async[i]...FIX :)

In my prior both articles about CALLBACK, which considered as Article of the Day @ www.asp.net recently might have problem:

Here i would like to talk about async indexer problem and of course solution as well :)

PROBLEM 1: '__pendingCallbacks[...].async' is null or not an object

EXPLANATION: if you debug then error message says, there is some problem with indexer [i] of async callback, hmmm you might not get that error message after using callback but developing other modules/part of the website you might get such error 1 day as i did :D, so if you are brainy enough, you must think something new i did which cause this ripple effect and go ahead to look for that what exactly i did and if you keep thinking with reading that error message carefully, you will get to know: somewhere you are using "i" variable and that variable is not being getting out of scope so mixing with "i" variable of callback async[i] and making problem.

Solutions:
1) solution is simple: follow standards and never make any variable name of single character rather use: anyhow either change your variable name from "i" to intCounter or anything u want

2) take care of your variable scope, so it wont mixup with variable "i"

3) use the following code/snippet: if you want to keep using your "i" variable in your code (may be you have used that at many places and don't wanna mess up with your existing code):

<script type="text/javascript">
function WebForm_CallbackComplete

_SyncFixed() {
  // SyncFix: the original version uses "i" as global thereby resulting in javascript errors when "i" is used elsewhere in consuming pages
  for (var i = 0; i < __pendingCallbacks.length; i++) {
   callbackObject = __pendingCallbacks[ i ];
  if (callbackObject && callbackObject.xmlRequest && (callbackObject.xmlRequest.readyState == 4)) {
   // the callback should be executed after releasing all resources
   // associated with this request.
   // Originally if the callback gets executed here and the callback
   // routine makes another ASP.NET ajax request then the pending slots and
   // pending callbacks array gets messed up since the slot is not released
   // before the next ASP.NET request comes.
   // FIX: This statement has been moved below
   // WebForm_ExecuteCallback(callbackObject);
   if (!__pendingCallbacks[ i ].async) {
     __synchronousCallBackIndex = -1;
   }
   __pendingCallbacks[i] = null;

   var callbackFrameID = "__CALLBACKFRAME" + i;
   var xmlRequestFrame = document.getElementById(callbackFrameID);
   if (xmlRequestFrame) {
     xmlRequestFrame.parentNode.removeChild(xmlRequestFrame);
   }

   // SyncFix: the following statement has been moved down from above;
   WebForm_ExecuteCallback(callbackObject);
  }
 }
}
window.onload = function Onloaad(){
if (typeof (WebForm_CallbackComplete) == "function") {
  // set the original version with fixed version
  WebForm_CallbackComplete = WebForm_CallbackComplete_SyncFixed;
}
}
</script>

 

Callback & Controls Rendering (Manually Partial Page Rendering)

Callback & Controls Rendering (Manually Partial Page Rendering) 

In my previous article, I wrote about Callback and JSON based Javascript serialization which you can find here. 1. Why

Should I read this article       As Callback doesn’t cause postback and page rendering neither full nor even partial. We can communicate with server (IIS) and our server side code runs there successfully and could rebind our controls like Dropdownlist, Gridview, Listview, Datalist, Repeater or any server side control to which you assign data but problem is when page wont render, its controls wont render and if controls wont render then changes wont reflect and when changes wont reflect there wont be anything at front end to show on webpage. Article is mainly about Callback and Rendering Controls but through this tutorial you can also learn many other things like brief introduction of Postback, Rendering, Create server side controls dynamically, Create Datatable dynamically in memory to bind with create server side controls means binding, get server side control at client side and set their properties and registering client side event of server side control from/through server side code. First of all, I would like to brief some terms which I believe every web developer should aware of.  

2.Postback          Postback is a mechanism of communication between client-side (browser) and server-side (IIS). Through postback all contents of page/form(s) sent to the server from client for processing and after following page life cycle all server side contents get render into client side code and client (browser) display that contents. Callback is another way of communication between server and client. Callback doesn’t follow the page life cycle which followed by in standard postback and doesn’t even cause Rendering. 

3. Rendering       Rendering is process of converting server side code/contents into client side code/content so client (browser) can understand that code and could display the output. Browser can understand or you may say decode code of client side languages and scripts like HTML, DHTML, XHTML, Javascript, Vbscript and a long list. If rendering wont happen then changes won’t reflect which happens on server at client side. Ajax leverages partial postback automatically whereas callback doesn’t cause, so programmer needs to perform that task manually. ASP.NET team has created RenderControl method with its each control so by using that control we can render our control very easily. If you have read my previous article you may skip following section from 4 and 5.  

4. CALLBACK        CALLBACK is lightweight process, It uses well known xmlhttp object internally to call server side method, it doesn’t cause page postback so doesn’t cause page rendering so we to show output at client side we need to make output html ourselves and render controls manually. 

5. ICALLBACKEVENTHANDLER         ICALLBACK implemented in asp.net by using ICALLBACKEVENTHANDLER interface has two methods, one of them used to be call from javascript (client side code) and other one return result asynchronously back to javascript function. We just need to perform some action through server side code at server side and needs to return results but results could are in instance or object of any class which could be not easy for javascript code to handle easily so here we prefer JSON which stands for Javascript Object Notation. 

7. Real Time Scenario with implementation     Suppose we have categories, subcategories, products data and needs to populate categories and subcategories which depend upon categories data would be populate in two different dropdownlists. For products data which is multicolumn and we need to show that data in tabular format so I would prefer Gridview control.  So the situation would be load/populate categories on Page_Load and load/populate subcategories on the basis of selected category using callback and finally load products into Gridview on the basis of selected subcategory.  Before starting coding, I would like to write Pseudo code for better understanding.  

8. Pseudo Code

  1. Create Server side controls e.g. Dropdownlists and Gridview
  2. Load Categories on Page load
  3. Implement ICallbackEventHandler interface
  4. Create subcategories data in server memory to bind to Subcategory dropdownlist.
  5. Render control (subcategory dropdownlist) and show output.
  6. Create products data in server memory to bind to Products gridview.
  7. Render Control (products gridview) and return rendered contents to client side to show
  8. Set innerHTML of each control by rendered contents

source code with comments has attached.

 12. Conclusion: Callback is lightweight technique used to call server side methods asynchronously from javascript without any postback and reloading/rendering of unnecessary parts of page and unnecessary code  So we can use that when we need to perform any operation at backend means at server like update records in database or like that. You don’t need to send all your contents of page in request and make that object heavyweight which could cause slow performance.  

 

More Posts Next page »