Friday 14 October 2011

Windows User Account Control (UAC) restrictions have been addressed

When you are working with the SQL Server Reporting services on windows server 2008 R2 and Window7 then you may encounter the following exception

User ‘Domain\User’ does not have required permissions. Verify that sufficient permissions have been granted and Windows User Account Control (UAC) restrictions have been addressed


To overcome that issue we nee to set the User Account Control settings. The steps to set the User Access Control as follows

  1. Open control panel
  2. Click on System and Security
  3. Click on User Account Control Settings

    4.  Slide down the User Account Control up to never notify. Then Click on Ok.

   5. Restart the system now.
   6. Open the Report server url in browser(Ex: http://systemname/Reports)

I hope this will helps to you.



Replacing special characters while creating directory or file

When we are creating directory in windows it could not accept the spacial character for directory name.
If folder name string is dynamic( we don't know which string it is) then we need to write the spacial character from that string. To repalce special characrers while creating directory as follows(this step must be added if we don't confirm that string)
directoryname=System.Text.RegularExpressions.Regex.Replace(directoryname,@"[*?:\|<>\\/]", "-");

Monday 3 October 2011

How to get comma separated string from the list of object for specified property

I have a one requirement that I have list of objects with that object have properties(ID, Name, Description). I want a comma separated string from the list of object for ID property.
We can achieve this by using Reflection classes.

The solution for the requirement has follows

Create a generic method to get the Comma separated string
 public static string GetCommaSeparatedString<T>(List<T> list, string property)
        {
                string value = string.Empty;
                PropertyInfo info = typeof(T).GetProperties().Where(i => i.Name == property).FirstOrDefault();
                if (info != null)
                {
                    foreach (T listItem in list)
                    {
                        value += info.GetValue(listItem, null).ToString() + ",";
                    }
                }
            return value.Substring(0,value.Length-1);
        }
Usage:
Take an example with Category class with the properties ID,Name
public class Category
{      
    public int ID { get; set; }
    public string Name { get; set; }
}
Create a list with Category objects
List<category> categories=new List<category>();
categories.Add(new Catagory {ID=1, Name = "abc" });
categories.Add(new Catagory {ID=10, Name = "pqr" });
Call the method as follows
GetCommaSeparatedString<Category>(categories,"ID");
//output: 1,10

Thursday 15 September 2011

HTTP Error 500.21 - Internal Server ErrorHandler "PageHandlerFactory-Integrated" has a badmodule "ManagedPipelineHandler" in its module list

This is the error due to not installing the .net frame work 4.0 on IIS7.x server. To install the .net 4.0 frame work run the following on command prompt.
on 32-bit operating system
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe –i


on 64-bit operating system
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe –i

If the above solution not worked then apparently, the reason for recieving the Internal Server error message was that installed SQL Server 2008, after installing Visual Studio 2010 vice versa, and because of this it corrupted the IIS Machine level configuration files ("If you install VS2010 and then install VS2008 and VS2008 SP1, the configuration files for ASP.NET in IIS only include about 1/2 of the correct .Net 4.0 configuration sections." read more here).

To repair this problem run a full silent repair of the .NET Framework 4.0.   Here's how on either a 32 bit or 64 bit computer:
  1. Click Start -> All Programs -> Accessories -> Run
  2. In the Open textbox paste in the following line (see list of all .NET Framework version install, repair and unistall command lines here):
    For silent repair on 32 bit computer with .Net Framework version 4.0.30319 use:
    %windir%\Microsoft.NET\Framework\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart

    For silent repair on 64 bit computer with .Net Framework version 4.0.30319 use:
    %windir%\Microsoft.NET\Framework64\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart

  3. Click OK to start the repair
  4. After, the repair ran for a few minutes, I restarted IIS 7.5, and things began to work correctly!

Hopefully, this will work for you...

Sunday 4 September 2011

How to start microsoft single sign-on service

Use the following procedure to start the Single Sign-On service.

Start the Single Sign-On service

  1. From Administrative Tools, click Services.
  2. Double-click Microsoft Single Sign-On Service.
  3. On the Log On tab of the Single Sign-On Service Properties page, click This account, and then type the domain, user name, and password that you have used to install and manage your server.
  4. Click Apply.
  5. On the General tab of the Single Sign-On Service Properties page, change the startup type to Automatic, click Start, and then click OK.

SharePoint – Access Denied When Enabling The Office SharePoint ServerPublishing Infrastructure,Site Collection Feature

Cause:
The application pool account does not have access to create / update timer jobs which is required when enabling the Office SharePoint Server Publishing Infrastructure Site Collection feature.
Solution:
There are two options:
  1. Temporarily add the application pool account to the farm administrators group, or
  2. Run the following command:
    stsadm -o activatefeature -name PublishingResources -url http://SITECOLLECTIONURL

Steps to add application pool account to the farms administrator group

  1. Start > Programs > Administrative Tools > IIS Manager
  2. Expand the Application Pools node, locate the application pool associated with the site collection that is experiencing an issue
  3. Right-Click the Application Pool and select "Properties"
  4. Select the "Identity" tab
  5.  Note the user account
  6. Start > Programs > Microsoft Office Server > SharePoint 3.0 Central Administration
  7.  Site Actions > Site Settings > Advanced Permissions
  8. Click "Groups"
  9.  Click "Farm Administrators"
  10. New > Add Users
  11. Add Users: Type the name of the Application Pool Identity account
  12. Give Permission: Add users to a SharePoint group: Farm Administrators
  13. Add the Application Pool account to the Farm Administrators group
  14.  Send E-Mail: Uncheck (you most likely do not want to send an email)
  15.  Click OK
  16. Try again to activate the "Office SharePoint Server Publishing Infrastructure" Site Collection Feature

Sunday 28 August 2011

How to create new custom Trust Level and Code Access Security inSharePoint

Step 1: Create a custom policy file wss_custom.config by copying the out-of-box policy file
  •  Open directory “C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\CONFIG”. The directory contains the out-of-box policy files defining Wss_Medium and Wss_Minimal trust levels of SharePoint.
  • Make a copy wss_minimaltrust.config in the same directory and rename it to wss_custom.config.

Step 2: Refer to the “wss_custom.config” policy file from the web.config
  • Add a new trustLevel entry to the web.config. The trustLevel points to the new policy file  wss_custom.config your created in step 1.

    <securityPolicy>
    ......
    <trustLevel name="WSS_Custom" policyFile="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\config\wss_custom.config" />
    </securityPolicy>

  • Change <trust level="WSS_Minimal" originUrl="" /> to <trust level="WSS_Custom" originUrl="" />
    <trust level="WSS_Custom" originUrl="" />

    After the first two steps, your sharepoint web application starts to use the custom poplicy file, wss_custom.config. Rememeber the “wss_custom.config” is just a copy of the out-of-box “wss_minimaltrust.config”. Now, we need to modify the file.

Step 3: Modify the “wss_custom.config” policy file so the Dlls in bin directory of the sharepoint web application have CAS SharepointPermission. You just need to add one IPermission element to an existing permissionset element as the follows:
<PermissionSet  class="NamedPermissionSet"  version="1" Name="SPRestricted">
<!-- add the following element -->
<IPermission
class="Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
version="1"
ObjectModel="True"
/>
<!-- end of the element -->
</PermissionSet>

How did I figure out to add the SharePointPermission to the SPRestricted permissionset? First, the exception message already tells you that we need to add SharePointPermission. So, you need to add IPermission element with SharePointPermission as its class.You can just use Version=”1”. The real catch is how to figure out adding ObjectModel=”true”. Go to http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.security.sharepointpermission_properties.aspx. You notice the SharePointPermission is a .NET class with three public properties. ObjectModel is one of them. What I did was to try each property and assign them to true. After a few tries, ObjectModel=”True” is the only one that really matters.
 Why I choose to add it to SPRestricted PermissionSet?. This requires a basic understanding of the structure of the CAS Policy file. Do a search for “SPRestricted” in the WSS_custom.config file. You will find the following element:
<CodeGroup class="UnionCodeGroup"  version="1" PermissionSetName="SPRestricted">
<IMembershipCondition
class="UrlMembershipCondition"
version="1"
Url="$AppDirUrl$/*"
/>
</CodeGroup>

This is the code group that dictates the CAS permission for all the Dlls under "$AppDirUrl$ directory, which includes the bin directory. This code group uses “SPRestricted” permission set. That is why to add the IPermission element to the “SPRestricted” permissionset.

Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. Sharepoint Webpart/Infopath Form

Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed
A Web part/InfoPath form with managed code causes the above error.

Cause: DLL's that access databases require at least the WSS_Medium security policy in the web.config file. If you receive a security message from the web part, it's usually the trust element in the web.config file.
You could also have a dll outside the GAC that's trying to access some part of the SharePoint Object Model.
Fix: There's a couple of ways to resolve this issue.

  1. Put you dll in the GAC. I don't like putting limited use web parts in there and managed code for InfoPath doesn't like it.

  2. Open wss_mediumtrust.config & wss_minimaltrust.config usually (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\config\) look in your web.config file for the exact path. Find in wss_mediumtrust.config: Copy and paste it in to the node of wss_minimaltrust.config.
    In the PermissionSet section of this configuration file, add the following: Find in wss_mediumtrust.config:
    Copy and paste it in to the a node of wss_minimaltrust.config. That about covers it

  3. You could also set the trust level to "wss_mediumtrust" or create a custom trust level. To create custom trust level see the post How to create cutom trust level in sharepoint

Wednesday 24 August 2011

Can't able to save Office File to SharePoint Document Library onWindows Server 2008

Using SharePoint 2007 on Windows Server 2008 might bring additional steps to configuration that didn't exist in Windows Server 2003. On of the most questioned area is "why I can't able to save Office Document to the SharePoint Document Library"?

On Windows Server 2003 you can create new Office document via Document Library toolbar and save this document back to Library directly from the Office. However, in the SharePoint instance on Windows Server 2008 you will be asked to save the document to the File System(hard drive). You won't see SharePoint Lists and typing the url of the sharepoint server in the "Save" dialog box will generate the error "Path doesnt hot found".

The issue of this is that WebDav access and functionality to browser the site structure is incorporated to "Desktop Experience" feature of Windows Server 2008. It's a new feature and not enabled by default. So, to have ability save document to SharePoint from Office you need to add  "Desktop Experience" feature to Windows Server 2008 manually (unfortunately, server restart is required).

SharePoint 2010 is affected as well.

Steps To install Desktop Experience in Windows Server 2008
  1. go to server manager
  2. features--> Add Feature
  3. select Desktop Experience
  4. Click on Install
Note: Make sure that you remove the WebDAV module in IIS 7.5 also if you're on Windows Server 2008 R2

Thursday 11 August 2011

SQL Server does not handle comparison of NText, Text, Xml, or Imagedata types.

When insert XML to an XML field in SQL server via Linq to SQL it all works fine, But  when you try  to update this XML field using LINQ, you will  get this exception:
System.NotSupportedException: SQL Server does not handle comparison of NText, Text, Xml, or Image data types
Inorder to fix this issue just open the dbml file with xml editor and set the updatecheck to false as follows:
<column canbenull="true" dbtype="Xml" name="PermissionsXml" type="System.Xml.Linq.XElement" updatecheck="Never"></column>

Your personal site cannot be created because Self-Service Site Creationis not enabled. Contact your site administrator for more information

Sometimes, even after personalizing your permissions in Shared Services, and after going to mysite it prompts:
“Your personal site cannot be created because Self-Service Site Creation is not enabled. Contact your site administrator for more information”
In order to fix this,
  1. Go to Central Administration,
  2. Application Management
  3. go to the categorySite Security
  4. click Self-service site management.
  5. Enable it (ensuring that the mysite web application is selected)

the problem is fixed (not really a problem, it’s due to diable MySite creation)

Enjoy!

Friday 29 July 2011

Getting the Enums Description

Some times we need to enums for strongly typed strings in place of normal string values. But while displaying the enums we need the space between two words at that time we uses the enum description as follows
public enum MenuOptions
{
[Description("Park Vehicle")]
ParkVehicle = 1,
[Description("Exit Vehicle")]
ExitVehicle = 2,
[Description("Check Slot is Empty")]
CheckSlotIsEmpty = 3,
[Description("Parked Vehicles List")]
ParkedVehiclesList = 4,
[Description("Exit")]
Exit = 5
}

Code to get the Enum Description:
public String GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes
(typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
}

The usage of enum description as follows
public static void GetNavigation()
{
foreach (int i in Enum.GetValues(typeof(MenuOptions)))
Console.WriteLine("{0}. {1}", i,GetEnumDescription((Enum)Enum.Parse(typeof(MenuOptions),Enum.GetName(typeof(MenuOptions), i))));
}

Declaring and using delegates in csharp

The following is the simple way to declare and using delegates
using System;
using System.Drawing;
using System.Windows.Forms;

// custom delegate
public delegate void Startdelegate(); //we can pass any type of parameter ex StartDelegate(string x);

class Eventdemo : Form
{
// custom event
public event Startdelegate StartEvent;

public Eventdemo()
{
Button clickMe = new Button();

clickMe.Parent = this;
clickMe.Text = "Click Me";
clickMe.Location = new Point(
(ClientSize.Width - clickMe.Width) /2,
(ClientSize.Height - clickMe.Height)/2);

// an EventHandler delegate is assigned
// to the button's Click event
clickMe.Click += new EventHandler(OnClickedMe);
// our custom "Startdelegate" delegate is assigned
// to our custom "StartEvent" event.
StartEvent += new Startdelegate(OnStartEvent);

// fire our custom event
StartEvent(); // if pass the parameters while declaring then call like StartEvent("hello")
}

// this method is called when the "StartEvent" Event is fired
public void OnStartEvent()
{
MessageBox.Show("I Just Started!");
}
//this method is called when button is clicked
public void OnClickedMe(object delSender, EventArgs delE)     
    { 
       MessageBox.Show("You Clicked My Button!");  
     };

 static void Main(string[] args)
{
Application.Run(new Eventdemo());
}
}

Note: EventHandler is a builtin type delegate. We can write our own delegates to handle events.

Querying xml using LINQ

LINQ to XML

Suppose that instead of hard-coding our suppliers and products, we’d used the following XML file:
<?xml version="1.0"?>
<Data>
<Products>
<Product SupplierID="1">
<Name> West Side Story</Name>
<Price>9.99</Price>
</Product>
<Product SupplierID="2">
<Name>Assassins</Name>
<Price>14.99</Price>
</Product>
<Product SupplierID="1">
<Name>Frogs</Name>
<Price>9.99</Price>
</Product>
</Products>
<Suppliers>
<Supplier SupplierID="1">
<Name>Solely Sondheim</name>
</Supplier>
<Supplier SupplierID="2">
<Name>CD-by-CD-by-Sondheim</name>
</Supplier>
</Suppliers>
</Data>

The file is simple enough, but what’s the best way of extracting the data from it? How do we query it? Join on it?. The following listing shows how much work we have to do in LINQ to XML.
XDocument doc = XDocument.Load("data.xml");
var filtered = from p in doc.Descendants("Product")
join s in doc.Descendants("Supplier")
on (int)p.Attribute("SupplierID")
equals (int)s.Attribute("SupplierID")
where (decimal)p.Element("Price") > 10
orderby (string)s.Element("Name"),
(string)p.Element("Name")
select new
{
SupplierName = (string)s.Element("Name"),
ProductName = (string)p.Element("Name")
};
foreach (var v in filtered)
{
Console.WriteLine("Supplier={0}; Product={1}",
v.SupplierName, v.ProductName);
}

Browser fixes for Styles in CSS

To apply any styles specific to the  all IE browsers append \o/ (use zero) to the styles before the semicolon as follows
.class{ padding-top:10px \o/; }

To apply any styles specific to the  all IE7  append  either // or  * to the styles before the style as follows
.class{ //padding-top:10px; }

.class{ *padding-top:10px; }

To apply any styles specific to the  safari browser append write the styles as follows
 @media screen and (-webkit-min-device-pixel-ratio:0) 
{
   //write your styles here
}

Ex:

 @media screen and (-webkit-min-device-pixel-ratio:0)
{
    .class {font-size:15px; margin-top:3px;}
}

To apply the styles specific to IE9 then the style declaration for IE9 as follows

Ex:
:root #dvtest { left:300px\o/;}

How to Get the Index Position of the LINQ Query Results

Select  and SelectMany  expose an overload that surfaces the index position (starting at zero) for each returned element in the Select projection. It is surfaced as an overloaded parameter argument of the selector lambda expression and is only accessible using the extension method query syntax(Lamda Expression). The following sample code demonstrates how to access and use the index position value in a Select projection.
List<CallLog> callLog = CallLog.SampleData();
var q = callLog.GroupBy(g => g.Number)
.OrderByDescending(g => g.Count())
.Select((g, index) => new
{
number = g.Key,
rank = index + 1, //one is added because it is zero based index
count = g.Count()
});

Creating an Xml document using XmlWriter in C Sharp

The following is the sample code to create xml document using c sharp
FileStream fs = new FileStream("products.xml", FileMode.Create);

XmlWriter w = XmlWriter.Create(fs);

w.WriteStartDocument();
w.WriteStartElement("products");

w.WriteStartElement ("product");
w.WriteAttributeString("id", "1001");
w.WriteElementString("productName", "Gourmet Coffee");
w.WriteElementString("productPrice", "0.99");
w.WriteEndElement();

w.WriteStartElement("product");
w.WriteAttributeString("id", "1002");
w.WriteElementString("productName", "Tea Pot");
w.WriteElementString("productPrice", "12.99");
w.WriteEndElement();

w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();

We can write it also by using XmlTextWriter. the following is the sample code is using XmlTextWriter
// prepare and write XML document
using (StringWriter writer = new StringWriter())
{
using (XmlTextWriter doc = new XmlTextWriter(writer))
{
// prepare XML header items
doc.Formatting = Formatting.Indented;
doc.WriteComment(”Summarized Incoming Call Stats”);
doc.WriteStartElement(”contacts”);
// join calls with contacts data
foreach (Contact con in contacts)
{
if (callGroups.ContainsKey(con.Phone))
{
List calls = callGroups[con.Phone];
// calculate the total call duration and average
long sum = 0;
foreach (CallLog call in calls)
sum += call.Duration;
double avg = (double)sum / (double)calls.Count;
// write XML record for this contact
doc.WriteStartElement(”contact”);
doc.WriteElementString(”lastName”,
con.LastName);
doc.WriteElementString(”firstName”,
con.FirstName);
doc.WriteElementString(”count”,
calls.Count.ToString());
doc.WriteElementString(”totalDuration”,
sum.ToString());
doc.WriteElementString(”averageDuration”,
avg.ToString());
doc.WriteEndElement();
}
}
doc.WriteEndElement();
doc.Flush();
doc.Close();
}
Console.WriteLine(writer.ToString());
}

Declaring and using anonymous types

The following is the way of declaring and using anonymous types
// simple anonymous type declaration
Console.WriteLine(”- Simple Anonymous Type -”);
var item = new { Name = ”Car”, Price = 9989.00 };
Console.WriteLine(”Type: {0}, Name: {1}, Price: {2}”,
item.GetType().ToString(), item.Name, item.Price);

 

// declaring and working with array of anonymous types
Console.WriteLine();
Console.WriteLine(”- Iterating Anonymous Types Array -”);
var list = new[] {
new { LastName = ”Magennis”,
DateOfBirth = new DateTime(1973,12,09)
},
new { LastName = ”Doherty”,
DateOfBirth = new DateTime(1978,1,05)
}
};
foreach (var x in list)
Console.WriteLine(”{0} ({1})”,
x.LastName, x.DateOfBirth);

Generating xml using linq query

The sample code for generating xml using linq query as follows
List<Contact> contacts = Contact.SampleData();
List<CallLog> callLog = CallLog.SampleData();
var q = from call in callLog
where call.Incoming == true
group call by call.Number into g
join contact in contacts on
g.Key equals contact.Phone
orderby contact.LastName, contact.FirstName
select new XElement(”contact”,
new XElement(”lastName”,
contact.LastName),
new XElement(”firstName”,
contact.FirstName),
new XElement(”count”,
g.Count()),
new XElement(”totalDuration”,
g.Sum(c => c.Duration)),
new XElement(”averageDuration”,
g.Average(c => c.Duration))
);
// create the XML document and add the items in query q
XDocument doc = new XDocument(
new XComment(”Summarized Incoming Call Stats”),
new XElement(”contacts”, q)
);
Console.WriteLine(doc.ToString());

output for the above query is as follows
<!—Summarized Incoming Call Stats—> 
<contacts>
<contact> 
<lastName>Gottshall</lastName> 
<firstName>Barney</firstName> 
<count>4</count> 
<totalDuration>31</totalDuration> 
<averageDuration>7.75</averageDuration>
</contact> 
... (records cut for brevity) 
<contact>
<lastName>Valdes</lastName> 
<firstName>Armando</firstName> 
<count>2</count> 
<totalDuration>20</totalDuration> 
<averageDuration>10</averageDuration>
</contact> 
</contacts>

Thursday 28 July 2011

Grouping list of objects

There are two methods for grouping list of  objects in c sharp. one is using  Dictionary and other one is using linq to objects

Using StoredDictionary
// group by state (using a sorted dictionary)
SortedDictionary<string, List<Contact>> groups =
new SortedDictionary<string, List<Contact>>();
foreach (Contact c in contacts)
{
if (groups.ContainsKey(c.State))
{
groups[c.State].Add(c);
}
else
{
List<Contact> list = new List<Contact>();
list.Add(c);
groups.Add(c.State, list);
}
}
// write out the results
foreach (KeyValuePair<string, List<Contact>>
group in groups)
{
Console.WriteLine(”State: “ + group.Key);
foreach (Contact c in group.Value)
Console.WriteLine(” {0} {1}”,
c.FirstName, c.LastName);
}

Using Linq to objects:

Linq to objects works from 3.0 .net frame work

var query = from c in contacts group c by c.State;
// write out the results
foreach (var group in query)
{
Console.WriteLine(”State: “ + group.Key);
foreach (Contact c in group)
Console.WriteLine(” {0} {1}”,
c.FirstName, c.LastName);
}

Sorting a list of object in c sharp

There are three methods to sort list of  objects in c sharp. one is using Deletages, second Implementing IComparer interface, and other one is using linq to objects

Implementing IComparer(C#1.0)
class ContactNameComparer : IComparer
{
public int Compare(Contact x, Contact y)
{
return x.Name.CompareTo(y.Name);
}
}
...
List<Contact> contacts=Contact.SampleData();
contacts.Sort(new ContactNameComparer());
foreach (Contact contact in contacts)
{
Console.WriteLine(contact);
}


Using  inline delegates(from C#2.0)

List<Contact> contacts = Contact.SampleData();
// sort by last name
contacts.Sort(
delegate(Contact c1, Contact c2)
{
if (c1 != null && c2 != null)
return string.Compare(
c1.LastName, c2.LastName);
return 0;
}
);

Using Linq to Objects(From C#3.0)

List<Contact> contacts = Contact.SampleData();
// perform the LINQ query
var query = from c in contacts
orderby c.State, c.LastName;

Friday 22 July 2011

Regular Expression for password strength validation

Shown below is the regular expression for password strength with n number of digits, upper case, special characters and at least 6 characters in length.
(?=^.{6,25}$)(?=(?:.*?\d){2})(?=.*[a-z])(?=(?:.*?[A-Z]){2})(?=(?:.*?[!@#$%*()_+^&}{:;?.]){1})(?!.*\s)[0-9a-zA-Z!@#$%*()_+^&]*$
Explanation:
  • (?=^.{6,25}$) -- password length range from 6 to 25, the numbers are adjustable
  • (?=(?:.*?[!@#$%*()_+^&}{:;?.]){1}) -- at least 1 special characters (!@#$%*()_+^&}{:;?.}) , the number is adjustable
  • (?=(?:.*?\d){2}) -- at least 2 digits, the number is adjustable
  • (?=.*[a-z]) -- characters a-z
  • (?=(?:.*?[A-Z]){2}) -- at least 2 upper case characters, the number is adjustable

Wednesday 13 July 2011

HTML 5 support for all non supported IE browsers or HTML5 in IE

Many of time you have seen that few HTML 5  tags are not supported by Internet Explorer. The solution for this is only <script> tag.

The <script> tag is very useful to define client side script but in this code I used it for only to make my Internet Explorer compatible to represent HTML5  tags.
To work with html5 tags in IE write the following code in <script> tag in header section.
<script type="text/javascript">  
document.createElement('nav');
document.createElement('menu');
.........................
.........................
</script>

Like the above what are the tags you want use just write single statement for each tag. or write as below
<!--[if IE]>
<script type="text/javascript">
var html5elements =
"menu,nav,output,progress,section,time,video,...........etc".split(',');
for (var i = 0; i < html5elements.length; i++)
document.createElement(html5elements[i]);
</script>
<![endif]-->

Monday 6 June 2011

How to identify is image is loaded or not using jquery. If image notloaded loading the default image

When we are working with websites some times images may failed to load. To Identify is the image is loaded or not the follwing is the solution.
Solution 1
function IsImageLoaded() {
if($('#img_id').attr('complete')){
alert('Image is loaded!');
return true;
} else {
return false;
}
}
Solution 2
$("#photo").error(function() {
alert("Image failed to load");
});

Thursday 5 May 2011

IIS7.5 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

On attempting to deploy a .net 3.5 website on the default app pool in IIS7 having the framework section set to 4.0, I get the following error. There is a duplicate 'system.web.extensions/scripting/scriptResourceHandler' section defined.

To resolve this issue

Solution 1:


You will need to cleanup the web.config that includes all the section Definitions that point to .net 3.5. The reason this fails is because these section definitions are already included in the root web.config in .NET 4.0 (see %windir%\microsoft.net\framework\v4.0.30319\config\machine.config) that include all the system.web.extensions declared already.

Solution 2:

Another quick fix is to have the application pool set to 2.0 just as your development machine appears to have,.



Monday 25 April 2011

The 'RadLangSvc.Package, RadLangSvc.VS, Version = 10.0.0.0, Culture = neutral, PublicKeyToken = 89845dcd8080cc91' failed to load

A couple of days ago, using the Schema Compare tool included in Visual Studio 2010 Ultimate, I ran into an error that reads:

"The 'RadLangSvc.Package, RadLangSvc.VS, Version = 10.0.0.0, Culture = neutral, PublicKeyToken = 89845dcd8080cc91' package did not load Correctly."

The system continues to operate apparently, only after the settings when we kick off the comparison, the environment crashes fatal.
After a little 'research I found this post which in turn refers to that.

The problem is essentially due to the installation of SQL Server 2008 R2, which affected various components associated with the SQL scripting. The same symptoms occur it is also using the SQL shell included in VS, even though I had installed the R2 for a while, 'I have not noticed it before because I always use the environment to SQL Server Management Studio.
The proposed solution is to simply re-run the post installation

DACProjectSystemSetup_enu.msi

located on the installation disc in the folder of VS 2010

\ WCU \ DAC

but for more serious problems may need to rerun the other two in the same folder installer

TSqlLanguageService_enu.msi
DACFramework_enu.msi

take care of it in VS closed and once the installation is complete, there is no need to restart everything is already back in place.

Sunday 17 April 2011

Determining which key is pressed using java script or Working withjavascript key codes

The following example is used to determine which key is pressed using javascript
<script type="text/javascript">
function displayunicode(e){
var unicode=e.keyCode? e.keyCode : e.charCode
alert(unicode)
}
</script>
<form>
<input type="text" size="2" maxlength="1"
onkeyup="displayunicode(event); this.select()" />
</form>

Working with jquery key events

The key events are always required to use in application when we dont want to use mouse. the following is the example to handle key events using key codes in jqurery. for all javascript key codes refer http://vikramdoda.wordpress.com/2011/04/10/javascript-key-codes/

Syntax for handle keypress event is
.keypress( [ eventData ], handler(eventObject) )
eventDataA map of data that will be passed to the event handler.
handler(eventObject)A function to execute each time the event is triggered.
<script> var xTriggered = 0;
 $('#target').keypress(function(event) { 
  if (event.which == '13') {   
   event.preventDefault();   
 }  
  xTriggered++;   
 var msg = 'Handler for .keypress() called ' + xTriggered + ' time(s).';  
 $.print(msg, 'html'); 
  $.print(event);
 });
 </script>

Thursday 14 April 2011

Restoring SQL Server Database from .bak files

Restoring MSSQL Database from .bak files

1. Open SQL Server Management Studio on your local machine.
2. Right click the Databases folder. From the pop-up menu, select New Database.
3. Enter a database name, and then click Ok.
4. Right click the new database icon. From the pop-up menu, select Tasks -> Restore -> Database.
5. Select the From Device option, and then click the browse button.
6. Click Add and navigate to the appropriate file. Click Ok.
7. In the Restore Database window, select the checkbox next to your .bak file.
8. Switch to the Options page. Select the Overwrite the existing databasecheckbox.
9. Click Ok.
10. Verify the contents of your database, which is now active on your local machine.

Unable to launch the application because port 'N' already in use.

I had a similar problem.  I found it to be related to the Eset personal security (guessing a recent update messed something up). To solve it I excluded VS2008 from the active browser filtering - this is in: setup -> advanced firewall setup -> antivirus & anti spyware -> web access protection -> HTTP -> webbrowsers

Deselecting vsdev in here fixed the problem - interestingly enough disabling the firewall and antivirus / antispyware did not solve the issue, so it is worth looking for a similar setting if you are running different security software

Restoring SQL Server Database from .mdf files

Restoring MSSQL Database from .mdf files

1. Open SQL Server Management Studio on your local machine.
2. Right click the Databases folder. From the pop-up menu, select Attach.
3. Click Add and select the appropriate .mdf file. Click Ok, and then click Ok again.
4. Verify the contents of your database, which is now active on your local machine.

How to run MVC3 Razor Application on IIS6

IIS6 Extension-less URLs

All the MVC3 razor application are not having any extension files. The IIS6 is not understand the extension less urls by default. In order to solve this problem the solution is as follow:

The extension-less URLs using the infamous “Star mapping” or “Wildcard mapping” feature of IIS 6. I say infamous because there is a lot of concern over the performance implications of doing this. Of course, you should measure the performance of your site for yourself to determine if it is really a problem.

Steps
  1. Go to Run-->Inetmgr-->then expand your website-->select virtual directory-->righclick-->properties.
  2. Click on Configuration-->Application Configuration Properties dialog will open.
  3. Select .aspx in application fileextensions--->clik on Edit. then Add/edit application extension mappind dialog will open.
  4. Copy the executable text-->click on cancel.
  5. Go back to Application Configuration dialog-->Click on inset beside the Wild card application maps
  6. then paste the executable text which is copied previously(that is nothing but isapi filter file path). Uncheck verify that file exits. dont forget to uncheck Verify that file exists. Click on ok.
  7. Restart iis.
  8. Now run your application.

Wednesday 13 April 2011

SQL Server 2008 Setup on Windows Fail With “The system cannot find thepath specified”

  • Clean SQL 2008 components using the command line given at the top of the Summary.txt file:
    setup /q /action=uninstall /instanceid=MSSQLSERVERfeatures=SQLEngine,Replication,FullText
    OR
    Use Add\Remove Programs to clean the installed components.
  • Do not remove 100 folder inside C:\Program Files\Microsoft SQL Server\..
  • Now, run rsfx.msi file from ..\Installation folder\[x86] or [x64] or [ia64]\Setup folder. This will create the RsFxInstall folder and .ini files inside ..\100\Shared.
  • Then start the slipstream setup again.

Sql Server 2008 Installation failed


If already sql server is installed in your system. if you want to upgrade or reinstalling fails
then follow the given steps

  1.  Stop IIS Admin Service
  2.  Stop IIS
  3. Uninstall SQL Server previously installed.
  4.  Start new installation

Tuesday 12 April 2011

Get the current page url using javascript

The following code line is used to get the current page url:
var currentPage=parent.document.URL.toString();

Getting jQuery Intellisense in Razor pages


Get jQuery Intellisense by adding this to a page:
@if(false)
{
<script src="../../Scripts/jquery-1.4.2-vsdoc.js" language="javascript" />
}

Sunday 10 April 2011

Javascript Key codes

Here is the list of key codes to handle key events in javascript.
Key Pressed Javascript Key Code
backspace 8
tab 9
enter 13
shift 16
ctrl 17
alt 18
pause/break 19
caps lock 20
escape 27
page up 33
page down 34
end 35
home 36
left arrow 37
up arrow 38
right arrow 39
down arrow 40
insert 45
delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
left window key 91
right window key 92
select key 93
numpad 0 96
numpad 1 97
numpad 2 98
numpad 3 99
numpad 4 100
numpad 5 101
numpad 6 102
numpad 7 103
numpad 8 104
numpad 9 105
multiply 106
add 107
subtract 109
decimal point 110
divide 111
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123
num lock 144
scroll lock 145
semi-colon 186
equal sign 187
comma 188
dash 189
period 190
forward slash 191
grave accent 192
open bracket 219
back slash 220
close braket 221
single quote 222

All Sql Server Connection Properties for creating Connection String

There are plenty of combinations when creating an SQL Server connection string. This reference table explains each option available per keyword.

Introduction
This table shows all connection string properties for the ADO.NET SqlConnection object. Most of the properties are also used in ADO. Using this table will give you a better understanding of the options available.

The Properties
Some of the keywords have several equivalents. For those, each variant is specified on its own line separated with "-or-".
Name Default Description
Application Name The name of the application, or '.Net SqlClient Data Provider' if no applicationname is provided.
Async 'false' When true, enables asynchronous operation support. Recognized values are true, false, yes, and no.
AttachDBFilename
-or-
extended properties
-or-
Initial File Name
The name of the primary database file, including the full path name of an attachable database. AttachDBFilename is only supported for primary data files with an .mdf extension. The attachment will fail if the primary data file is read-only. The path may be absolute or relative by using the DataDirectory substitution string. If DataDirectory is used, the database file must exist within a subdirectory of the directory pointed to by the substitution string.

Note that remote servers, HTTP, and UNC (\\server\sharename\folder\) path names are not supported.

The database name must be specified with the keyword 'database' (or one of its aliases) as in the following: "AttachDbFileName=|DataDirectory|\data\YourDB.mdf; integrated security=true;database=YourDatabase". An error will be generated if a log file exists in the same directory as the data file and the 'database' keyword is used when attaching the primary data file. In this case, remove the log file. Once the database is attached, a new log file will be automatically generated based on the physical path.
Connect Timeout
-or-
Connection Timeout
15 The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.
Connection Lifetime 0 When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by Connection Lifetime. This is useful in clustered configurations to force load balancing between a running server and a server just brought online. A value of zero (0) causes pooled connections to have the maximum connection timeout.
Context Connection 'false' true if an in-process connection to SQL Server should be made.
Connection Reset 'true' Determines whether the database connection is reset when being removed from the pool. Setting to 'false' avoids making an additional server round-trip when obtaining a connection, but the programmer must be aware that the connection state is not being reset.
Current Language The SQL Server Language record name.
Data Source
-or-
Server
-or-
Address
-or-
Addr
-or-
Network Address
The name or network address of the instance of SQL Server to which to connect. The port number can be specified after the server name: server=tcp:servername, portnumber. When specifying a local instance, always use (local). To force a protocol, add one of the following prefixes: np:(local), tcp:(local), lpc:(local)

ADO.NET 2.0 does not support asynchronous commands over shared memory for SQL Server 2000 or earlier. However, you can force the use of TCP instead of shared memory, either by prefixing tcp: to the server name in the connection string, or by using localhost.
Encrypt 'false' When true, SQL Server uses SSL encryption for all data sent between the client and server if the server has a certificate installed. Recognized values are true, false, yes, and no.
Enlist 'true' When true, the pooler automatically enlists the connection in the creation thread's current transaction context. Recognized values are true, false, yes, and no.
Failover Partner N/A The name of the failover partner server where database mirroring is configured. The Failover Partner keyword is not supported by .NET Framework version 1.0 or 1.1.
Initial Catalog
-or-
Database
The name of the database.
Load Balance Timeout 0 The minimum time, in seconds, for the connection to live in the connection pool before being destroyed.
MultipleActiveResultSets 'false' When true, an application can maintain multiple active result sets (MARS). When false, an application must process or cancel all result sets from one batch before it can execute any other batch on that connection. Recognized values are true and false. The keyword is not supported by .NET Framework version 1.0 or 1.1.
Integrated Security
-or-
Trusted_Connection
'false' Whether the connection is to be a secure connection or not. Recognized values are 'true', 'false', and 'sspi', which is equivalent to 'true'.
Max Pool Size 100 The maximum number of connections allowed in the pool.
Min Pool Size 0 The minimum number of connections allowed in the pool.
Network Library
-or-
Net
'dbmssocn' The network library used to establish a connection to an instance of SQL Server. Supported values include dbnmpntw (Named Pipes), dbmsrpcn (Multiprotocol, Windows RPC), dbmsadsn (Apple Talk), dbmsgnet (VIA), dbmslpcn (Shared Memory, local machine only) and dbmsspxn (IPX/SPX), dbmssocn (TCP/IP) and Dbmsvinn (Banyan Vines).
The corresponding network DLL must be installed on the system to which you connect. If you do not specify a network and you use a local server (for example, "." or "(local)"), shared memory is used.
Packet Size 8192 Size in bytes of the network packets used to communicate with an instance of SQL Server.
Password
-or-
Pwd
The password for the SQL Server account logging on. Not used with (the strongly recommended) 'Integrated Security=true' option.
Persist Security Info 'false' When set to 'false' (strongly recommended), security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. Resetting the connection string resets all connection string values including the password.
Pooling 'true' When true, the SQLConnection object is drawn from the appropriate pool, or if necessary, is created and added to the appropriate pool. Recognized values are true, false, yes, and no.
Replication 'false' true if replication is supported using the connection.
Transaction Binding Implicit Unbind Controls connection association with an enlisted System.Transactions transaction. Possible values are:
Transaction Binding=Implicit Unbind;
Transaction Binding=Explicit Unbind;
Implicit Unbind causes the connection to detach from the transaction when it ends. After detaching, additional requests on the connection are performed in autocommit mode. The System.Transactions.Transaction.Current property is not checked when executing requests while the transaction is active. After the transaction has ended, additional requests are performed in autocommit mode.
Explicit Unbind causes the connection to remain attached to the transaction until the connection is closed or an explicit SqlConnection.TransactionEnlist(null) is called. An InvalidOperationException is thrown if Transaction.Current is not the enlisted transaction or if the enlisted transaction is not active.
TrustServerCertificate 'false' When set to true, SSL is used to encrypt the channel when bypassing walking the certificate chain to validate trust. If TrustServerCertificate is set to true and Encrypt is set to false, the channel is not encrypted. Recognized values are true, false, yes, and no.
Type System Version N/A A string value that indicates the type system the application expects. Possible values are:
Type System Version=SQL Server 2000;
Type System Version=SQL Server 2005;
Type System Version=SQL Server 2008;
Type System Version=Latest;
When set to SQL Server 2000, the SQL Server 2000 type system is used. The following conversions are performed when connecting to a SQL Server 2005 instance:
XML to NTEXT
UDT to VARBINARY
VARCHAR(MAX), NVARCHAR(MAX) and VARBINARY(MAX) to TEXT, NEXT and IMAGE respectively.
When set to SQL Server 2005, the SQL Server 2005 type system is used. No conversions are made for the current version of ADO.NET.
When set to Latest, the latest version than this client-server pair can handle is used. This will automatically move forward as the client and server components are upgraded.
User ID The SQL Server login account.
User Instance 'false' A value that indicates whether to redirect the connection from the default SQL Server Express instance to a runtime-initiated instance running under the account of the caller.
Workstation ID The local computer name The name of the workstation connecting to SQL Server.

Summary

There is no point in always defining each of these properties. Return to this sheet to look up definitions as a way to ensure proper connections. Also use this as a reference to ensure that you have included every property applicable to your specific situation.

IP Addresses & Categories

IP address is the logical address to identify the device in network.

IP address are of two types
  1. IPv4
  2. IPv6
In IPv4 32bits are divided into four octates. Each octate is separed with dot(.) and its known as dotted decimal notation. Total 4.3 billion IP address are again divided into 5 classes i.e., is from Class A,B,C,D,E based on priority bits. Priority bits are most significant bits from most significant octates.
Class First octet range Priority bit Octet format Usage
A 0-127 0 N.H.H.H Large Networks
B 128-191 10 N.N.H.H Medium Networks
C 192-223 110 N.N.N.H Small Networks
D 224-239 1110 - Reserved for multicasting
E 240-255 1111 - Resrved for research and development
To calculate
Number of networks=2N-P
where N=number of network bits and P=number of priority bits

Number of Hosts=2H-2
where H=number of host bits

Network ID: Network ID is used for representing the network. It represents group of IP addresses. By default network ID contains 0 in the host portion.
First IP of the network is the network ID. ex: 192.168.1.0

Broadcast ID:
Broadcast ID is used for broadcasting the information to other IP addresses which is belongs to same network. By default broadcast contains 255 in the host portion.
Last IP address of the network is broadcast ID. ex: 192.168.1.255

Valid IP address: Valid IP addresses exit between network ID and broadcast ID
Ex:192.168.1.2

Public IP addresses:
Public IP addresses are the valid IP addresses which are routable over the internet. These IP addresses are not free of cost. Inorder to access them we have to purchase from Internet Service Providers(ISP).

Private IP addresses: Certain addresses from each class of the IP address are reserved for private networks. These addresses are called private IP address. These private IP addresses are not valid over the internet.

Private IP address from each class
Class A 10.0.0.0 - 10.255.255.255
Class B 172.16.0.0 - 172.31.255.255
Class C 192.168.0.0 - 192.168.255.255
Exclusion Range of IP address
  • 0.0.0.0 is completely excluded from IP address range. it is called global ip.

  • 127.x.x.x range of IP addresses are also excluded. It is called loopback addresses. It is used to check the compatability of Network Interface Card(NIC) with operating system as well as functionality of TCP/IP.
  • 255.255.255.255 is also excluded. It is called broadcast ID.
NOTE:
169.254.0.0 - 169.254.255.255 Special range ip address used for dynamic purposes when we are using Dynamic Host Control Protocol(DHCP) to assign ip addresses. If no ip addresses available or any network problem raises this special range ip addresses are asigned by DHCP server.

Friday 1 April 2011

Identifying control raising postback event

This should get you the control that caused the postback:
public static Control GetPostBackControl(Page page)
{
    Control control = null;
    string ctrlname = page.Request.Params.Get("__EVENTTARGET");
    if (ctrlname != null && ctrlname != string.Empty)
    {
        control = page.FindControl(ctrlname);
    }
    else
    {
        foreach (string ctl in page.Request.Form)
        {
            Control c = page.FindControl(ctl);
            if (c is Button || c is ImageButton)
            {
                control = c;
                break;
            }
        }
    }
    return control;
}

Read more about this on this page: http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx

List of Protocols and Their Port Numbers

Here are the List of Protocols and their Port Numbers along with registered and unregistered.

How to get Asp.net Control ClientID in external javascript file

Every asp.net developer knows that Every control which is running at server in asp.net application changes the id of the control while rendering into the browser. If it is an Internal script we can access using '<%=ConrolId.ClientID>'. But we cann't access like this in external javascript file.

Solution to access the Serverside control in External javascript file:

Step1:We need to declare two arrays; the first array will have the server IDs of the required controls, and the  second array will have the client IDs of the server controls in the same order.

Step2: Register these two arrays at the client side.

Step3:Now, create a JavaScript function which will accept the server ID and will compare the server ID with the available server IDs in the array and will give its position in the array. Then, the same function would return you the matching client ID from the same location in the client IDs array.

The code below shows the declaration of the array, and the declaration of the JavaScript function in the code-behind.
/* This is the method used to register the array
of the clientid's as well as the serverid's
Also this method registers the function GetClientId, which is used
to get the client id provided server id is supplied */

public void RenderJavaScriptArrayWithCliendIds(params Control[] wc)
{
if (wc.Length > 0)
{
StringBuilder arrClientIDValue = new StringBuilder();
StringBuilder arrServerIDValue = new StringBuilder();

// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;

// Now loop through the controls and build
//the client and server id's
for (int i = 0; i < wc.Length; i++)
{
arrClientIDValue.Append("\"" +
wc[i].ClientID + "\",");
arrServerIDValue.Append("\"" +
wc[i].ID + "\",");
}

// Register the array of client and server id to the client
cs.RegisterArrayDeclaration("MyClientID",
arrClientIDValue.ToString().
Remove(arrClientIDValue.ToString().Length - 1, 1));
cs.RegisterArrayDeclaration("MyServerID",
arrServerIDValue.ToString().
Remove(arrServerIDValue.ToString().Length - 1, 1));

// Now register the method GetClientId,
// used to get the client id of tthe control
cs.RegisterStartupScript(this.Page.GetType(), "key",
"\nfunction GetClientId(serverId)\n"+
"{\nfor(i=0; i<MyServerID.length; i++)" +
"\n{\nif ( MyServerID[i] == serverId )\n" +
"{\nreturn MyClientID[i];\nbreak;\n}\n}\n}", true);
}
}

Call the method in BasePage or BaseMaster which is accessible to all the pages
RenderJavaScriptArrayWithCliendIds(tbUserName[,tbpassword,.......]);

In the external javascript file if u want to get the clientid of tbUserName then call the javascript function as follows
var tbUserName=document.getElementById(GetClientId('tbUserName'));

This will solve any issue arising due to changes in the client IDs of controls placed inside a Master Page or Page.

List of ALL MimeTypes on the Planet, mapped to File Extensions

http://www.iana.org/assignments/media-types/ lists the "official" mime-types, but it doesn't prevent anyone making their own an not registering it with Inetenet Assigned Numbers Authority(IANA).

JavaScript fuction for ReplaceAll

The solution to replace all using javascript is as follows:
String.prototype.ReplaceAll = function(stringToFind,stringToReplace){

var temp = this;

var index = temp.indexOf(stringToFind);

while(index != -1){

temp = temp.replace(stringToFind,stringToReplace);

index = temp.indexOf(stringToFind);

}

return temp;

}

Javascript function for InitCaps

The following is the simple code for converting the given string in to the init caps using javascript
function initcaps( string ) {
/* The following  Regex Replace  will  Identify  First Character
from the Word and  makes  it to  Uppercase and remaining
text to lower case */
/* This function consider only Alphanumeric Not  any 
Special Characters.*/

string =string.replace( /(\b\w)([a-zA-Z0-9]+)/gi,
function(t,a,b) { return a.toUpperCase() + b.toLowerCase(); } );
return string;
}

Wednesday 23 March 2011

Export GridView to Excel

It is essential for end user to save the reports in a document which is portable.

The following steps are required to export gridview to microsoft excel

Step1: Override the method "VerifyRenderingInServerForm" in our code otherwise we will get an Error Control of type "GridView" must be placed inside of the form tag with runat="server". Even we are placing a gridview in form which is running at server becausing we are calling the method RendorControl() manualy. Syntax to override the method is as follow
public override void VerifyRenderingInServerForm(Control control)
{
//Confirms that an HtmlForm control is rendered for the 
//specified ASP.NET
//server control at run time.
}

Step2:Assign datasource to gridview and set the allowpaging and allowsorting properties to false.

Ex:
public void ReportToExcel(GridView gridView,String fileName)
{
gridView.AllowPaging = false;
gridView.AllowSorting = false;
gridView.DataSource = resultDataSet;
gridView.DataBind();
if (gridView != null && gridView.Rows.Count > 0)
{
PrepareGridViewForExport(gridView);
ExportGridView(fileName,gridView);
}
}

Step3: Prepare the gridview to export. This step is requied only if the control otherthan literal used in the gridview.(Ex: if we use EditTemplate)

Sample code to Prepare Gridview For Export is as follows
public static void PrepareGridViewForExport(Control gvcontrol)
{
for (int i = 0; i < gvcontrol.Controls.Count; i++)
{
Control current = gvcontrol.Controls[i];
if (current is LinkButton)
{
gvcontrol.Controls.Remove(current);
gvcontrol.Controls.AddAt(i,
 new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
gvcontrol.Controls.Remove(current);
gvcontrol.Controls.AddAt(i,
 new LiteralControl((current as ImageButton).
AlternateText));
}
else if (current is Image)
{
gvcontrol.Controls.Remove(current);
gvcontrol.Controls.AddAt(i
, new LiteralControl((current as Image).
AlternateText));
}
else if (current is HyperLink)
{
gvcontrol.Controls.Remove(current);
gvcontrol.Controls.AddAt(i,
 new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
gvcontrol.Controls.Remove(current);
gvcontrol.Controls.AddAt(i,
new LiteralControl((current as DropDownList).
SelectedItem.Text));
}
else if (current is CheckBox)
{
gvcontrol.Controls.Remove(current);
gvcontrol.Controls.AddAt(i,
new LiteralControl((current as CheckBox).Checked 
? "True": "False"));
}
else if (current is TextBox)
{
gvcontrol.Controls.Remove(current);
gvcontrol.Controls.AddAt(i,
new LiteralControl((current as TextBox).Text));
}
else if (current is HiddenField)
{
gvcontrol.Controls.Remove(current);
}
if (current.HasControls())
{
PrepareGridViewForExport(current);
}
}

Step4: Export Grid view to Excel By using HtmlTextWriter. There is one method in gridview i.e, RenderControl(Writer)
public static void ExportGridView(string fileName, GridView gv)
{

HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.
AddHeader("content-disposition",
string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType =
 "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}

Query to count total number of stored procedures,tables and Views in database

When you want to count the total number of stored procedures in your database

the solution is

select count(*) as 'total' from sysobjects where xtype='P'

Note: where xtype='p' for stored procedures

xtype='V' for views

xtype='U' for tables

Tuesday 22 March 2011

HOW TO: Control Authorization Permissions in an ASP.NET Application

Configure Access to a Specific File and Folder


  1. Set up forms-based authentication.For additional information, click the article numbers below to view the articles in the Microsoft Knowledge Base:

  2. Request any page in your application to be redirected to Logon.aspx automatically.
  3. In the Web.config file, type or paste the following code.This code grants all users access to the Default1.aspx page and the Subdir1 folder.
    <configuration>
    <system.web>
    <authentication mode="Forms" >
    <forms loginUrl="login.aspx" name=".ASPNETAUTH"
    protection="None" path="/" timeout="20" >
    </forms>
    </authentication>
    <!-- This section denies access to all files in this application
     except for those that you have not explicitly specified by using
    another setting. -->
    <authorization>
    <deny users="?" />
    </authorization>
    </system.web>
    <!-- This section gives the unauthenticated user access to
    the Default1.aspx page only. It is located in the same folder
    as this configuration file. -->
    <location path="default1.aspx">
    <system.web>
    <authorization>
    <allow users ="*" />
    </authorization>
    </system.web>
    </location>
    <!-- This section gives the unauthenticated user access
    to all of the files that are stored in the Subdir1 folder.  -->
    <location path="subdir1">
    <system.web>
    <authorization>
    <allow users ="*" />
    </authorization>
    </system.web>
    </location>
    </configuration>

    Users can open the Default1.aspx file or any other file saved in the Subdir1 folder in your application. They will not be redirected automatically to the Logon.aspx file for authentication.
  4. Repeat Step 3 to identify any other pages or folders for which you want to permit access by unauthenticated users.

How To Implement Forms-Based Authentication in Your ASP.NET Applicationby Using C#.NET

Authentication and authorization are important to our web application.

Configure the Security Settings in the Web.config File


This section demonstrates how to add and modify the <authentication> and <authorization> configuration sections to configure the ASP.NET application to use forms-based authentication.
  1. In Solution Explorer, open the Web.config file.
  2. Change the authentication mode to Forms.
  3. Insert the <Forms> tag, and fill the appropriate attributes. (For more information about these attributes, refer to the MSDN documentation or the QuickStart documentation that is listed in the REFERENCES section.) Copy the following code, and then click Paste as HTML on the Edit menu to paste the code in the <authentication> section of the file:


    <authentication mode="Forms">
    <forms name=".ASPXFORMSDEMO" loginUrl="logon.aspx"
    protection="All" path="/" timeout="30" >
    
    <credentials passwordFormat="Clear">
    <user name="ramp" password="password"/>
    </credentials>
    </forms>  
    
    </authentication>


  4. Deny access to the anonymous user in the <authorization> section as follows:


    <authorization>
    <deny users ="?" />
    <allow users = "*" />
    </authorization>



For more details refer this article

Export GridView to Pdf

Steps to export gridview to pdf:
  1. Download the Itextsharp.dll
  2. Add ItextSharp.dll reference to your project.
  3. the following is the sample code for export gridview to pdf
protected void ExportToPDF(GridView gvReport, bool LandScape)
{
int noOfColumns = 0, noOfRows = 0;
DataTable tbl = null; 

if (gvReport.AutoGenerateColumns)
{
// Gets the DataSource of the GridView Control.
tbl = gvReport.DataSource as DataTable;
noOfColumns = tbl.Columns.Count;
noOfRows = tbl.Rows.Count;
}
else
{
noOfColumns = gvReport.Columns.Count;
noOfRows = gvReport.Rows.Count;
}

float HeaderTextSize = 8;
float ReportNameSize = 10;
float ReportTextSize = 8;
float ApplicationNameSize = 7;

// Creates a PDF document

Document document = null;
if (LandScape == true)
{
// Sets the document to A4 size and rotates it so that the
//   orientation of the page is Landscape.
document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
}
else
{
document = new Document(PageSize.A4, 0, 0, 15, 5);
}

// Creates a PdfPTable with column count of the table equal to
// no of columns of the gridview or gridview datasource.
iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);

// Sets the first 4 rows of the table as the header
// rows which will be repeated in all the pages.
mainTable.HeaderRows = 4;

// Creates a PdfPTable with 2 columns to hold the header in the exported PDF.
iTextSharp.text.pdf.PdfPTable headerTable = new   iTextSharp.text.pdf.PdfPTable(2);

// Creates a phrase to hold the application name at the left hand side of the header.
Phrase phApplicationName = new Phrase("Sample Application", FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));

// Creates a PdfPCell which accepts a phrase as a parameter.
PdfPCell clApplicationName = new PdfPCell(phApplicationName);
// Sets the border of the cell to zero.
clApplicationName.Border = PdfPCell.NO_BORDER;
// Sets the Horizontal Alignment of the PdfPCell to left.
clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;

// Creates a phrase to show the current date at the right hand side of the header.
Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"),
FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));

// Creates a PdfPCell which accepts the date phrase as a parameter.
PdfPCell clDate = new PdfPCell(phDate);
// Sets the Horizontal Alignment of the PdfPCell to right.
clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
// Sets the border of the cell to zero.
clDate.Border = PdfPCell.NO_BORDER;

// Adds the cell which holds the application name to the headerTable.
headerTable.AddCell(clApplicationName);
// Adds the cell which holds the date to the headerTable.
headerTable.AddCell(clDate);
// Sets the border of the headerTable to zero.
headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;

// Creates a PdfPCell that accepts the headerTable as
// a parameter and then adds that cell to the main PdfPTable.
PdfPCell cellHeader = new PdfPCell(headerTable);
cellHeader.Border = PdfPCell.NO_BORDER;
// Sets the column span of the header cell to noOfColumns.
cellHeader.Colspan = noOfColumns;
// Adds the above header cell to the table.
mainTable.AddCell(cellHeader);

// Creates a phrase which holds the file name.
Phrase phHeader = new Phrase("Sample Export",
FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
PdfPCell clHeader = new PdfPCell(phHeader);
clHeader.Colspan = noOfColumns;
clHeader.Border = PdfPCell.NO_BORDER;
clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
mainTable.AddCell(clHeader);

// Creates a phrase for a new line.
Phrase phSpace = new Phrase("\n");
PdfPCell clSpace = new PdfPCell(phSpace);
clSpace.Border = PdfPCell.NO_BORDER;
clSpace.Colspan = noOfColumns;
mainTable.AddCell(clSpace);

// Sets the gridview column names as table headers.
for (int i = 0; i < noOfColumns; i++)
{
Phrase ph = null;

if (gvReport.AutoGenerateColumns)
{
ph = new Phrase(tbl.Columns[i].ColumnName,
FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
}
else
{
ph = new Phrase(gvReport.Columns[i].HeaderText,
FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
}

mainTable.AddCell(ph);
}

// Reads the gridview rows and adds them to the mainTable
for (int rowNo = 0; rowNo < noOfRows; rowNo++)
{
for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
{
if (gvReport.AutoGenerateColumns)
{
string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
else
{
if (gvReport.Columns[columnNo] is TemplateField)
{
DataBoundLiteralControl lc = gvReport.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
string s = lc.Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
else
{
string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
}
}

// Tells the mainTable to complete the row even if any cell is left incomplete.
mainTable.CompleteRow();
}

// Gets the instance of the document created and writes it to
// the output stream of the Response object.
PdfWriter.GetInstance(document, Response.OutputStream);

// Creates a footer for the PDF document.
HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true);
pdfFooter.Alignment = Element.ALIGN_CENTER;
pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER;

// Sets the document footer to pdfFooter.
document.Footer = pdfFooter;
// Opens the document.
document.Open();
// Adds the mainTable to the document.
document.Add(mainTable);
// Closes the document.
document.Close();

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
Response.End();
}

How to Generate the Scripts for Table with data in sql server 2011

Steps requied to generate Script in MS-Sql Server 2011:

  1. Click on database. Right click on database and open context menu.Select Tasks > Generate Scripts... from displayed menu.

  2. Microsoft SQL Server 2011 Generate and Publish Scripts wizard is displayed. Click on Next buton.

  3. We are going to choose database objects that we want to create scripts for. If you want to script data of a single sql table, choose the "Select specific database objects" option. If you want to generate script for all database objects in the target database you can choose "Script entire database and all database objects". Click on Next button

  4. Next we will configure scripts in detail and save or publish options.If you want to display the generated data script in the SQL Server Management Studio Query Editor window.

  5. The most important configuration here in this screen is configuring the script wizard to script data. So please click Advanced buton. In the Advanced Scripting Options configuration screen, find Types of data to script parameter. The default selection is Schema only script type. In order to script data in table in SQL Server, you can either choose Data only script type or Schema and data script type.

  6. After you completed your advanced scripting options selection, click OK buton. Then click Next buton. Click Next buton if everything is correct. Or click Previous buton to reconfigure generate script data options.

  7. The Generate and Publish Scripts wizard, executes the task and displays each step and the result of the task execution.

  8. Click Finish buton to close the SQL Server 2011 generate script wizard.

How to Generate the Scripts for Table with data in sql server 2008

MS SQL Server 2008 has new Generate Scripts option which enables sql programmers
to script data in SQL Server database tables. SQL developers can script data
from sql tables into a script file, to the clipboard or script data on a new sql
query window. Script data can be used to export and/or import table data from
one database to another database.

The Script Data option creates INSERT
statements foreach row in the table using the column data that the related table
record has. Later than the scripted table data can be used by executing the
generated t-sql scripts, to create a copy of the original table on an other
server or an other database with identical data or identical rows on the
destination database or table.

SQL Server generate script with data is a powerful SQL Server tool in order to
create sql script to move data from one database to another database.

Script Data option is new with Microsoft SQL Server 2008. So on the Tasks
context menu of a database although the Generate Scripts... option exists, we
won't be able to find the Script Data options in the Choose Script Options
screen of the Script Wizard.

In this article, I want to demonstrate with a sample how a sql developer can use
the Generate Scripts task in order to script table data of a SQL Server 2008
database table.

Open the Generate Scripts SubMenu Item from Task Menu


First of all, open the Microsoft SQL Server Management Studio which is installed
from the Client Tools of a MS SQL Server 2008 installation package.

Connect to a MS SQL Server 2008 database instance using the Server Explorer or using the
Connect screen.

Then open the Object Explorer window and expand the Databases
node.

Here I connected to the local SQL Server 2008 instance and clicked over
the Databases node and a list of existing sql server databases are visible in
the object explorer window now. Later, I clicked the sql database MyWorks which
owns the tables that I want to script data, rows/records of the database.

Continue by right clicking on the database name and open the context menu,
chooes Tasks menu and open submenu. Select Generate Script submenu item from the
displated list.



Tasks menu - Generate Scripts...

Generate SQL Server Script Wizards


When you select the Generate Scripts sub menu item the Generate SQL Server
Scripts Wizard starts. SQL administrators and sql programmers can use the Script
Wizard to generate t-sql scripts as a t-sql scripter to create scripts for any
object (tables, views, schemas, etc). You can work in detail on the Script
Wizard and find useful hint that you can benefit in your sql developments.


Generate SQL Server Scripts Wizard

Select Database to Script


The first step in the Script Wizard is detemining the database to work on. You
can choose a sql database among the listed all sql databases existing on the sql
server instance.


Script Wizard - Select Database Option

Choose Script Options


Here is the screen where sql developers can configure the script details, and
where developers can shape the automatic generated script according to the
applications needs and requirements.

For our case, since we want to script table data which exists in the database
that I have selected in the previous steps, we should set the Script Data option
to True. You can see that the Script Data option is listed in the Table/View
Options sections on the Choose Script Options screen. Since default Script Data
option is set to false by default, we should alter this option in order to get
an Insert statement for each row in the database table.

Note : Set Script Data option to True


Script Wizard - Choose Script Options

Choose Object Types


This option in the Script Wizard is for the types of the objects we want the
script generator to build scripts for. Since we deal with database tables, we
will select Tables among the listed options such as Schema and User-defined
table types.


Script Wizard - Choose Object Types

Choose Tables


Since we selected Tables in the previous step, the wizard now displays all the
tables that exists in the selected sql database. Here as a developer, I make a
list of tables that I want to generate table data scripts for. For our sample
case, I only select one table.


Script Wizard - Choose Tables

Output Option


Output Option screen in the Generate Script Wizard is the screen where a sql
administrator or a programmer can make a selection among the existing output
options. The script generator can create the desired scripts in the forms of a
file, also can split the automatic generated script per object basis, or define
the file as a unicode file or in ANSI text. A database developer can also select
the file name and the output file folder for the script engine to create and
place the script file.

Other output options are script to clipboard, just like a Copy-Paste operation
and the last option is displaying the generated script on a new query window in
the Microsoft SQL Server Management Studio.

I selected the New Query Window option in order to display the generated script
by the MS SQL Server 2008.


Script Wizard - Output Options

Script Wizard Summary


Here is the last stop before proceeding to the script generation where database
programmers can see which options they have selected and can go back to previous
screen and make re-selections in the options for a desired script.


Script Wizard Summary

Generate Script Progress


Generate Script Progress screen displays the status of the scripting operation.
If an error occurs sql developers and administrators can find the error details
on this screen. If everything runs without any error and does not fail, you will
see Success status for each scripting action on the progress screen.


Generate Script Progress

Data Script on the Query Window


Since as the output option for the scripting, the New Query Window is selected,
the final script is displayed on the SQL Server Management Studio Query Editor
window as shown below.

This script is formed of a CREATE TABLE script for the source table and
following that, INSERT statements for each row in the selected source table.

As you see, any sql developer or any database administrator can use the below
script to create a copy of any sql database tables with their data on another
sql database or an other sql server instance.


Sample Output to New Query Windows for Scripting Table Data

How to Generate the Scripts for Table with data in sql server 2005

This is the problem I faced when I want to change the schema and adding a new column to table which has lot of records. while adding a column it is showing timeout. I deleted the data from the table and added the column. But i want to insert the same data which has before delete.  Then I get a question that How i can generate scripts along with data in Sql Server 2005?. The sql server 2005 doesnot have generate script along with data facility.

Solution for SQL SERVER – 2005 – Create Script to Copy Database Schema and All The Objects – Stored Procedure, Functions, Triggers, Tables, Views, Constraints and All Other Database Objects:

  1. First of all install Database Publishing Wizard from here : Download Database Publishing Wizard. It will be installed at following location : C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\

  2. Now  goto Command prompt and run following command on any desire database, it will create the script at your specified location. Script will have schema as well as data which can be used to create the same information on new server.


Examples:

Command to run which will create schema and database:
C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz script -d AdventureWorks “C:\AdventureWorks.sql”

Command to run which will create schema:
C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz script -d AdventureWorks “C:\AdventureWorks.sql” -schemaonly

Command to run which will create data:
C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz script -d AdventureWorks “C:\AdventureWorks.sql” -dataonly

Note: I suggest that you try this on smaller database of size around 100MB.

Reference : Database Publishing Wizard

Jquery making synchronous Ajax call

Difference between Synchronous and Asynchronous
  • Synchronous is where the script stops and waits for the server to send back a reply before continuing
  • Asynchronous is where the script allows the page to continue to be processed and will handle the reply if and when it arrives.
$.ajax({
type: "POST",
url: "url of the page",
processData: false,
success: function(msg) {alert("success")},
async:false 
});
If you see the last line, the attribute declaration async:false which is the key for the telling the Jquery client proxy to make asynchronous call or not. If it is true then asynchronous otherwise synchronous. By default it is asynchronous.