Wednesday, January 6, 2010

Hey here's is a simple example of invoking a function in a different thread
Deployment.Current.Dispatcher.BeginInvoke(
{
HelloWorld();
});
private void HelloWorld()
{
//Your code goes here
}

Wednesday, March 4, 2009

Encoding and Decoding string Values in Silverlight

Silverlight allows us to Encode and Decode string values which can be used when we pass the values between Javascript functions or between two xap files in the same browser.

To Encode a string use the following code

byte[] bt = Encoding.UTF8.GetBytes("This is a Encoded String");
string encodedData = Convert.ToBase64String(bt);

Where encodedData will be the Encoded string.


To decode the Encoded String use the following code

byte[] decbuff = Convert.FromBase64String(encodedData);
string decodedData = Encoding.UTF8.GetString(decbuff, 0, decbuff.Length);

Where
decodedData will be the Decoded string.

Tuesday, August 5, 2008

Isolated Storage

Isolated Storage

When an application stores data in a file, the file name and storage location must be carefully chosen to minimize the possibility that the storage location will be known to another application and, therefore, vulnerable to corruption. Without a standard system in place to manage these problems, developing ad hoc techniques that minimize storage conflicts can be complex and the results can be unreliable.

With isolated storage, data is always isolated by user and by assembly. Credentials such as the origin or the strong name of the assembly determine assembly identity. Data can also be isolated by application domain, using similar credentials.

Administrators can limit how much isolated storage an application or a user has available, based on an appropriate trust level. In addition, administrators can remove all a user's persisted data. To create or access isolated storage, code must be granted the appropriate IsolatedStorageFilePermission.

System.IO.IsolatedStorage Namespace

The System.IO.IsolatedStorage namespace contains types that allow the creation and use of isolated stores. With these stores, you can read and write data that less trusted code cannot access and prevent the exposure of sensitive information that can be saved elsewhere on the file system. Data is stored in compartments that are isolated by the current user and by the assembly in which the code exists. Additionally, data can be isolated by domain. Roaming profiles can be used in conjunction with isolated storage so isolated stores will travel with the user's profile. The IsolatedStorageScope enumeration indicates different types of isolation. For more information about when to use isolated storage, see Performing Isolated Storage Tasks.

The IsolatedStorageFile class provides most of the necessary functionality for isolated storage. Use this class to obtain, delete and manage isolated storage. The IsolatedStorageFileStream class handles reading and writing files to a store. This is similar to reading and writing in standard File I/O classes. For more information about I/O, see the System.IO namespace.

Writing and reading – IsolatedStorage

Write

public void StoreDataIsolated(string strFilename, string strStoreValue)

{

using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())

{

using (IsolatedStorageFileStream isoStream =

new IsolatedStorageFileStream(strFilename, FileMode.Create, isoFile))

{

using (StreamWriter sw = new StreamWriter(isoStream))

{

sw.Write(strStoreValue);

}

}

}

}

Read

public string ReadDataIsolated(string strFilename)

{

string strRetValue = "";

using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())

{

using (IsolatedStorageFileStream isoStream =

new IsolatedStorageFileStream(strFilename, FileMode.OpenOrCreate, isoFile))

{

using (StreamReader sw = new StreamReader(isoStream))

{

strRetValue = sw.ReadToEnd();

}

}

}

return strRetValue;

}

Wednesday, June 25, 2008

How to build a Sharepoint Silverlight Beta 2 Webtart?

How to build a Sharepoint Silverlight Beta 2 Webtart?

If anyone is in need of the above topic pls add your comments.

Tuesday, June 10, 2008

How can I connect to the database in Silverlight project? (VS 2008 Beta 2)

Silverlight applications behave like a client side application. So we willnot be able to connect to the DB on the server from the silverlight application as the application and DB are on different layers.
So how do we access DB from Silverlight?
There are different ways to access DB from Silverlight application.
i) Webservices
ii) WCF Service
iii) A normal ASPX page.
In the 1st and 2nd methods the code can be of the same type. A sample service code is as follows

[WebMethod]public string RetrieveTexture()
{
try
{
MySqlConnection _mysqlConnection = new MySqlConnection();_mysqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["mySqlConnection"].ToString();
_mysqlConnection.Open();
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = new MySqlCommand("SELECT * FROM myTablename LIMIT 0, 20", _mysqlConnection);DataSet ds = new DataSet();
da.Fill(ds);
StringBuilder sb = new StringBuilder();
sb.Append("");
sb.Append("");
foreach (DataRow dr in ds.Tables[0].Rows)
{
sb.Append("");sb.Append("");
sb.Append(dr[0].ToString());
sb.Append("
");
sb.Append("");
sb.Append(dr[1].ToString());
sb.Append("
");sb.Append("");
sb.Append(dr[4].ToString());
sb.Append("
");
sb.Append("");
sb.Append(dr[5].ToString());
sb.Append("
");sb.Append("
");
}
sb.Append("
");
_mysqlConnection.Close();
return sb.ToString();
}
catch (Exception ex)
{
return string.Empty;
}
C# Code:----------------------------------------------------------------------------------------------------public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
Loaded += new RoutedEventHandler(UserControl_Loaded);
}
void UserControl_Loaded(object sender, RoutedEventArgs e)
{
BasicHttpBinding bind = new BasicHttpBinding();
bind.MaxReceivedMessageSize = 2147483647;
bind.MaxBufferSize = 2147483647;
EndpointAddress endpoint = new EndpointAddress("http://localhost:51103/serviceTest_Web/myService.asmx");theSercice.myServiceSoapClient textureSoapClient = new serviceTest.theSercice.myServiceSoapClient(bind, endpoint);
textureSoapClient.RetrieveTextureAsync();
textureSoapClient.RetrieveTextureCompleted +=
new EventHandler(textureSoapClient_RetrieveTextureCompleted);
}

void textureSoapClient_RetrieveTextureCompleted(object sender, serviceTest.theSercice.RetrieveTextureCompletedEventArgs e)
{
if (e.Error == null)
displayData(e.Result);
}
void displayData(string xmlContent)
{
try
{
if (xmlContent != string.Empty)
{
XDocument xmlProducts = XDocument.Parse(xmlContent);
var textures = from texture in xmlProducts.Descendants("Texture")
select new
{
itemId = (string)texture.Element("item").Value.PadLeft(10, '0'),
txArtist = (string)texture.Element("Artist").Value.PadLeft(10, '0'),
txPath = (string)"http://www.texturearchive.com/thumbs/" + texture.Element("class1").Value + "/" + texture.Element("class2").Value + "/" + texture.Element("item").Value.PadLeft(10, '0') + "_" + texture.Element("Artist").Value.PadLeft(10, '0') + "_tn.jpg"
};
//Bug: http://silverlight.net/forums/t/11147.aspx
List texturesList = new List();foreach (var t in textures)
{
Texture pdt = new Texture { itemId = t.itemId, txArtist = t.txArtist, txPath = t.txPath };
texturesList.Add(pdt);
}
texturesDataGrid.ItemsSource = texturesList;
}
else
{
//errMessage.Visibility = Visibility.Visible;
texturesDataGrid.ItemsSource = null;
}
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
public class Texture
{
public string itemId { get; set; }
public string txArtist { get; set; }
public string txclass1 { get; set; }
public string txclass2 { get; set; }
public string txPath { get; set; }
}

This same logic can be acheved from a ASPX page which will render the above output in XML format.
For Example the ASPX page should have the following code in the page load event
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "text/xml";
Response.Write(“Any XML String”);
Response.End();
}

Saturday, May 24, 2008

.NET Programming Standards and Naming Conventions

Common .NET Naming Conventions

These are the industry-accepted standard naming conventions for J#, C# and VB.NET programs. For additional information, please see the MSDN help documentation and FX Cop. While individual naming conventions at organizations may vary (Microsoft only suggests conventions for public and protected items), the list below is quickly becoming the de-facto standard in the industry. Please note the absence of Hungarian Notation except in visual controls. These naming standards should find their way into all of your .NET development, including ASP.NET Web applications and .NET Windows Forms applications.

Note that while this document predates the online and printed standards documentation from Microsoft, everything below which indicates it is based on .NET library standards is consistent with that documentation. In areas where Microsoft has not provided guidance (Microsoft generally doesn't care what you do in private/non-exposed code. In fact, they aren't even consistant in their internal code in the .NET framework), de facto standards have emerged, and I have captured them here.

The "ux" naming convention for controls is something I have added and found to be helpful. It is not based on any official standards, but instead based upon a multitude of projects by my teams and others, as well as on-line discussions on the topic. While I strongly recommend that you follow Microsoft guidelines when present, I encourage you to try out the items marked as extensions below and see how they work for you before committing to them.






Type

Standard / Convention

Example


Namespaces


Standard Based Upon Microsoft .NET Library Standards



Pascal Case, no underscores. Use CompanyName.TechnologyName as root. If you don't
have a company, use your domain name or your own initials. Note that any acronyms
of three or more letters should be pascal case (Xml instead of XML) instead of all
caps.



Why: This convention is consistent with the .NET Framework and is easy to read.



AppliedIS.TimeCard.BusinessRules

IrritatedVowel.Controllers

PeteBrown.DotNetTraining.InheritanceDemo PeteBrown.DotNetTraining.Xml





Assemblies


Standard Based Upon Microsoft .NET Library Standards



If the assembly contains a single name space, or has an entire self-contained root
namespace, name the assembly the same name as the namespace.



Why: This convention is consistent with the .NET Framework and is easy to read.
More importantly, however, it keeps your assembly names and namespaces lined up,
making it really easy to figure out what is any particular assembly, and what assembly
you need to reference for any given class.




AppliedIS.TimeCard.BusinessRules.dll

IrritatedVowel.Controllers.dll








Classes and Structs


Standard Based Upon Microsoft .NET Library Standards



Pascal Case, no underscores or leading "C" or "cls". Classes may begin with an "I"
only if the letter following the I is not capitalized, otherwise it looks like an
Interface. Classes should not have the same name as the namespace in which they
reside. Any acronyms of three or more letters should be pascal case, not all caps.
Try to avoid abbreviations, and try to always use nouns.



Why: This convention is consistent with the .NET Framework and is easy to read.




Widget

InstanceManager

XmlDocument

MainForm

DocumentForm

HeaderControl

CustomerListDataSet (typed dataset)







Collection Classes


Standard Based Upon Microsoft .NET Library Standards



Follow class naming conventions, but add Collection to the end of the name



Why: This convention is consistent with the .NET Framework and is easy to read.



WidgetCollection






Delegate Classes


Standard Based Upon Microsoft .NET Library Standards



Follow class naming conventions, but add Delegate to the end of the name



Why: This convention is consistent with the .NET Framework and is easy to read.



WidgetCallbackDelegate






Exception Classes


Standard Based Upon Microsoft .NET Library Standards



Follow class naming conventions, but add Exception to the end of the name



Why: This convention is consistent with the .NET Framework and is easy to read.



InvalidTransactionException






Attribute Classes


Standard Based Upon Microsoft .NET Library Standards



Follow class naming conventions, but add Attribute to the end of the name



Why: This convention is consistent with the .NET Framework and is easy to read.



WebServiceAttribute






Interfaces


Standard Based Upon Microsoft .NET Library Standards



Follow class naming conventions, but start the name with "I" and capitalize the
letter following the "I"



Why: This convention is consistent with the .NET Framework and is easy to read.
It also distinguishes classes from interfaces, where (unlike in VB6) are truly different
beings. This avoid name collisions as well, as it is quite common to have IFoo and
a class named Foo that implements IFoo.



IWidget






Enumerations


Standard Based Upon Microsoft .NET Library Standards



Follow class naming conventions. Do not add "Enum" to the end of the enumeration
name. If the enumeration represents a set of bitwise flags, end the name with a
plural.



Why: This convention is consistent with the .NET Framework and is easy to read.




SearchOptions (bitwise flags)



AcceptRejectRule (normal enum)








Functions and Subs


Standard Based Upon Microsoft .NET Library Standards



Pascal Case, no underscores except in the event handlers. Try to avoid abbreviations.
Many programmers have a nasty habit of overly abbreviating everything. This should
be discouraged.



Functions and subs must differ by more than case to be usable from case-insensitive
languages like Visual Basic .NET



Why: This convention is consistent with the .NET Framework and is easy to read.




VB: Public Sub DoSomething(...)



C#: public void DoSomething(...)








Properties and Public * Member Variables


Standard Based Upon Microsoft .NET Library Standards



Pascal Case, no underscores. Try to avoid abbreviations. Members must differ by
more than case to be usable from case-insensitive languages like Visual Basic .NET.



Why: This convention is consistent with the .NET Framework and is easy to read.




VB: Public Property RecordID As Integer



C#: public int RecordID








Parameters


Standard Based Upon Microsoft .NET Library Standards



Camel Case. Try to avoid abbreviations. Parameters must differ by more than case
to be usable from case-insensitive languages like Visual Basic .NET.



Why: This convention is consistent with the .NET Framework and is easy to read.




VB: ByRef recordID As Integer



C#: ref int recordID








Procedure-Level Variables


Standard Based Upon De facto Industry-Accepted Practices



Camel Case



Why: This convention is consistent with the .NET Framework and is easy to read.
It also avoids naming collisions with class-level variables (see below)




VB: Dim recordID As Integer



C#: int recordID ;








Class-Level Private and Protected Variables


Standard Based Upon De facto Industry-Accepted Practices



Camel Case with Leading Underscore. In VB.NET, always indicate "Protected" or "Private",
do not use "Dim". Use of "m_" is discouraged, as is use of a variable name that
differs from the property by only case, especially with protected variables as that
violates compliance, and will make your life a pain if you program in VB.NET, as
you would have to name your members something different from the accessor/mutator
properties.



Of all the items here, the leading underscore is really the only controversial one.
I personally prefer it over straight underscore-less camel case for my private variables
so that I don't have to qualify variable names with "this." to distinguish from
parameters in constructors or elsewhere where I likely will have a naming collision.
With VB.NET's case insensitivity, this is even more important as your accessor properties
will usually have the same name as your private member variables except for the
underscore.



As far as m_ goes, it is really just about aesthetics. I (and many others) find
m_ ugly, as it looks like there is a hole in the variable name. It's almost offensive.
I used to use it in VB6 all the time, but that was only because variables could
not have a leading underscore. I couldn't be happier to see it go away.



Microsoft recommends against the m_ (and the straight _) even though they did both
in their code. Also, prefixing with a straight "m" is right out. Of course, since
they code mainly in C#, they can have private members that differ only in case from
the properties. VB folks have to do something else. Rather than try and come up
with language-by-language special cases, I recommend the leading underscore for
all languages that will support it.



If I want my class to be fully CLS-compliant, I could leave off the prefix on any
C# protected member variables. In practice, however, I never worry about this as
I keep all potentially protected member variables private, and supply protected
accessors and mutators instead.



Why: In a nutshell, this convention is simple (one character), easy to read (your
eye is not distracted by other leading characters), and successfully avoids naming
collisions with procedure-level variables and class-level properties.




VB: Private _recordID As Integer



C#: private int _recordID ;








Controls on Forms


An Extension to the Standards



In recent projects (since 2002 or so), I have taken to a single prefix for all my
UI controls. I typically use "ux" (I used to use "ui", but it wasn't set apart well
in intellisense). "ux" comes from my usual design abbreviations where it means "User
eXperience", which has also since become a popular acronym. I have found this to
be extremely helpful in that I get the desired grouping in the intellisense even
better than if I use "txt", "lbl" etc. It also allows you to change combo boxes
to text boxes etc. without having to change the names - something that happens often
during initial prototyping, or when programming using highly iterative agile/xp
methodologies.



Why: This convention avoids problems with changing control types (textboxes to drop-down
lists, or simple text box to some uber textbox, or text box to date picker, for
example), and groups the items together in intellisense. It is also much shorter
than most Hungarian conventions, and definitely shorter and less type-dependent
than appending the control type to the end of the variable name. I will use generic
suffixes which allow me enough freedom to change them around.




"ux" prefix



uxUserID, uxHeader, uxPatientDateOfBirth, uxSubmit







Constants


Standard Based Upon Microsoft .NET Library Standards



Same naming conventions as public/private member variables or procedure variables
of the same scope. If exposed publicly from a class, use PascalCase. If private
to a function/sub, use camelCase..



Do not use SCREAMING_CAPS



Why: This convention is consistent with the .NET Framework and is easy to read.
A sizable section of the Framework Design Guidelines is dedicated to why they chose
not to go the SCREAMING_CAPS route. Using SCREAMING_CAPS also exposes more of the
implementation than is necessary. Why should a consumer need to know if you have
an enum, or (perhaps because they are strings) a class exposing public constants?
In the end, you often want to treat them the same way, and black-box the implementation.
This convention satisfies that criteria.




SomeClass.SomePublicConstant



localConstant



_privateClassScopedConstant



Use the Network Service Account to Access Resources in ASP.NET

This How To shows you how you can use the NT AUTHORITY\Network
Service machine account to access local and network resources. By default on
Windows Server 2003, ASP.NET applications run using this account's identity. It
is a least privileged account with limited user rights and permissions. It does
have network credentials. This means that you can use it to authenticate against
network resources in a domain. This How To describes how you can use the Network
Service account to access server resources such as the Windows event log,
Windows registry, file system, and local and remote SQL Server databases.


By default, Microsoft Internet Information Services (IIS) 6.0 on Windows Server 2003 runs ASP.NET applications in application pools that use the NT AUTHORITY\Network Service account identity. This account is a least privileged machine account with limited permissions. An application that runs using this account has restricted access to the event log, registry, and file system. The account does have network credentials, which means you can use it to access network resources and remote databases by using Windows authentication. The network resources must be in the same domain as your Web server or in a trusted domain.

In some scenarios, using a custom domain service account is a better approach than using the Network Service account. You should use a custom domain service account if:

  • You want to isolate multiple applications on a single server from one another.
  • You need different access controls for each application on local and remote resources. For example, other applications cannot access your application's databases if access is restricted to your application's account.
  • You want to use Windows auditing to track the activity of each application separately.
  • You want to prevent any accidental or deliberate changes to the access controls or permissions associated with the general purpose Network Service account from affecting your application.

This How To shows you how you can use the Network Service account to access a variety of resources types including the event log, registry, file system, and databases.

Event Log Access

Applications that run using the Network Service identity can write to the event log by using existing event sources, but they cannot create new event sources because of insufficient registry permissions. When you use the EventLog.Write method, if the specified event source does not exist, this method attempts to create the event source and a security exception is generated.

Note : It is useful to use application specific event sources so that your application's events can easily be differentiated from other applications' events.

To enable your ASP.NET application to write to the event log using an event source that does not already exist, you have two options:

  • Create new event sources at application install time
  • Manually create new event source entry in the registry.

Creating a New Event Source at Install Time

With this option, you create a specialized installer class that you run by using the install utility to create a new event source at install time when administrator privileges are available. You run the install utility using an administrator account so it has permission to create the new event source.

To create an installer class to create event sources

  1. Use Visual Studio .NET 2005 to create a class library project named InstallerClass.dll. Add a reference of System.Configuration.Install to the InstallerClass project.
  2. Name the class CustomEventLogInstaller, and derive it from System.Configuration.Install.Installer.
  3. Set the RunInstaller attribute for the class to true.
  4. Create a System.Diagnostics.EventLogInstaller instance for each new event log your application needs, and call Installers.Add to add the instance to your project installer class. The following sample class adds one new event source named customLog to the Application Event Log.

using System;
using System.Configuration.Install;
using System.Diagnostics;
using System.ComponentModel;
[RunInstaller(true)]
public class CustomEventLogInstaller: Installer
{
private EventLogInstaller customEventLogInstaller;
public CustomEventLogInstaller()
{
// Create an instance of 'EventLogInstaller'.
customEventLogInstaller = new EventLogInstaller();
// Set the 'Source' of the event log, to be created.
customEventLogInstaller.Source = "customLog";
// Set the 'Event Log' that the source is created in.
customEventLogInstaller.Log = "Application";
// Add myEventLogInstaller to 'InstallerCollection'.
Installers.Add(customEventLogInstaller);
}
public static void Main()
{
}
}

5. Compile the code for the InstallerClass.dll library.
6. Use an account with administrative privileges to run the InstallUtil.exe utility, supplying the name of
the DLL on the command line. For example, open the Visual Studio command prompt and enter the following command.

InstallUtil.exe \InstallerClass.dll

When the install utility is called with the installer class, it examines the RunInstallerAttribute. If this is true, the utility installs all the items in the Installers collection. This creates the specified event sources for your ASP.NET application.

Manually Creating New Event Source Entry in the Registry

If you are unable to create a event source at installation time, and you are in deployment, the administrator should manually create a new event source entry beneath the following registry key

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\

To manually create a new event source entry beneath this registry key

  1. Start the Registry Editor tool Regedit.exe.
  2. Using the Application Event log, expand the outline list in the left panel to locate the following registry subkey: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application
  3. Right-click the Application subkey, point to New, and then click Key.
  4. Type a new event source name for the key name and press Enter.

The Network Service account can use the new event source for writing events.

Note You should not grant write permission to the ASP.NET process account (or any impersonated account if your application uses impersonation) on the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\ registry key. If you allow write access to this key and the account is compromised, the attacker can modify any log-related setting, including access control to the log, for any log on the system.

Health Monitoring

ASP.NET version 2.0 health monitoring writes to the Windows application event log to report significant lifetime and security events, if configured to do so. You can raise custom events in your code to write to the event log by using ASP.NET health monitoring. This approach does not use EventLog.WriteEntry, but you are restricted to using a predefined event source. For more information about health monitoring, see How To: Use Health Monitoring in ASP.NET 2.0.

Registry Access

The Network Service account does not have write access to the registry. If your application needs to write to the registry, you must configure the necessary access control lists (ACLs) on the required registry keys.

Granting Registry Access to Network Service

In the following example, an application needs to change and display the name of the Internet time server that Windows is automatically synchronized with. An operator can change this setting by using the Internet Time tab from the Date and Time item in the Control Panel.

Your application needs to modify the following registry key: HKLM\SOFTWARE\ Microsoft\Windows\CurrentVersion\DateTime\Servers

To allow the Network Service account write access to the preceding registry key

You need to use an administrator account with permission to alter the registry security to perform the following steps:


  1. On the taskbar, click Start, and then click Run. Type regedit in the Open box, and then click OK.
  2. Expand the outline list in the left panel to locate the DateTime folder icon at the preceding registry path.
  3. Right-click the DateTime folder, and then click Permissions.
  4. In the Permission for Servers dialog box, click the Add button.
  5. In the Select Users, Computers, or Groups dialog box, type NETWORK SERVICE in the text box, and then click Check Names. The Network Service name will be underlined; this indicates that it is a valid security principal. Click OK.
  6. In the Permissions for Servers dialog box, click the Network Service user name from the list, and in the Permissions for NETWORK SERVICE section, click Advanced.
  7. In the Advanced Security Settings for Servers dialog box, click Network Service, and then click Edit.
  8. In the Permission Entry for Servers dialog box, select the Set Value and Create Subkey check boxes in the Allow column to permit write access. Click OK several times until the Permissions dialog box closes.

Note You should be careful while editing the registry because any mistake can lead to system instability.

Your ASP.NET application could now use code similar to the following sample to change and display the name of the Internet time server.

using Microsoft.Win32;
...
protected void Button1_Click(object sender, EventArgs e)
{
//change the time server
RegistryKey rk = Registry.LocalMachine.OpenSubKey(
@"SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers",
true); //writable - this will fail without proper access
string sDefault = (String)rk.GetValue("");
int iDefault = Convert.ToInt32(sDefault);
//this an array of all the server names
string[] sServers = rk.GetValueNames();
//requires enumerate sub keys
iDefault++; if (iDefault >= sServers.Length)
iDefault=1; rk.SetValue("", iDefault.ToString());
// update display
Response.write(rk.GetValue(sServers[iDefault]).ToString());
}

File Access

The Network Service account has Read and Execute permissions on the IIS server root folder by default. The IIS server root folder is named Wwwroot. This means that an ASP.NET application deployed inside the root folder already has Read and Execute permissions to its application folders. However, if your ASP.NET application needs to use files or folders in other locations, you must specifically enable access.

Granting File Access to Network Service

To provide access to an ASP.NET application running as Network Service, you must grant access to the Network Service account.

To grant read, write, and modify permissions to a specific file


  1. In Windows Explorer, locate and select the required file.
  2. Right-click the file, and then click Properties.
  3. In the Properties dialog box, click the Security tab.
  4. On the Security tab, examine the list of users. If the Network Service account is not listed, add it.
  5. In the Properties dialog box, click the Network Service user name, and in the Permissions for NETWORK SERVICE section, select the Read, Write, and Modify permissions.
  6. Click Apply, and then click OK.

Your ASP.NET application can now write to the specified file.

Note If you need to allow the same level of access to a file resource for all accounts that run ASP.NET applications (Network Service or a custom service account), you can grant access to the IIS_WPG group instead of specifically to the Network Service account. Any account used to run ASP.NET is required to be a member of the IIS_WPG group.

For more information about creating a custom account to run an ASP.NET application, see How To: Create a Service Account for an ASP.NET 2.0 Application.

SQL Server

ASP.NET applications should use Windows authentication while connecting to a database. By using Windows authentication, you avoid storing database credentials in connection strings and you avoid passing passwords over the network to the database server.
With Windows authentication, your application's process account is used by default for authentication. To be able to access a database, your account requires:

  • A SQL Server login on the database server.
  • Permissions to the required objects (for example, stored procedures, views, or tables) in the required database.

Granting Access to a Local SQL Server
When the SQL Server is on the Web server, you must create a database login for the NT AUTHORITY\Network Service account.


To access a local SQL Server database using Network Service

  1. Start SQL Server Enterprise Manager.
  2. Expand the folders in the left panel and locate the Security folder for your local SQL Server.
  3. Right-click Logins in the Security folder, and then click New Login.
  4. In the SQL Server Login Properties - New Login dialog box, in the Name box, enter NT AUTHORITY\NETWORK SERVICE. Accept the defaults for the other settings, and then click OK.
  5. Expand the Databases folders, and then expand the Pubs (or equivalent) database.
  6. Right-click Users, and then click New Database User.
  7. In the Database User Properties - New User dialog box, select the NT AUTHORITY\NETWORK SERVICE account.
  8. In the Permit in Database Role list, select the db_datareader check box.
  9. Click OK, and then close the SQL Server Enterprise Manager.


The Network Service account now has permission to read the data in the tables of the designated database.

In practice, your application's requirements may be more complex. For example, you might want to allow read access to certain tables and allow update access to others. The recommended approach to help mitigate the risk posed by SQL injection is to grant execute permissions to the Network Service account on a selected set of stored procedures and provide no direct table access.

Granting Access to a Remote SQL Server

If you are accessing a database on another server in the same domain (or in a trusted domain), the Network Service account's network credentials are used to authenticate to the database. The Network Service account's credentials are of the form DomainName\AspNetServer$, where DomainName is the domain of the ASP.NET server and AspNetServer is your Web server name.

For example, if your ASP.NET application runs on a server named SVR1 in the domain CONTOSO, the SQL Server sees a database access request from CONTOSO\SVR1$.

To access a remote SQL Server using Network Service

To grant access to a remote database server in the same domain or a trusted domain, follow the steps described earlier for a local database, except in step 4, use the DomainName\AspNetServer$ account to create the database login.
Note In production environments, you should place the network service account into a Windows group and create a SQL Server login for the Windows group.