Er. alokpandey's Blog

What Great .NET Developers Ought To Know

Posted in ASP.NET (C# & VB), C#, VB by Alok Kumar Pandey on February 23, 2011

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

Top Best Free 42 CMS

Posted in ASP.NET (C# & VB), HTML and XHTML, VB, WCF by Alok Kumar Pandey on February 18, 2011

Top Best Free 42 CMS

At BLORGE we’re great fans of open source, and in particular, open source content management systems (CMS).

While we all know about content management systems such as SageFrame, DNN, Joomla, wordpress and Drupal, you may be surprised to learn that there literally dozens and dozens of other content management systems out there, many of which  do have their special niche.

While some CMSs are great for putting up a dynamic website in a snap, others are too difficult to implement and use. We’ve compiled a list of what we consider to be the top open source content management systems available to help you choose the most appropriate tool for your needs.

  1. SageFrameSageFrame is an open source web development framework developed on the top ASP.NET 3.5 with service pack 1 (sp1) technology, provided by SageFrame. The SageFrame is a Leading web content management framework for Microsoft asp.net.

 

The SageFrame is not only a framework with a set of classes but it also creates an abstraction layer in which the programmer is concerned only with the code. The programmer needs not to worry about HOW the result will be presented, but HOW to produce the information.

Users can now relax about various elements such as database, security (with multiple roles), file system, etc because all the elements are dealt with within the framework. Native support for internationalization, multiple sites, templates (based on CSS), integrated security and login with single sign-in, possibility to modify the templates of SageFrame and customize it according to your needs.

 

  1. DNN – DotNetNuke is the leading Web Content Management Platform (or CMS) for Microsoft ASP.NET
  2. Joomla – a very  popular open-source CMS that is found at the heart of many well known websites (the United Nations is just one example)
  3. Drupal – another very popular, powerful and flexible content management system
  4. WordPress – although geared for publishing blog, WordPress has proven that it can be a powerful CMS too, as you can see with my publisher’scustom publishing web site
  5. Movable Type – like WordPress, Movable Type is also a weblog creation tool which is also used for building non-blog dynamic websites
  6. b2Evolution – a full-featured weblog creation tool/CMS that supports multiple categories, sub-categories, multiple weblogs, skins, statistics, comments, anti-spam filters, photo management and multiple blogs
  7. Xoops – extensible, OO (Object Oriented), easy to use dynamic web content management system written in PHP
  8. Alfresco – powerful enterprise content management system featuring web and document management
  9. DotCMS – J2EE/Java Web Content Management System (wCMS) which includes an AJAX calendar and events management, e-communications tools, personalization/CRM tools, eCommerce hooks and more
  10. e107 – PHP-based content management system designed for the quick creation of websites or community portals
  11. Exponent– a website CMS that allows site owners to easily create and manage dynamic websites without necessarily directly coding web pages, or managing site navigation.
  12. ImpressCMS – a community developed CMS for easily building and maintaining a dynamic web site offering easy to use, secure and flexible system which is said to be an ideal tool for business to community users, from large enterprises to people who want a simple, easy to use blogging tool
  13. Liferay – offers an enterprise portal solution using Java and Web 2.0 technologies
  14. KnowledgeTree Document Management System – document management software designed for business people for team collaboration, storing documents with ease
  15. Pivot – a web-based tool for maintaining dynamic websites, weblogs or online journals
  16. Magnolia – widely used by most Government websites, it offers an easy-to-use editing interface that allows authors to lay out content exactly as it would appear to a website visitor. Contains “best-of-breed” Java technology
  17. MediaWiki – is a free software wiki package originally written for Wikipedia, but that is now used by several other projects of the non-profit Wikimedia Foundation and by many other wikis
  18. MiaCMS – is a fork of the Mambo CMS and offers simple installation, graphical content editors, RSS content syndication, powerful/extensible 3rd party extension system
  19. MODx – described as a “PHP application framework that helps you take control of your online content”; it allows developers and advanced users to give as much control as desired to whomever they desire for day-to-day website content maintenance chores
  20. Nucleus CMS – extensible and powerful CMS based on PHP/SQL blogging tool that features multiple weblog capabilities, and RSS syndication
  21. Nuxeo CPS – is said to be “the most complete open source platform” for building Enterprise Content Management (ECM) applications, and is described as an user-friendly accessible application ready to for enterprise-grade content management with many collaboration features.
  22. OneCMS – most commonly used by gaming websites, it can be used by webmasters to manage their website, allowing the user to upload files, add content and various other features
  23. OpenACS – an open architecture community system toolkit for building scalable, community-oriented web applications.
  24. PhpCMS–  a CMS characterized by simple system requirements, high performance and flexibility, which is said to be suitable for both small, private websites, as well as complex high-traffic websites
  25. Plone– easy to use, set-up and run CMS, well suited for project groups, online communities, small business websites
  26. TextPattern – a flexible and easy-to-use feature rich CMS with a built-in search engine
  27. PhpNuke – a CMS and portal solution that features web-based administration, surveys, customisable blocks, modules and themes with multilingual support.
  28. Zope – application server for building content management systems, intranets, portals, and custom applications, written in Python
  29. Plone – suited for building an intranet, web site or community site, Plone is a Content Management, Document Management and Knowledge Management system
  30. Jahia – is an enterprise web content and portal management system that includes a web publishing system, a content management server, and a portal server
  31. Website BAKER – a PHP-based CMS developed with one goal in mind, to enable users to create websites easily
  32. ezPublish – is both an open source content management system and content management framework, which offers an enterprise content management solution, community portal and social networking platform
  33. jLibrary – a CMS engine geared for both personal and enterprise use and offers a very flexible system that can almost be used for any information management purpose
  34. Pligg – ever wanted to create your own Digg clone? Well Pligg is exactly what you’re looking for. It’s a content management system based on PHP/MySQL with features such as multiple authors, article rating, private messaging and much more
  35. Mambo – full-featured CMS that can be used  for small or large websites; described as a “powerful enough for the most demanding Internet or intranet site, simple enough for everyone to use!”
  36. Jaws – a Framework and Content Management System for building dynamic web sites that is user-friendly and easy-to-use
  37. Geeklog – PHP/MySQL based application for managing dynamic web content, offering out-of-the-box blog engine, and CMS with support for comments, trackbacks, multiple syndication formats, and spam protection
  38. CMS Container – enables an organization to efficiently maintain a large content-driven website using single CMS. This CMS features the ability to create a staging and live environment, scheduling of content for publication, and automatic removal of content on expiry
  39. SiteFrame – a lightweight, web-based CMS designed for the rapid deployment of community-based websites. A group of users can share stories and photographs, create blogs, send email to one another, and participate in group activities.
  40. Xaraya – offers a “cutting edge open source framework” written in PHP, on which developers can create sophisticated web applications featuring modular design, stable and extensive API and fully internationalized platform
  41. PHP Fusion – PHP-based light-weight open-source content management system that includes a simple, comprehensive administration system.

“Programming Quotes”

Posted in ASP.NET (C# & VB), C#, HTML and XHTML, J-Query, JavaScript, LINQ, PLINQ, SEO, SilverLight, VB, WCF by Alok Kumar Pandey on February 15, 2011
  1. If debugging is the process of removing software bugs, then programming must be the process of putting them in. –  Edsger Dijkstra
  2.  

  3. The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.  – Tom Cargill
  4.  

  5. “There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies.”-  C.A.R. Hoare
  6.  

  7. Measuring programming progress by lines of code is like measuring aircraft building progress by weight. – Bill Gates
  8.  

  9. “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.” – Martin Golding
  10.  

  11. “The trouble with programmers is that you can never tell what a programmer is doing until it’s too late.” – Seymour Cray
  12.  

  13. Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. – Rick Cook
  14.  

  15. “Most of you are familiar with the virtues of a programmer. There are three, of course: laziness, impatience, and hubris.” – Larry Wall
  16.  

  17. “Sometimes it pays to stay in bed on Monday, rather than spending the rest of the week debugging Monday’s code.” – Christopher Thompson
  18.  

  19. Walking on water and developing software from a specification are easy if both are frozen. –Edward V Berard

 

How CRUD Is Your Design?

Posted in ASP.NET (C# & VB), C#, HTML and XHTML, J-Query, JavaScript, LINQ, PLINQ, SEO, SilverLight, VB, WCF by Alok Kumar Pandey on February 9, 2011

If you’re a software developer or know one well, the acronym CRUD — Create, Read, Update and Delete — is burned into your vocabulary. These are some of the foundational elements of good software development, and each provides ways to keep your audience engaged.

When you take any one of these elements away from your users, there’s a good chance you’ll diminish the value of their experience. Here’s why.

Create

When your audience isn’t allowed or doesn’t know how to contribute, they become passive bystanders. Your website or application no longer provides an interaction or dialogue and it probably won’t lead to a meaningful user experience.

The more you treat your audience as equals, the better. If you’re a news community like Newsvine, invite your users to create news. If you’re a information community like Wikipedia, invite your audience to create information. If you sell products like Amazon, make ratings and reviews an important part of the interface.

Read

Confidence erodes when people can’t see data they’ve added to a website or application. They scratch their heads, wondering: Did it work? Did I do it right?

When uncertainty creeps in, people tend to blame themselves or the tool they’re using. Both scenarios are problematic, so show users where their data goes and how they can get back to it in the future.

Update

“There are just some things you can’t take back.” This philosophy applies in the real world, but it should be avoided in a website or application.

People get nervous when they think an error they’ve made will become a permanent part of the system. So be liberal with your editing tools, and don’t hide them behind drop-downs, roll-overs or tool-tips.

Delete

People don’t like screwing up, especially in public. The ability to remove data will bring a serious dose of confidence to anyone creating content within a system. If you show them they can’t make a mistake, they’ll be much more likely to participate and give even more data.

CRUD As A Measure Of Control

There are scenarios where CRUD isn’t relevant: activity streams, automated recommendations, etc. These types of content can be interesting, exciting and even addictive, but be careful not to let them take over your website or application. Once your audience’s threshold of perceived control is lost, they’ll loose interest and move on.

So… How do you keep your audience engaged? How do you encourage them to participate? Remember, the amount of data that can be created, read, updated or deleted on your website is directly related to how in-control your audience will feel.

Leave a comment below to discuss how CRUD can make our designs more effective.

 

10 ways to show you’re a programming rockstar

Posted in ASP.NET (C# & VB), C#, HTML and XHTML, J-Query, JavaScript, LINQ, PLINQ, SEO, SilverLight, Uncategorized, VB, WCF by Alok Kumar Pandey on January 27, 2011

It seems nowadays that programmers are a dime a dozen, but how do you pick the best programmers from the rest of the crowd.

It’s not just about coding (although that is a big factor). It’s about building your skill set over the years and nurturing them so you can stand out from the programming “collective.”

What characteristics makes them stand out? Are they easy to get along with? How long have they been programming? Are they teaching you things you never knew were possible? Here’s how to find out if you are a programming rock stars!

  1. Master your language and tools. Whether it’s Visual Studio, Eclipse, or even Aptana, your programming tools should be second nature to you when developing that next web application. Just like a plumber or carpenter, if you don’t have the proper tools, you won’t get the job done right.
  2. Enhance your tools and environment. With that said, even though you’ve mastered your tools, always strive to find ways to enhance your environment. This may include plug-ins to Visual Studio or Eclipse or a code generation tool that works along side your environment. If you’re not looking for better ways to enhance your productivity, you may be working yourself into an early grave.
  3. Research new technologies. While your primary language may do everything you need, make time to research your craft and experiment with new frameworks that wrap around your existing technologies. For example, while programming in web forms with C#, I heard about a new framework from Microsoft called MVC. Since I’ve started working with MVC, I’ve been programming in MVC for more than 2 years now and I haven’t looked back or regretted my decision since.
  4. Leverage your existing code you wrote. Programmers who write code and then immediately disregard it are missing out on the most exceptional tip on this list: start building your library of routines and techniques. If you are in a corporate environment, yes, you will have a corporate library to pull from for your projects. If you are an individual programmer, yes, you will have your own collection of routines or libraries that you can use in your “outside” projects. As the object-oriented saying goes, the routines are reusable.
  5. Automate like crazy. If you’ve been around the programming block for a while, you know that there are always quicker ways to accomplish certain tasks. It’s now getting to the point in this industry where if someone asks you for a web site, you can build one relatively quick. Then they start asking for features. It’s the features part that makes the difference and slows you down.
  6. Perform proper analysis. New developers always shoot first (start coding) and ask questions later. Take the time to analyze the project and ask as many questions as you can. The more questions you ask upfront, the better your ability to complete a more thorough and clear design of your application.
  7. Perform Unit Testing. Along with preceding your coding with proper analysis, always finish your coding by performing unit tests. This not only tests the quality of your code but will also let you know when your system fails on regression testing. Unit Testing should be the “checks and balances” of your programming.
  8. Extend your reach. Most developers keep to their code and that’s all they do. Break out of your comfort zone and read up on usability studies, how to document your code better, and/or using better design techniques. Expanding your skills into other areas will do three things: 1. Make you more visible to other people; 2. Make you more valuable to others because of your thirst for knowledge; and 3. Provide you with more opportunities than just programming.
  9. Communicate effectively. This is in regards to project management, coding, documentation, and impromptu meetings. If you can’t explain an extremely awesome cool coding technique to your peers or communicate why a particular feature shouldn’t be in the project to a project manager because of a time constraint, you may need to work on your verbal skills instead of your coding skills.
  10. Make time to assist others. You will seem as a definite team player by taking the time to help a fellow programmer in need. Help them understand a new concept or technique that is unclear to them and they will be grateful for the help and see you as a definite resource and go to guy.

As you can see, there are a lot of factors to take into account when deciding who is a programming rock star and how they will be perceived by other team members or by clients.

Come to think of it, you could even use some of these factors for general interview questions.

Did I miss any factors? What skills or characteristics do you think makes a programming rock star?

 

Consuming Membership and Profile Services via ASP.NET AJAX

Posted in ASP.NET (C# & VB), C#, VB, WCF by Alok Kumar Pandey on January 27, 2011

ASP.NET 2.0 introduced various application services—such as Membership, Roles, and Profiles—that eliminate a lot of coding that was required to provide the same functionality. However, these services are part of ASP.NET’s server-side framework, which could pose a challenge when you use ASP.NET AJAX to consume the services from client-side JavaScript code. Fortunately, ASP.NET AJAX provides an out-of-the-box solution to this problem. This article explains how to use this solution in C# with Visual Studio.

Sample Scenario

Suppose you are developing a new web site and want to implement forms authentication. The web site will have a user registration page, a login page, and one or more pages that you must secure. The user registration and login pages use ASP.NET AJAX for an enhanced user experience. Also, the site must capture details such as birth date and address at the time of registration. This information is to be stored in the Profile of the user.

To develop a web site that fulfills all the above requirements, begin by creating a new ASP.NET AJAX-enabled web site with C# (see Figure 1).

Figure 1. Creating a New ASP.NET AJAX-enabled Web Site

Configuring the Web Site

Before you begin coding, configure the web site for forms authentication as well as Membership and Profile services. Open a web.config file in your Visual Studio IDE and add the following markup inside the connectionStrings section:

<connectionStrings>
   <add name="connstr"
        connectionString="data source=.\sqlexpress;
        initial catalog=northwind;
        integrated security=true"
        providerName="System.Data.SqlClient"/>
</connectionStrings>

You specified a database connection string named connstr that points to a Northwind database. Make sure to change the connection string to match your development environment. I assume that your database is configured for application services using the aspnet_regsql.exe tool. You will use this connection string while configuring membership and profile providers

Now, add the following markup inside the system.web section:

<system.web>
<authentication mode="Forms">
   <forms loginUrl="Login.aspx"></forms>
</authentication>
<authorization>
   <deny users="?"/>
</authorization>
<membership defaultProvider="p1">
   <providers>
      <add name="p1"
           connectionStringName="connstr"
           type="System.Web.Security.SqlMembershipProvider"
           requiresQuestionAndAnswer="false"/>
   </providers>
</membership>
<profile defaultProvider="p2">
   <providers>
      <add name="p2"
           connectionStringName="connstr"
           type="System.Web.Profile.SqlProfileProvider"/>
   </providers>
   <properties>
      <add name="FullName"/>
      <add name="DOB" type="System.DateTime"/>
      <group name="Address">
      <add name="Street"/>
      <add name="Country"/>
      <add name="PostalCode"/>
      </group>
   </properties>
</profile>

 

Review the above markup carefully, and you’ll notice the following:

  • The authentication section sets the authentication mode to Forms. The forms tag sets the URL of the login page by using the loginUrl attribute.
  • The authorization section disables anonymous users by setting the users attribute of the deny tag to “?”.
  • The membership section configures a membership provider named p1. (You can change this any name you choose.)
  • The connectionStringName attribute specifies the database that will be used for storing membership information.
  • The type attribute indicates the class that will act as the membership provider. You use the built-in SQL Membership provider called SqlMembershipProvider.
  • The requiresQuestionAndAnswer attribute indicates that you do not intend to accept a secret question and answer from the end user at the time of registration.
  • The profile section configures a profile provider named p2 and various profile properties. The significance of the connectionStringname and type attributes is same as for the membership section. Note, however, that this time the type is a SqlProfileProvider class. The properties section defines profile properties and groups.
  • You defined two simple properties called FullName and DOB and a property group called Address. The Address group further contains three properties: street, country, and postalcode. The DOB property is of type DateTime; therefore, its type attribute is set to System.DateTime.

Now that you have configured your web site for using forms authentication and membership services, it’s time to expose Membership and Profile services to the client-side AJAX code. The web.config file will have a pre-defined section called webServices. By default, all its content is commented. You need to un-comment and modify it so that it looks as shown below:

<webServices>
   <authenticationService enabled="true"
   requireSSL="false"/>
   <profileService enabled="true"
   readAccessProperties="FullName,DOB,Address.Street,Address.Country,
                         Address.PostalCode"
   writeAccessProperties="FullName,DOB,Address.Street,Address.Country,
                          Address.PostalCode"/>
</webServices>

The authenticationService tag is used to expose forms authentication and membership services to AJAX code. The enabled attribute governs whether AJAX code can avail membership services. The requireSSL attribute indicates whether the authentication is happening over SSL. Similarly, the Profile service is exposed to AJAX code by using the profileService tag. The readAccessProperties and writeAccessProperties attributes of the profileService tag specify the profile properties that are readable and writable, respectively. Notice how the grouped properties are specified using the dot (.) notion. If you do not include a specific profile property in these attributes, it will not be accessible to the client code.

Applying forms authentication ensures that all the forms of the web site except the login page are secured. However, you want your registration page to be unsecured because new users will need to access it. Do this by adding a location section in the web.config file as shown below:

<location path="register.aspx">
   <system.web>
      <authorization>
         <allow users="*"/>
      </authorization>
   </system.web>
</location>

The path attribute of the location tag specifies a virtual path of a file or folder that is to be configured. It then allows access to all the users using the authorization section and allow tag.

This completes the web site configuration. Now, you will move on to develop the required web forms.

User Registration

First of all, you will create the user registration page. Add a new web form named Registration.aspx. Drag and drop a ScriptManager control from the toolbox (see Figure 2).

Figure 2. Drag and Drop a ScriptManager Control

Also, drag and drop an UpdatePanel and UpdateProgress control on the web form. The UpdatePanel control represents a part of the total web form that can be refreshed without causing a post back of the entire form. The UpdateProgress control is used to display a progress message while the UpdatePanel is being refreshed.

Drag and drop a Label control inside the UpdateProgress control and set its Text property to “Please wait…”. Also, set its AssociatedUpdatePanelID property to the ID of the UpdatePanel control. The AssociatedUpdatePanelID property links the UpdateProgress with an UpdatePanel.

Add a table into the UpdatePanel and design it as shown in Figure 3

Figure 3. Design for Table in the UpdatePanel

The first column of the table contains Label controls that act as prompts for the textboxes. The second column of the table contains TextBox controls. Each TextBox control is validated by using a RequiredFieldValidator control. The TextMode property of the password and confirm password textboxes is set to Password. Similarly, the TextMode property of the street address textbox is set to MultiLine.

There is a Button called “Check Availability” that the end user can use to check the availability of a user ID. The “Check Availability” button will make an AJAX call to the web form to decide whether the specified user ID is available for registration. Set the OnClientClick property of the “Check Availability” button to “return CheckAvailability();” (CheckAvailability() is a client-side JavaScript function that you will write later). This function will call a web method to decide whether the user ID is available for registration. Finally, the Register button will create the user in the system with the help of the Membership features. The Label at the bottom is used for displaying success or error messages.

Now, go in the code behind of the Register.aspx and add a static web method called CheckAvailability. The following is the complete code of the method:

[WebMethod]
public static bool CheckAvailability(string uid)
{
   MembershipUser user = Membership.GetUser(uid);
   if (user == null)
   {
      return true;
   }
   else
   {
      return false;
   }
}

You might be wondering why you added a web method inside a web form. Remember that you have a “Check Availability” button that is supposed to check whether the specified user ID is available for registration. You will be making an AJAX call to do that. ASP.NET AJAX allows you to call web methods defined in web forms via an object called PageMethods. Therefore, you marked the CheckAvailability() method with a [WebMethod] attribute. Note that you must refer to the System.Web.dll and import the System.Web.Services namespace to use the [WebMethod] attribute.

The CheckAvailability() method accepts a user ID and returns true if that ID is available for registration. Inside, it calls the GetUser() method of the Membership object. The GetUser() method returns an instance of the MembershipUser class that represents the specified user. If it returns null, it indicates that the specified user doesn’t exist and accordingly true or false is returned to the caller.

When the user clicks the Register button, you need to add user details in the membership and profile tables. Use the Membership and Profile objects to do this BECAUSE ASP.NET AJAX doesn’t allow you to create users from client-side code. The following code shows the Click event handler of the Register button:

protected void Button1_Click(object sender, EventArgs e)
{
   try
   {
      MembershipUser user   = Membership.CreateUser
      (TextBox2.Text, TextBox3.Text, TextBox5.Text);
      ProfileCommon pc      = Profile.GetProfile(user.UserName);
      pc.FullName           = TextBox1.Text;
      pc.DOB                = DateTime.Parse(TextBox6.Text);
      pc.Address.Street     = TextBox7.Text;
      pc.Address.Country    = TextBox8.Text;
      pc.Address.PostalCode = TextBox9.Text;
      pc.Save();
      lblMsg.Text           = "User created successfully!";
   }
   catch (Exception ex)
   {
      lblMsg.Text = ex.Message;
   }
}

You call the CreateUser() method of the Membership object to create the user and pass user ID, password, and email. The CreateUser() method returns an instance of MembershipUser representing the newly created user. At this point, the user is not authenticated, so you cannot set the user’s profile directly via the Profile object. Instead, you call the GetProfile() method of the Profile object. The GetProfile() method returns an instance of the ProfileCommon class. Through this instance, you set various profile properties. Once all the profile properties are saved, the Save() method of the ProfileCommon class is called to save profile information to the underlying database. A success message is then displayed in a Label control. Any exceptions during the registration process are captured BY using try-catch blocks and an error message is displayed in a Label control.

Now, code the client-side CheckAvailability() function. Switch to the HTML source view of the Register.aspx and add a script block in the HEAD section of the page. Then, add the following functions in the script block:

function CheckAvailability()
{
   var uid=document.getElementById('TextBox2').value;
   if(uid=="")
   {
      alert('Please enter user ID!');
      return false;
   }
   PageMethods.CheckAvailability(uid,OnComplete);
   return false;
}
function OnComplete(result)
{
   var lblMsg=document.getElementById('lblMsg');
   if(result)
   {
      lblMsg.innerText="The ID is available!";
   }
   else
   {
      lblMsg.innerText="The ID is unavailable!";
   }
}

The CheckAvailability() function retrieves the user ID textbox using the getElementById() method of the HTML DOM, which accepts the ID of an element and returns a reference to it. The code checks whether the user ID is empty and, if so, displays an error message. It then calls the CheckAvailability() web method via the PageMethods object and passes the specified user ID to it. The PageMethods object is a built-in object provided by ASP.NET AJAX that allows you to call web methods defined in web forms. The second parameter of the CheckAvailability() call is nothing but the name of another JavaScript function (OnComplete in this example) that gets called after the web method call completes. You may find this mechanism a bit odd, but remember that ASP.NET AJAX communication is always asynchronous. The OnComplete() function receives the return value of the web method as a result parameter. It then simply displays a success or error message in a Label control. Note that the CheckAvailability() JavaScript function returns false so that there won’t be any post back.

This completes your registration page. To test it, run the Register.aspx in the browser and try creating new users. Also, check how the “Check Availability” button works. Figure 4 shows a sample run of the web form.

Figure 4. Sample Run of the Web Form

Developing a Login Page

Now that users can register themselves with the web site, you need to provide a facility that enables them to log in and access various pages. To do so, add a new web form called Login.aspx to the web site. Remember that you have set the loginUrl attribute of the forms tag to Login.aspx. Drag and drop a ScriptManager control on it and design the login page as shown in Figure 5 by assembling various controls.

Figure 5. The Login Page Design

As you can see, the login page consists of textboxes for entering a user ID and password. The “Remember Me” checkbox allows you to preserve your logged-in status even after closing the browser window. The TextMode property of the password textbox is set to Password. Further, the OnClientClick property of the Login button is set to “return BeginAuthenticateUser();”. BeginAuthenticateUser() is a JavaScript function that uses the ASP.NET AJAX authentication service to authenticate the user. The following is the BeginAuthenticateUser() function:

function BeginAuthenticateUser()
{
   var uid;
   var pwd;
   var isPersistent;
   uid=document.getElementById('TextBox1').value;
   pwd=document.getElementById('TextBox2').value;
   isPersistent=document.getElementById('CheckBox1').checked;
   Sys.Services.AuthenticationService.login
   (uid,pwd,isPersistent,null,null,
   EndAuthenticateUser,OnError,uid);
   return false;
}

he BeginAuthenticateUser() JavaScript function retrieves the user IDs and passwords entered in their respective textboxes. It also retrieves the status of the “Remember Me” checkbox. ASP.NET AJAX provides a built-n class called AuthenticationService that resides in the Sys.Services namespace. Remember that the Sys.Services namespace is defined by the client-side framework of ASP.NET AJAX. The AuthenticationService class offers two methods: login() and logout(). The code above used the login() method, which takes in all eight parameters. Their significance is listed below:

Parameter Significance
1 A user ID
2 A password
3 A boolean value indicating whether an authentication cookie will be persistent
4 The web page where the user should be redirect after a successful login
5 Reserved for future use
6 A callback function that will be called after a successful login (EndAuthenticateUser in this example)
7 A callback function that will be called in case a login attempt fails (OnError in this example)
8 A custom value that is passed to the callback functions

If the user is successfully authenticated, the EndAuthenticateUser function will be called. The following is the EndAuthenticateUser function:

function EndAuthenticateUser(result,userContext,methodName)
{
   if(result)
   {
      window.location='default.aspx';
   }
   else
   {
      alert("Unable to login! Please check user id and password!!");
   }
}

 

The EndAuthenticateUser() function takes three parameters: the result of the login operation, the user context that you passed earlier in the eighth parameter of the login() method, and the method name. Inside, it checks whether the result is true (in other words, the user is successfully authenticated) and, if so, it sets the location property of the windows object to default.aspx. This way, the user is redirected to the default page after a successful login attempt. If there is any error, an error message is displayed using the alert() function.

The OnError() function is called whenever an error occurs when calling the authentication service. This function is shown below:

function OnError(result,userContext,methodName)
{
   alert(result.get_message());
}

The function simply displays an error message to the user. The result parameter received is actually an object and has a method called get_message() that returns a descriptive error message.

This completes the login page.

 

ASP.NET: Use VB.NET and C# within the App_Code folder

Posted in ASP.NET (C# & VB), C#, VB by Alok Kumar Pandey on January 27, 2011

When I was creating my new blog site (this site your looking at), I chose to write it in C#. I had a problem with the App_Code folder because I had some code in VB.NET code and some C# code I needed to put in there. I didn’t want to rewrite my VB.NET code in the App_Code folder just so I could write the rest of the code for the site in C#.

Luckily, the ASP.NET Team had already thought about just this kind of circumstance. They implemented a way to partition the App_Code folder into sub-folders, one for each set of code files written in the same programming language. Awesome, I didn’t have to spend a couple hours converting code from VB.NET to C#!

The below works with ASP.NET 2.0 and later.

Even if you don’t use multiple different programming languages for your code files in the App_Code folder, you could use this feature to organize your sets of related code files into sub-folders.

Step 1: Add the following lines to the web.config

 

<configuration>
<system.web>
<compilation>
<codeSubDirectories>
<add directoryName=”VB_Code”/>
<add directoryName=”CS_Code”/>
</codeSubDirectories>
</compilation>
</system.web>
</configuration>

Step 2: Create a sub-folder in the App_Code folder for each language you want to support.
For Example:
/App_Code/VB_Code
/App_Code/CS_Code

Step 3: Place your VB.NET code in the VB_Code folder and place C# code in the CS_Code folder.

 

 

What if Visual Studio supported achievements

Posted in ASP.NET (C# & VB), C#, LINQ, PLINQ, SEO, SilverLight, VB by Alok Kumar Pandey on January 26, 2011

What if Visual Studio supported achievements, just like games on Steam, Xbox or PS3? Bragging to your coworkers about which one you’ve just unlocked, imagine that! Here’s a little proposed list for some of them. .NET / C# flavored, of course.

  • Falling Down – Created a new SharePoint project
  • Job Security – Written a LINQ query with over 30 lines of code
  • The Sword Fighter – 5 Consecutive Solution Rebuilds with zero code changes
  • Shotgun Debugging – 5 Consecutive Solution Rebuilds with a single character change
  • The Mathematician – Defined 15 local variables with a single character name
  • The Academic – Written 1000 lines of F#
  • Spaghetti Monster – Written a single line with more than 300 characters
  • Wild One – Mixed tabs and spaces for indentation more than 5 times in a single line
  • The Organizer – Created a Solution with more than 50 projects
  • The Portal – Created a circular project dependency
  • The Multitasker – Have more than 50 source files open at the same time
  • The Code Keeper – Uninstalled Resharper because it made you redundant
  • Pasta Chef – Created a class with more than 100 fields, properties or methods
  • Procedural Programmer – Created a method with more than 10 out parameters
  • Steam Powered – Added Visual Studio as a Steam game
  • The Poet – Written a source file with more than 10,000 lines
  • The Enterprise – Build Solution took more than 10 minutes
  • Highway to Hell – Successfully created a WCF service
  • The Explainer – Written a comment with more than 100 words
  • TPS Reports – Created a Crystal Reports Project
  • Rage Quit – ALT+F4 after a failed bug fix
  • Ooooh Shiny – Written 100 extensions methods
  • Look Ma – Written an infinite Fibonacci generator using yield
  • The Engineer – Killed a zombie with The Wrench
  • The Architect – Created 25 Interfaces in a single project
  • The Right Way – Test method is longer than the tested method
  • The Defender – Checked every argument for null exceptions
  • Pokemon Programming – Caught all the exceptions
  • Black Magic – Implemented a RealProxy
  • Gimme back my ASM – Used ILGenerator
  • I’m Sorry – Created a new Visual Basic Project
  • The SEO Expert – ASP.NET MVC Routing table with more than 100 routes
  • The Matrix – Windows Forms with more than 100 controls
  • The Daredevil – UpdatePanels nested more than 3 layers deep
  • Just a Test – Nested multiline C-style comments that caused a compilation error
  • Warm Bath – Successfully consumed a non .NET SOAP web service
  • Old School – Defined more than 100 static objects
  • The Cloner – Copy-pasted more than 50 lines
  • The Dependency – Referenced more than 30 projects
  • Paying the bills – Imported a Visual Basic project
  • First Hit – Included a Codeproject.com library into your project and it actually compiled
  • Paula – Define a firstname field with value Brillant
  • Every Option Considered – Created an enum with more than 30 values

how to generate validationKey and decryption Key for web.config

Posted in ASP.NET (C# & VB), C#, VB, WCF by Alok Kumar Pandey on January 12, 2011

This article describes how to create keys to use for encryption, decryption, and validation of Forms authentication cookie data. You can use the keys that you create in this article for the validationKey and decryptionKey attributes of the <machineKey> section in the <system.web> element in the web.config file or Machine.config.

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:

  • Microsoft Windows 2000 or Microsoft Windows XP
  • Microsoft .NET Framework
  • Microsoft Internet Information Services (IIS)

Create the project

Create a Visual C# .NET console application:

  1. Start Visual Studio .NET.
  2. On File menu, point to New, and then click Project.
  3. Under Project Types, click Visual C# Projects.
  4. Under Templates, click Console application.
  5. Name the project HashConfigCs.
  6. Click OK.

 

Write the code to generate the keys

The following code reads two arguments that are passed from the command line:

  • The first argument is the number of bytes that is used to create the decryptionKey attribute.
  • The second argument is the number of bytes that is used to create the validationKey attribute.

The code uses a random number generator to create a random number of bytes based on the command-line arguments. After the random bytes are created, the bytes are formatted into a hexadecimal string that is suitable for use in the .config files.

Note The hexadecimal string that is created is twice the size of the value that is passed on the command line. For example, if you specify 24 bytes for a key, the resulting string is 48 bytes in length after the conversion. The valid values for decryptionKey is 8 or 24. This creates a 16 byte key for Data Encryption Standard (DES) or a 48 byte key for Triple DES, respectively. Valid values for validationKey are 20 to 64. This creates keys from 40 to 128 bytes in length. The output from the code is an entire <machineKey> element that you can copy and paste into a web.config file.

Add the following code to a .cs file:

using System;
using System.Text;
using System.Security.Cryptography;

namespace Crypto
{
    public class KeyCreator
    {
        public static void Main(String[] args)
        {			
            String[] commandLineArgs = System.Environment.GetCommandLineArgs();
            string decryptionKey = CreateKey(System.Convert.ToInt32(commandLineArgs[1]));
            string validationKey = CreateKey(System.Convert.ToInt32(commandLineArgs[2]));

            Console.WriteLine("<machineKey validationKey=\"{0}\" decryptionKey=\"{1}\" validation=\"SHA1\"/>", validationKey, decryptionKey);
        }	

        static String CreateKey(int numBytes) 
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buff = new byte[numBytes];

            rng.GetBytes(buff);
            return BytesToHexString(buff);
        }

        static String BytesToHexString(byte[] bytes) 
        {
            StringBuilder hexString = new StringBuilder(64);

            for (int counter = 0; counter < bytes.Length; counter++) 
            {
                hexString.Append(String.Format("{0:X2}", bytes[counter]));
            }
            return hexString.ToString();
        }
    }
}

Generate the hashes

Now you can compile the application.

Run the application from a command prompt by passing in two integer values that are the size of the decryption and the validation keys. For example, if you named the console application HashConfigCs.exe, type the following syntax from the command line in the Bin\debug directory of the application:

hashconfigcs.exe 24 64

You can expect the application to return output that is similar to the following output:

<machineKey validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"
            decryptionKey="261F793EB53B761503AC445E0CA28DA44AA9B3CF06263B77"
            validation="SHA1"/>


Note Because the code is using a random number generator, the output is different each time.

Note for Machine.config

Update the configuration file

  1. Locate the Machine.config file.
  2. Locate the <system.web> section in the configuration file.
  3. Replace the <machineKey> section with the output from the console application. If the <machineKey> section does not exist, create it.
  4. Save the configuration file.
  5. Restart IIS on all servers in the Web farm for the Machine.config changes to take effect.

Troubleshooting

Make sure that the <machineKey> section has identical, explicit keys (that is, do not use the AutoGenerate option for attributes in the <machineKey> section) across the Web farm in the following scenarios:

  • When you use Forms authentication.
  • When you run session state in StateServer mode.
  • When you want ViewState to be available across a Web farm because the enableViewStateMAC attribute is set to True by default.

More information

The machineKey section should be the same across the web farm in the following cases:

  • When using Forms Authentication.
  • When you run session state in StateServer mode.
  • When you want viewstate to be available across a web farm since enableViewStateMac is turned on by default.

String Format for DateTime [C#]

Posted in ASP.NET (C# & VB), C#, LINQ, SilverLight, VB, WCF by Alok Kumar Pandey on January 2, 2011
String Format for DateTime [C#]

// create date time 2008-03-09 16:05:07.123 DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123); String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24 String.Format("{0:m mm}", dt); // "5 05" minute String.Format("{0:s ss}", dt); // "7 07" second String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M. String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone

// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt);            // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt);    // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt);            // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

Standard DateTime Formatting

Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
r, R RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTi­mePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
U UniversalSorta­bleDateTimePat­tern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)

(*) = culture independent