Search

Dec 10, 2009

Schema and Data Compare Scripts in MS SQL

Hello All,

I was searching for a tool which gives me the Schema and or data comparison for SQL Server, its really needed while we are updating staging or updating our live site. There may be lots of tool available on net but I found one tool which is part of Microsoft® Visual Studio Team System 2008 Database Edition GDR R2.

Team Edition provides lots of functionality, mainly we are using to write Test Case which is very useful for Test Driven Development.

On top of this if you have Database edition then you can do lots of things with it. One of the feature is Schema and Data Compare. This blog post will walk you thru steps to compare data and schema.

Schema Comparison

1. Go to New Schema Comparison form Data menu

2. Next select the two database, one is source and other is target

 

3. When press OK will give you the Schema Compare of all the objects including Tables, Views, Stored Procedures and many more.

Here you can see the list of Objects and the Object Definitions windows

4. In following image Table is expanded so you can see the changes in details on what table what action is held.

 

5. To see more in details select one of the updated row and you can see the definition in Object Definitions window; it will generate Create script and highlight the difference. There is also Schema Update Script which will have alter script of all the changes that is detected during Schema Compare.

6. You can either copy the script or export to file or editor by using Export To Edition command on tool box.

This was all about how to detect schema change, its very handy with lots of options.

Data Comparison

Now same way we have Data Comparison, which is use to compare data, it provides tons of details and script for insert/update and delete. The steps are pretty much starlight forward. I have listed the steps here.

1. Click on New Data Comparison from Data menu

2. It will ask for Source and Target tables

3. On click of Finish, it will provide you all the information that is differ in between two database tables

You can see here it shows 2 rows are only in source, means two rows are added to SB_mst_Group table. It also provides the what exact rows are added in middle section along with other options.

In third last section which is Data Update Script; provides you the script for the action, here we have addition, so its provide the insert statements which we can run in UAT to get the date.

I found it very useful and easy to generate required script in few mouse click!

Nov 25, 2009

Consuming WCF service out of box

Hello All,

I found one issue while consuming WCF service from out of box, There are lots of threads I found for 'The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.' error, CommunicationObjectFaultedException exception thrown and 'The caller was not authenticated by the service.'

I spent lots of time in search, got bunch of solutions, some worked some does not, after doing lots of troubleshooting I got solution for my problem.

My case was, a web application running on different box is trying to consume WCF service which is hosted on different box, but some how on production it was not working. It always throws 'CommunicationObjectFaultedException'. Usually we are putting such calls in using blog, as its taking care of disposing object. But in case of WCF it may not work as per expected, the reason is; A CommunicationObjectFaultedException has been throws so you, the object is not yet initialized and you are using is trying to dispose method which again throw exception.

 

This is because using implicitly call Dispose at the closing brace, which may throw an exception because your object is not yet initialized as its in the Faulted state. To over come this a simple solution, use try catch and call Abort. More reading on this click Avoiding Problems with the Using Statement, good article form Microsoft including Sample application. During my search I found one good code delegate make you fell like you are using clause, but internally its handling such exception.

private class Util
{
public static void UsingWcf<T>(T client, Action<T> action)
where T : System.ServiceModel.ICommunicationObject
{

try
{
action(client);
client.Close();
}
catch (Exception)
{
client.Abort();
throw;
}
}
}
class Program
{
static void Main(string[] args)
{

Util.UsingWcf(new WcfClient(), c =>
{

});

/*using (WcfClient wcfClient = new WcfClient())
{
....
}// This will throw an error
*/
}
}

So we have caught CommunicationObjectFaultedException, but still we are not able to make call to service method. Now you can see one new error 'The caller was not authenticated by the service'. Cool we reach the service but its missing some credentials, as we are consuming service out of box.

Typical configuration section looks like following



Form error 'The caller was not authenticated by the service' we can guess that we need some credentials to call method. You can see the configuration; it says clientCredentialsType="Windows" and security mode is Message, generally with wsHttpBinding these are the typical settings.



As we are using Windows as credential type, we need to provide credentials to use WCF serverice out of box. Once this done you just need to pass user and password in ClientCredentials just like bellow

Nov 21, 2009

Baroda Developers Conference

Hello All,

Event  Baroda Developer Conference was held on Saturday, November 21, 2009 at Dr. I.G. Patel Seminar Hall Vadodara.

Links: Baroda Mega Developers Conference; Baroda Developers Conference [Dev-Con]

I recently gave presentation at a session titled as "Features of C# 3.0" followed by Probjots session "Introducing LINQ" & "VS 2010 & .Net 4.0" and "MOSS 2007" by Bhavin Gajjar.

It was my first experience to give a presentation. There were students who were part of Microsoft Student Partner program with sound knowledge in Microsoft .Net Technology.

Here are few snaps from conference. 

 

[Attending one students' question on Partial Methods]

[Me with Probjot and students]

[Attendees]

I want to congratulate all the attendees for being part of such a knowledge sharing conference and taking active part in it.They came from different territories of all over India. I really appreciate their interest. Also I have demo project which I have used during my presentation to get this send me an email.

I am very much thankful of Jacob Sebastian who promoted me for this event and Prakher Mehta who was the organizer and inviter of BUG [Baroda User Group]

Oct 14, 2009

Rolebase page access and rulebase operation access

Hi Again,

This is typical scenario where programmer done want to allow specific user to visit specific page due to functionality which needs to be secure based on user types. The task like managing users should not accessed by a normal user. So we need security based on user types, more precisely we need Authorization. Once user passed thru authentication it is not Authorization who decide the access of current logged user to perform some task.

Before introductions of ASP.NET Rolebase providers, people used to check on each page for the role, and if it does not have that role then redirection process, here all data related to user role kept in session.

This functionality is much more simpler after introduction of Rolebase provider, we just need to define roles and access to that roles. We can restrict users based on either role or userid itself, its depend how the application needs the functionality. This is for particular page, now what if I need to restrict user at operation level? Mean I don't allow Account user to manage users personal details, he just need to play with user's account, he does not need to update personal details of user. Here we can use Rolebase provider to check whether logged in user have rights to perform that operation or not.

Rolebase page Access: After setting roles and mapping, you just need to add few settings into configuration file which rolebase provider will use to perform authorization. Typical example of such web.config is as following.

Authorization_Admin

Lets understand the setting.

  • location tag in which you have to specify path of resource. If path is directory then the authorization will consider on all the pages inside that directory.
  • authorization tag will contains the allow or deny user/roles listing.
  • allow tag contains the roles attribute, in which you have to put role name. So you are allowing user having SiteAdmin to access ManageUser page. In the same way if you write deny roles then it will deny that particular role to access ManageUser page.
  • deny tag contains roles or user. In typical setting we are putting selected roles/users in allow list and for rest we kept as deny, so in deny you may always find * which means all user or all roles.

Typically we have more then one configuration files kept in different-different directories to manage folder separately.

Now let's see how we can implement operation level security using Rulebase provider. Microsoft Enterprise Library Security Application Block helps developers implement common authorization-related functionality in their applications. We just need to set some configuration setting using which you can identify the operation level access. Following is the typical configuration to implement rulebase provider.

RuleBaseProvider

You can see the how rule has been added here along with expression. You can add new rule by adding name and expression, expression is simple string which contains set of Role name and expression. There are list of more expression you can find bellow. First lets try to understand EditPersonalInfo rule, it has two role SiteAdmin or Superuser or User, so all user having these roles can perform EditPersionInfo operation.

Rule Expression can contains I, R, AND, OR, NOT, (, ), ?, *.

  • I: It will authorize to identity which is supplied with I
    • expresson="I:Imran" will allow a user with identity Imran
  • R: It will authorize to role which is supplied with R
  • Rest will be operator you can use at any time
    • expression="((R:Superuser OR R:AccountAdmin) AND (NOT R:SiteAdmin))"

Now this is all about configuring rules. Will see how to apply these rules in our coding.

RoleProvider_Code

Just two lines of code to know weather user is authorize to do that action or not.

Oct 13, 2009

SQL Challenge - Find second highest salary by department

Hello All,

I am starting this new thread called SQL Challenges, which will have SQL Challenge for beginners. I hope your all like that and participate also.

Jacob Sebastian, had already started posting challenges, I would like you to participate into challenge, may be you can get gift or rewards.

There are some rules and regulation which you have to read before posting any reply, it's very simple not a big deal. So first challenge is out there, to finding out second highest salary by department, please visit this link for more details. You can find scripts to generate data too.

Hope you will have great time to solving and most important thing is learning; you will learn lot not only from question also from the best answer posted for particular challenge.

Oct 11, 2009

Core Service - Extensible Output Caching

Output caching is one of the major factor to load your page more faster. up to now ASP.NET allow developer to store generated output of page, control and HTTP request into memory to used further request.

ASP.NET 4.0 provides the mechanism to let developer handle output cache by creating your own custom output-cache provider and manage the persistency of HTML content. For doing this you just need to create class which derives from System.Web.Caching.OutputCacheProvider type and add it to your caching section of web.config. The default provider is AspNetInternalProvider.

ExtensibleOutputCaching 

In addition, you can choose different provider for different pages! There are two way to do this.

First you need to override one new method in Global.asax called GetOutputCacheProviderName which helps you to select output cache provider.

OutputCacheGlobal

Adding code at request level is like adding more work to do, the easiest way is to select output-cache provider is to set value of attribute providerName which is part of OutputCache page or control directive.

OutputCachePage

Topic: ASP.NET 4.0 and Visual Studio 2010 Web Development Beta 2 Overview

Oct 10, 2009

Core Service – Web.Config file Minification

The configuration file is very important for each web application, each web application will have one master web.config file which contains all the setting that a simple web application needs, on top of it we have machine.config, there always be single machine.config file.

Now typical web.conifg will have lots of section and sub-section which are common for all the application, like AJAX related stuff, IIS integration and many more, what 4.0 does is it moved common setting from web.config to machine.confg, this means now your web.config file in ASP.NET 4.0 either empty or contains following lines.

WebConfigMinification

Topic: ASP.NET 4.0 and Visual Studio 2010 Web Development Beta 2 Overview

Oct 6, 2009

Overview of new features in windows 7 - MTD Session

Hello All,

This is my first post on Windows 7, I have attended the event Microsoft Community TechDays on 3rd October 2009 in Ahmedabad having one of the session on cool features of Windows 7, that had been presented by Vinod Kumar Microsoft Evangelist, who is known for his famous SQL site http://extremeexperts.com/. Who basically expert in SQL Server but did wonderful presentation with only one slide and tones of tips and tricks by Demo, I enjoyed the session lots.

I am listing some cool features which I like the most in windows 7 here, this does not mean that features rest feature I don't like but may be I need to explore windows 7 more and more as there are lots of features that been added to windows 7.




[Jacob Sebastian, Imran Bhadelia, Vinod Kumar]

  • Jump List

    The Jump List feature is designed to provide you with quick access to the documents and tasks associated with your applications. You can think of Jump Lists like little application-specific Start menus. Jump Lists can be found on the application icons that appear on the Taskbar when an application is running or on the Start menu in the recently opened programs section. Jump Lists can also be found on the icons of applications that have been specifically pinned to the Taskbar or the Start menu.

    For developer the JumpListManager class provides an abstraction of the application jump list, including facilities to manipulate custom destinations, user tasks, recent/frequent lists and items removed by the user.



  • VHD [Virtual Hard Disk]

    I like this feature the most, VHDs are widely used as storehouses for hard disk images you intend to deploy out to clients. For example, you can keep different images, for different types of users, in the form of separate VHDs and then just deploy the ones you need to whomever they need to go to. Although VHD is closely intertwined with virtualization, it's also being widely used as a stand-alone tool because Windows 7 adds support for Native VHD, which means you can use it without virtualization in place.

  • Global Keyboard shortcuts

    I love to use keyboard as much as I can, windows 7 have added lots of shortcuts to it, I am listing few here.

    Win+Space operates as a keyboard shortcut for Aero Peek.
    Win+Up and Win+Down are new shortcuts for Maximize and Restore/Minimize.
    Win+Shift+Up vertically maximizes the current window
    Win+Left and Win+Right snap the current window to the left or right half of the current display; successive keypresses will move the window to other monitors in a multi-monitor configuration.
    Win+Shift+Left and Win+Shift+Right move the current window to the left or right display.
    Win+ + and Win+ − (minus sign) zoom the desktop in and out.
    Win+Home operates as a keyboard shortcut for Aero Shake.
    Win+P shows an "external display options" selector that gives the user the choice of showing the desktop on only the computer's screen, only the external display, on both at the same time (mirroring), or on both displays with independent desktops (extending).

  • Direct Access

    Traditionally, remote users connect to internal network resources with a Virtual Private Network (VPN). However, using a VPN can be cumbersome for users because it requires several steps, and several seconds (or even minutes), for authentication to occur. Windows 7, together with Windows Server 2008 R2, introduces DirectAccess, a new solution that enables users to have the same experience working remotely as they would working in the office. Taking advantage of technologies such as IPv6 and IPSec, DirectAccess provides remote computers with automatic, seamless access to the internal network across the Internet without connecting to a Virtual Private Network (VPN), while providing secure and flexible network infrastructure for enterprises.



  • Taskbar APIs for developer



    The IMClient sample demonstrates how taskbar overlay icons and taskbar progress bars can light up an application’s taskbar button instead of relying on an additional dialog or on an icon in the system notification area (tray).

  • Aero Shake

    Aero Shake allows users to clear up any clutter on their screen by shaking (dragging back and forth) a window of their choice with the mouse. All other windows will minimize, while the window the user shook stays active on the screen. When the window is shaken again, they are all restored, similar to desktop preview.

  • Problem Steps Recorder

    A very handy tool to record steps which produce the problem, this is very useful if you belong to Quality Assurance. It gives you details of every operation that you had done along with image and description, and again it requires very less space as its highly compact. The Problem Steps Recorder creates a .MHT file (a type of HTML document that includes images in a single file) compressed in a zip archive. The IT professional can open the .MHT file, view screenshots and get an exact description of the user’s actions. It helps overcome language barriers, allowing IT professionals to diagnose problems regardless of language differences



  • Resource Monitor

    Before I was using process monitor, windows 7 have introduced resource monitor, which is way ahead from process monitor, it gives you all the information regarding CPU, Memory, Disk and Network.



  • More Advance Calculator

    New functionality allows the user to not only calculate in the Standard and Scientific modes, but also in Programmer and Statistics modes. And that’s not all! Ever need conversion formulas for temperature, weight, area, or time? Finding the unit conversion option makes it a snap and takes all the work out of the user’s hands.There are even templates for gas mileage, lease estimations, and mortgage estimations.



  • Aero Peek Your Desktop

    A lesser-known versatile tool introduced with Windows 7 is the Aero Peek. Just click the rectangle in the lower right hand corner of the task bar for quick access to your desktop. The keyboard shortcut Window Key + Space performs the same function.



Jul 15, 2009

Repeater with Paging and Sorting Features

Hi all,

We all know our pages need to be created dynamic, .NET provides some good inbuilt controls which does same thing specifically framework 2.0 included lots of handy controls to build you page quickly

I usually pick the Repeater control, to render simple or complex table, why because its very simple and main reason is its faster and light weighted. There are limitation of Repeater, like it does not have inbuilt functionality for Paging and Sorting.

We can add the functionality of Paging and Sorting by our own, I wrote an article on Extended Repeater, having Sorting and Paging support with very less effort. It uses PagedDataSource I am sure its very new to you! But it’s now new it was there as in framework 1.1!

You can find the article here, I have explained all important code logic and also you can download the sample code there.

Jul 2, 2009

Create your own shortcut in SQL Management Studio 2008

Hi All,

Shortcut is good way to increase the speed of development and work. SQL Server Management Studio 2008 have numerous shortcuts.

We are writing various SQL statement, few statements are common like, SELECT * FROM [TABLE_NAME] which we are using very frequent. its always tedious job to write SELECT * FROM statement, can’t we create shortcut for that? Yes we can. Here is the steps to create your own shortcut with screenshot may be it helps you to increase productivity.

Step 1: Find the Keyboard setting [Tools – Options – Keyboard]

ToolsOptions

Step 2: Pick the available Shortcut [Query Shortcuts]

Here you can see the default query shortcuts. Find the available and create your own.

QueryShortcut

Lets create one shortcut for SELECT Statement

SelectStatement 

Press OK, you are done with your first shortcut. Before we use the shortcut and it get applies we need to restart IDE so our shortcut will get effected.

After restarting IDE, in Query write the table name, select it and apply your shortcut [Ctrl+f1].

SelectDemo

You can see it works like SELECT * FROM EmpMaster. Now let’s apply WHERE clause and see if its works or not?

SelectWithWhere

It’s working perfectly. Use shortcuts be more productive.

Jun 30, 2009

Get query string value using JavaScript

Here is the JavaScript function getQuerystring which finds the key form query string and returns the value.

/*
* <summary>
* Get the querystring value
* </summary>
* <param name="key">A string contains the querystring key</param>
* <param name="defaultVal">Object which get returns when there is not key</param>
**/
function getQuerystring(key, defaultVal) {
if (defaultVal == null) {
defaultVal = "";
}
key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
var qs = regex.exec(window.location.href);
if (qs == null) {
return defaultVal;
}
else {
return qs[1];
}
}

Jun 22, 2009

Register for PHP Developers Day

Microsoft invites you to this exclusive session on Microsoft InterOp initiatives tailored for open source developers to create cutting-edge business applications.

 

Title

Level

Speaker

Details

1.

Build Mission Critical Applications on the Microsoft Platform using Eclipse

300

Nahas Mohammed, Technology Advisor, Microsoft

Microsoft has delivered multiple technologies that focus on interoperability with non-Microsoft and Open Source technologies. Learn how to use Eclipse tools today to build Silverlight applications that run on PCs and Macs, how to work in a cross-platform environment and yet integrate your solution with your designer team. Also get to know about Microsoft's commitment to openness with the Azure Services Platform.

2.

jQuery - the write less do more javascript library

300

Deepak Gulati, Lead Architect, Cricinfo.com

jQuery has gained tremendous popularity in little over two years. It aims to allow web developers to write clear, concise code that cleanly separates the behavior of a page from its design without having them fret over details of cross-browser Javascript development. With its formal inclusion into Microsoft's Ajax stack, it is bound to become an important tool in an ASP.NET Web
Developer's toolbox.
We'll begin with a whirlwind tour of some advanced features of Javascript and then move on to using jQuery for:

-

Efficient DOM traversal and manipulation

-

Using a unified event handling mechanism
across browsers

-

Increasing visual and functional appeal of your web-pages with special effects and plugins

3.

MS SQL Business Intelligence with mySQL

300

Praveen Srivatsa, Director, Asthrasoft

Have your data residing on mySQL but want to leverage MS SQL server capabilities to build Business Intelligence solutions? Then this is the right session for you. This session looks at leveraging your existing investments in mySQL and leveraging the Reporting and Analysis Services from MS SQL server to extract data out from your mySQL data store to build meaningful dashboards. It looks at how we can integrate SQL Reporting Services and use SSIS to harvest the data from mySQL. It also looks at how we can replicate or sync data between MS SQL Server and mySQL to be able to share the relevant data across these databases.

4.

Trouble Ahead? Know Your Project Warning Signs! How Successful Leaders Recognize and Deal with Project Warning Signs

 

Sanjay Dugar, instructor, ESI International

This session is run by ESI and provides detailed guidance on conducting project health checks, what warning signs to look for, how to find them and finally, when to pull the plug on a project. For more than 25 years, ESI International has helped many of the world's most successful organizations-including Fortune 1000 companies and nearly every major agency of the United States federal government-align strategies, build talent and achieve organizational goals. To date, ESI has helped more than 850,000 technical and specialized professionals around the world improve the way they manage their projects, contracts, requirements and vendor relationships.

 

Jun 13, 2009

Long word breaks the UI

Hi All,

Working with long word into Web application some times break the UI. There always be a question for How to break long words?? As a long word without space kills your user interface.

I found the reason, in general when you system is tested by QA first thing he is going to break if you don’t limit the size and then it try to break UI with adding a loooooong space less word :)

There can be lots of other solutions, like create function which finds the long word and break it out. But I like is Regx, yes the regular expression is very optimum, but you have to learn them which is not like eating piece of cake :)

Following is the Regx which validate the text box and allow user to add 35 character long word although it seems to be not possible :)

<asp:RegularExpressionValidator ID="regNoLongWords" runat="server" ControlToValidate="txtText"
ErrorMessage="Word is too long" Display="None"
ValidationExpression="(?!.*?\S{36,}).*"></asp:RegularExpressionValidator>

Have fun with Regx !!!

Jun 12, 2009

Tech.Ed India 2009

Its a great pleasure to make announcement that Tech.Ed 2009 its now in Ahmedabad, its FREE event and you should go and attend it. If you missed TechEd Indian 2009 at Hydrabad then you can now attend it in Ahmedabad, Gujarat, India on June 20, 2009 Saturday at Rock Regency.

techedonroad

You may get change to meet/talk to two MVPs Pinal Dave and Jacob Sebastian, who will also going to attend this event. If you are interested then register here it’s based on First Come First Serve.

Jun 8, 2009

Best way to hiding Telerik Grid Column

Hi All, I was just looking into list of function while applying some logic for show/hide column of Telerik it provides two methods to do so.

public GridColumn FindByUniqueName(string UniqueName);
public GridColumn FindByUniqueNameSafe(string UniqueName);


As name suggest first method is not safe, it can throw GridExceptions if no column is found, where second one is returning null if no column is found. Along with these tow method, it have one property name UniqueName; this property helps FindByUniqueName and FindByUniqueNameSafe to find the column. So now we don’t need to remember the column id also we can now easily change the sequence of column as they are not referring with unique name.

<telerik:GridTemplateColumn UniqueName="Clients" HeaderText="Clients">


And server side write following code.

GridColumn gridColumn = dgTest.Columns.FindByUniqueNameSafe("Clients");
if (gridColumn != null)
gridColumn.Visible = false;

Jun 3, 2009

Viewstate in dynamic Control

Hi All,

There is general problem to having issue with ViewState in dynamic control.

I have posted one article Code Project you can find it here.

May 27, 2009

Using let in LINQ to Objects – Performance killer if used wrong way

C# 3.0 LINQ has one more hidden and powerful feature; which provides you to store result of sub-expression in order to use subsequence clause. You can achieve this with the help of let keyword. The variable created using let is readonly; once initialized it can’t use to store another value only good this is it can be queried.

Let’s see this with example. We have employees details in text file delimited my ‘:’, also each employee have it’s own details separated by ‘,’.

string strEmployees = "1, John, Methew:2, Nick, Althoff:3, David, Oliver:4, Sam, Peterson";

Lets write query to grab all the employee details.

string strEmployees = "1, John, Methew:2, Nick, Althoff:3, David, Oliver:4, Sam, Peterson";

//Split with :
var query = from empData in strEmployees.Split(':')
select empData;

//Split with ,
foreach (var q in query)
{
var e = q.Split(',');
Console.WriteLine("Id - {0}, First Name - {1}, Last Name - {2}",
e[0], e[1], e[2]);
}

As you can see we have to write two different logic to split one more time employee details, now let’s use let keyword and make coding easy.

string strEmployees = "1, John, Methew:2, Nick, Althoff:3, David, Oliver:4, Sam, Peterson";

var query = from empData in strEmployees.Split(':')
let emp = empData.Split(',')
select new { Id = emp[0], FName = emp[1], LName = emp[2] };

foreach (var q in query)
{
Console.WriteLine("Id - {0}, First Name - {1}, Last Name - {2}",
q.Id, q.FName, q.LName);
}


In both query output will be same.

output

emp is intermediate enumerable type which we are using in next line! This is very simple example, now what compiler treats the code above? Compiler will create one sub-query that returns the anonymous type composed of the original value along with new value specified by the let.

As its creating sub-query if you write bunch of let statements, it will kill your performance. If its implemented in proper way let is very good option to go with, the scenario where you need some function which operates on your select clause more then 2-3 times, you can create let variable and use them into your select which makes your faster.

static void SummOfferNoLet()
{
var q = from c in Products
where SumOffers(c) < 10000 && SumOffers(c) > 1000
select c;
int count = q.Count();
}
static void SummOfferWithLet()
{
var q = from c in Products
let offerValue = SumOffers(c)
where offerValue < 10000 && offerValue > 100
select c;
int count = q.Count();
}


In this case SummOfferWithLet will faster as you can see SummOfferNoLet we need to call SumOffers twice.

Conclusion: Using let is powerful but if you used wrong way then it will kill the performance.

May 25, 2009

Issues with Web.config in IIS 7 and Modules (in Vista)

A simple web application runs fine on internal web server, but the time we put it on IIS7 specially in Windows Vista, its start giving configuration error, first and foremost is issue with Modules.

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

And its points to <handlers> section under <system.webServer> section. The issue related to IIS don’t have ASP.NET installed. You can check your Windows feature, although you have installed IIS7 and compatibility for IIS6, ASP.NET is not getting installed automatically. Here is the Windows feature should look like as in following image.

No_ASP.Net

You can find this window from Control Panel –> Programs and Features –> Turn Windows features on or off [Left panel]

TurnWindowsFeaturesOnOrOff

If you have ASP.NET installed on your IIS 7.0 then you have to change the configuration from applicationHost.config file, which resides in %windir%\system32\inetsrv\config\applicationHost.config. You can find the entry for handlers and it has value Deny for property overrideModeDefault, change it to Allow.

<section name="handlers" overrideModeDefault="Deny" /> to <section name="handlers" overrideModeDefault="Allow" />

While saving file I am pretty much sure that it asks for Administrator account although your role is Administrators as you are not owner of that file you can’t make change to file, so solution for this is login as Administrator and do the changes. For vista Administrator is not active for login so find my post which help you to login as Administrator.

May 23, 2009

How to login as Administrator in Windows Vista

Hi All,

In working with Visa, you always get Alert saying “You don’t have permission to access this folder, click continue to get access”, or “Windows needs your permission to continue” or “Destination Folder Access Denied” or due to security you are not able to save file or change who owned by System…. Lots more. Although you have Administrative privileges still its says sometime “You should have administrative permission”. Or if a program needs Admin permission then you can run that application using “Run as Administrator”!!!!

So we need to do login using Administrator account, but the question is from where?

In Vista, the Administrator (or an administrator) is no longer the most trusted object in the operating system. Yes this is to "ostensibly" protect the system, and is part of a general concept of protecting the integrity of the system. The Administration is not activated and you don’t find any User Interface [Up to now, I didn’t fine] which make it active!!! Does it means you can’t make it Active? NO.

To make it active, you have to run command prompt with Administrator permission. Go to Start –> All Programs –> Accessories –> Command Prompt [right click and RUN AS ADMINISTRATOR]

RunAsAdmin

Write following commands to make Administrator active and set the password.

CommandPrompt 

First command will make Administrator account active and another will set yourpassword as Administration account password. Last command Exit.

Now, reboot or switch user or logoff from current user; you can see it will ask for Administrator account password.

USE AT YOUR OWN RISK.

This application has failed to start because the application configuration is incorrect – Solution

I have migrated Vista Home to Vista Premium and my SQL Server and Visual Studio 2008 was not able to start and giving me error ‘This application has failed to start because the application configuration is incorrect, the application has failed to start because its side-by-side configuration is incorrect’. I then check the Event Viewer and find some Dependent Assembly were missing.

Activation context generation failed for "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\LanguagePackage.dll". Dependent Assembly Microsoft.VC80.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="8.0.50727.1833" could not be found. Please use sxstrace.exe for detailed diagnosis.

Solution: If you are using VS2005 then download vcredist_x86.exe, and for 2008 download vcredist_x86.exe. No need to do any registry entry or any manifest file.

Apr 17, 2009

User Group Meeting [18-Apr-09]

Its time to announce the user group meeting for Ahmedabad SQLServer UserGroup for the month of April.

The main focus of the meeting will be XML features of SQL Server 2008. You can read more on http://ahmedabad.sqlpass.org/

I would like you to join and gain lots of knowledge and also there will be QA session where you can ask any question related to topic or SQL Server

Hope to see many of you tomorrow!!!

Apr 2, 2009

Enum in JavaScript


We are using enum in server side scripting language, recently I come across requirement where I have to write lots of if-else if clause, then I found the interesting thing which is enum.

Lets see how we can declare enum.

var Technology = 
{
Microsoft: 0,
PHP: 1,
ROR: 2,
Java: 3
}

Minor change in declaration, now lets see how we can use enum.

function Show(tech) {

var msg = 'Welcome to the world of {0}';
switch (Number(tech)) {
case Technology.Microsoft:
alert(String.format(msg, 'Microsoft'));
break;
case Technology.PHP:
alert( String.format(msg, 'PHP') );
break;
case Technology.ROR:
alert(String.format(msg, 'ROR') );
break;
}

}


//And here is the function call
Show(0);
Show(Technology.PHP);
Show(Technology.Microsoft);
Show(2);



Mar 27, 2009

Anonymous Types in C# 3.0

We all know about Abstract Type, generally we are creating Class which are Abstract Type, A Class has name assigned with it. Anonymous Type are Class without specifying the name to it. You can create Anonymous class by using new operator. Consider the following example.

class AnonymousType
{
public string Name { get; set; }
public int Age { get; set; }
public string Country { get; set; }
}
.
.
.
AnonymousType a1 = new AnonymousType { Name = "Marco" };
var a2 = new AnonymousType { Name = "Paolo" };
var a3 = new { Name = "Tom", Age = 31 };
var a4 = new { a2.Name, a2.Age };
var a5 = new { a1.Name, a1.Country };
var a6 = new { a1.Country, a1.Name };



The variables a1 and a2 are of the AnonymousType, but the type of variables a3, a4, a5, and a6 cannot be inferred type, see more on Local Type Inference. The var keyword get the type based on assigned expression which must with new keyword and without a type specified.



The variables a3 and a4 are of the same anonymous type because they have the same fields and properties. Even if a5 and a6 have the same properties (type and name), they are in a different order, and that is enough for the compiler to create two different anonymous types.



You can use anonymous type in array initializer too, lets see and example.




var ints = new[] { 1, 2, 3, 4 };
var arr1 = new[] {
new AnonymousType { Name = "Marco", Country = "Italy" },
new AnonymousType { Name = "Tom", Country = "USA" },
new AnonymousType { Name = "Paolo", Country = "Italy" }};
var arr2 = new[] {
new { Name = "Marco", Sports = new[] { "Tennis", "Spinning"} },
new { Name = "Tom", Sports = new[] { "Rugby", "Squash", "Baseball" } },
new { Name = "Paolo", Sports = new[] { "Skateboard", "Windsurf" } }};



While ints is an array of int and arr1 is an array of AnonymousType, arr2 is an array of anonymous types, each containing a string (Name) and an array of strings (Sports). You do not see a type in the arr2 definition because all types are inferred from the initialization expression. Once again, note that the arr2 assignment is a single expression, which could be embedded in another one.



You can read more features from my older post, Automatic Properties, and Object-Collection Initialization, Local Type Inference and Partial Methods.

Mar 25, 2009

Local Type Inference in C# 3.0


There are list of new features added in C# 3.0, I already cover Automatic Properties, and Object-Collection Initialization and Partial Methods in my older posts, here one more new feature which allow you to write more relaxed code. In another work you can define variable and use them without worrying about too much about their type, leaving it to the compiler to determine the correct type of a variable by inferring it from the expression assigned to the variable itself.

The price for using type inference might be less explicit code against the types you want to use, but in our opinion, this feature simplifies code maintenance of local variables where explicit type declaration is not particularly meaningful.

This might seem to be equivalent to defining a variable of type object, but it is not. The following code shows you that an object type requires the boxing of a value type (see b declaration), and in any case it requires a cast operation when you want to operate with the specific type (see d assignment):

var a = 2;       // a is declared as int
object b = 2; // Boxing an int into an object
int c = a; // No cast, no unboxing
int d = (int) b; // Cast is required, an unboxing is done

C# 3.0 offers type inference that allows you to define a variable by using the var keyword instead of a specific type. When var is used, the compiler infers the type from the expression used to initialize the variable.

The var keyword calls to mind the Component Object Model (COM) type VARIANT, which was used pervasively in Visual Basic 6.0, but in reality it is absolutely different because it is a type-safe declaration. The following code shows some examples of valid uses of var: x, y, and r are double types; d and w are decimal; s and p are string; and l is an int. Please note that the constant 2.3 defines the type inferred by three variables, and the default keyword is a typed null that infers the correct type to p.

public void ValidUse(decimal d)
{
var x = 2.3; // double
var y = x; // double
var r = x / y; // double
var s = "sample"; // string
var l = s.Length; // int
var w = d; // decimal
var p = default(string); // string
}

The next sample shows some cases in which the var keyword is not allowed:

class VarDemo
{
// invalid token 'var' in class, struct or interface member declaration
var k = 0;
// type expected in parameter list
public void InvalidUseParameter(var x) { }
// type expected in result type declaration
public var InvalidUseResult()
{
return 2;
}
public void InvalidUseLocal()
{
var x; // Syntax error, '=' expected
var y = null; // Cannot infer local variable type from 'null'
}
// …
}

The k type can be inferred by the constant initializer, but var is not allowed on type members. The result type of InvalidUseResult could be inferred by the internal return statement, but even this syntax is not allowed .

Partial Methods in C# 3.0

In C# 2.0 Partial Class has been added, which was I personally believe very good features to work in multi-developer environment.

One more new feature added in C# 3.0; Partial Method. I already talked about Automatic Properties, and Object-Collection Initialization which also introduced in C# 3.0. Partial Method is a method which must reside [only signature] into Partial Type [Partial Class] and if define somewhere then will get executed. This basically a rule created by one, if other want to implement then go ahead or leave it blank. I can compare it with Interface method; although its major difference between Interface method and Partial method. In Interface method if you does not implement then the type which implement that interface MUST be abstract; but in the case of Partial Method, its not abstract but its Partial.

There are few rules if you want to work with Partial Methods:

  • A method must be declared within Partial Class or Partial Structure
  • A method cannot have access modifiers. [virtual, abstract, new, sealed...]. They are always private
  • A method must return void
  • A method cannot have out parameter
  • A method definition hast to end with ';'
Here is the simple example of Partial Methods

partial class PartialMethods
{
partial void DoSomeWork();
}

If you build with this code, it will work fine although we haven't write body of this function. If you see the Manifest you wont find this method anywhere. The only constructor will part of PartialMethods class.

PartialMethod1

Now let me write body for the method and check manifest again

partial class PartialMethods
{
partial void DoSomeWork();
}

public partial class PartialMethods
{
partial void DoSomeWork()
{
//Do your work here
}
}


PartialMethod2

Now we can see the method, this class is not full class but as partial methods are private, you cant not access from outside, you have to call within that class. Partial method allow developer to create rule which can be implemented later but only once.