Er. alokpandey's Blog

Get Started SageFrame

Posted in ASP.NET (C# & VB), C#, HTML and XHTML, J-Query by Alok Kumar Pandey on April 25, 2012

On using SageFrame for your web development, you can, not only gain benefits of a CMS that is easy to use, but also an ability to create your own custom applications. Similarly, you can use applications and modules developed by other users. SageFrame’s plug and play modular architecture enables you to plug a desired module into your system and acquire the required feature instantly.

More

Advertisements

How to drop all the tables, stored procedures, triggers, constriants and all the dependencies in one sql statement on MSSQL 2005/2008/2008 R2

Posted in ASP.NET (C# & VB), C#, MSSQL by Alok Kumar Pandey on January 21, 2012

How to drop all the tables, stored procedures, triggers, constriants and all the dependencies in one sql statement on MSSQL 2005/2008/2008 R2

Script

DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘P’ AND category = 0 ORDER BY [name])

WHILE @name is not null
BEGIN
SELECT @SQL = ‘DROP PROCEDURE [dbo].[‘ + RTRIM(@name) +’]’
EXEC (@SQL)
PRINT ‘Dropped Procedure: ‘ + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘P’ AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all views */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘V’ AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = ‘DROP VIEW [dbo].[‘ + RTRIM(@name) +’]’
EXEC (@SQL)
PRINT ‘Dropped View: ‘ + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘V’ AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all functions */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N’FN’, N’IF’, N’TF’, N’FS’, N’FT’) AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = ‘DROP FUNCTION [dbo].[‘ + RTRIM(@name) +’]’
EXEC (@SQL)
PRINT ‘Dropped Function: ‘ + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N’FN’, N’IF’, N’TF’, N’FS’, N’FT’) AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘FOREIGN KEY’ ORDER BY TABLE_NAME)

WHILE @name is not null
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘FOREIGN KEY’ AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint IS NOT NULL
BEGIN
SELECT @SQL = ‘ALTER TABLE [dbo].[‘ + RTRIM(@name) +’] DROP CONSTRAINT [‘ + RTRIM(@constraint) +’]’
EXEC (@SQL)
PRINT ‘Dropped FK Constraint: ‘ + @constraint + ‘ on ‘ + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘FOREIGN KEY’ AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘FOREIGN KEY’ ORDER BY TABLE_NAME)
END
GO

/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘PRIMARY KEY’ ORDER BY TABLE_NAME)

WHILE @name IS NOT NULL
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘PRIMARY KEY’ AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint is not null
BEGIN
SELECT @SQL = ‘ALTER TABLE [dbo].[‘ + RTRIM(@name) +’] DROP CONSTRAINT [‘ + RTRIM(@constraint)+’]’
EXEC (@SQL)
PRINT ‘Dropped PK Constraint: ‘ + @constraint + ‘ on ‘ + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘PRIMARY KEY’ AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘PRIMARY KEY’ ORDER BY TABLE_NAME)
END
GO

/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘U’ AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = ‘DROP TABLE [dbo].[‘ + RTRIM(@name) +’]’
EXEC (@SQL)
PRINT ‘Dropped Table: ‘ + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘U’ AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

Reference

http://stackoverflow.com

eCommerce platform

Posted in ASP.NET (C# & VB), C#, HTML and XHTML, J-Query by Alok Kumar Pandey on December 16, 2011

A new open source “Flexible and easy eCommerce platform” offers a complete ecommerce solution that allows you to run your fully functional online store in minutes.

AspxCommerce is easy to learn, use and comes enhanced with abundant features for web designers, developers and merchants alike. Merchants can enjoy complete flexibility and control over the look, content and functionality of their online store, AspxCommerce is available on ColePlex
http://aspxcommerce.codeplex.com/

Download AspxCommerce
for features visit demo link http://demo.aspxcommerce.com/
to know much more please visit
http://www.aspxcommerce.com/

Intro

Demo

SageFrame is now available for ASP.NET 4.0 also

Posted in ASP.NET (C# & VB), C#, WCF by Alok Kumar Pandey on August 12, 2011
SageFrame is now available for ASP.NET 4.0 also, interested developers 
and site owners now can directly download from CodePlex. 
http://sageframe.codeplex.com/releases/view/70057 
How to install full guide is available 
Installation on Windows XP
 Installation on Windows 7
For details just visit 
http://www.sageframe.com
For the Support just visit
http://www.sageframe.com/Community/Forum.aspx
http://www.sageframe.com/Blog.aspx

Parallel Extensions for ASP.NET 4 Apps

Posted in ASP.NET (C# & VB), C#, Windows Mobile 7 by Alok Kumar Pandey on May 11, 2011

ASP.NET applications already get a lot of concurrency for free. The .NET Framework load balances incoming requests among ThreadPool worker threads, striving for optimal use of available CPUs. As long as you minimize blocking in your ASP.NET page code, ASP.NET will process requests concurrently. In most cases, and in particular for Web applications with heavy usage, it is probably not necessary to introduce extra parallelism since adding more work items will only result in competition for CPU time and ultimately reduce request throughput.

Dealing with I/O bound work
If most of the work being done in an ASP.NET request is asynchronous in nature (such as I/O), doing the asynchronous work synchronously can be a huge scalability bottleneck. Solutions based on Asynchronous Programming Model (APM) and Event-based Asynchronous Pattern (EAP) have been recommended to ease this bottleneck. For an in-depth discussion on this refer to Scalable Apps with Asynchronous Programming in ASP.NET and Asynchronous Pages in ASP.NET 2.0. The article Improving ASP.NET Performance also has some good pointers to improving the scalability of your web applications.

New features in the .NET Framework 4 can also be used to make programming asynchronous pages easier. The System.Threading.Tasks.Task class (and the Taskclass that derives from it) can be used to represent asynchronous operations, both classes implement IAsyncResult, and they provide capabilities for coordinating between multiple asynchronous activities. Since part of ASP.NET’s asynchronous pages support is based on the Asynchronous Programming Model (APM) pattern and IAsyncResult, Task can play a role in easing the implementation of asynchronous pages. In particular, Task is most useful if you want to structure your code with continuations, which can be useful if you have multiple stages of asynchronous activity that need to happen before the rest of the page continues execution. For more details, refer to Tasks and the Event-based Asynchronous Pattern and Tasks and the APM Pattern

Dealing with CPU intensive work

If requests are computationally cheap to process, then parallelism is probably an unnecessary overhead.

If the incoming request rate is high, then adding more parallelism will likely yield few benefits and could actually decrease performance, since the incoming rate of work may be high enough to keep the CPUs busy.

If the incoming request rate is low, then the Web application could benefit from parallelism by using the idle CPU cycles to speed up the processing of an individual request. We can use either PLINQ or TPL (either Parallel loops or the Task class) to parallelize the computation over all the processors. Note that by default, however, the PLINQ implementation in .NET 4 will tie-up one ThreadPool worker per processor for the entire execution of the query. As such, it should only be used in Web applications that see few but expensive requests.

If the incoming request rate is variable, i.e. there are long periods when request rate is low (say, at night) and then other periods when request rate is high (say, midday), we need a strategy that will dynamically adjust to the available resources. When the load is high, we don’t want to add to the contention but when the load is low, we want to use the idle resources. For this scenario, we can use TPL’s Parallel or Task constructs since they can adapt to use available resources within a process. If the server is already loaded, the Parallel loops can use as little as one worker and make forward progress. If the server is mostly free, they can grow to use as many workers as the ThreadPool can spare.

Conclusion


ASP.NET already takes advantage multiple processors on your server. Most developers will not need to explicitly add any parallelism into their ASP.NET Web applications. However, if your particular situation requires explicit parallelism, the new parallelism APIs in .NET 4 can be beneficial to you.

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?

“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.