best MS.NET Learn Things From This Site
This is purely for my reference only
Tuesday, February 21, 2012
Friday, February 17, 2012
A simple example on achieving polymorphism in ASP.Net application part 2
A simple example on achieving polymorphism in ASP.Net application part 2
this is for reference only.
this is for reference only.
| Reactions: |
Thursday, February 16, 2012
Monday, February 6, 2012
Sunday, January 8, 2012
CONVERTING DATAREADER TO GENERIC COLLECTION
public static void ConvertTo(SqlDataReader sqlDr, IList list, Type type)
{
while (sqlDr.Read())
{
T item = (T)Activator.CreateInstance(type);
// Get all the properties of the type
PropertyInfo[] properties = ((Type)item.GetType()).GetProperties();
for (int j = 0; j < sqlDr.FieldCount; j++) { if (sqlDr.GetName(j) == properties[j].Name) { properties[j].SetValue(item, sqlDr[j], null); } } list.Add(item); } } Much simpler, although I have no idea if his way is more efficient or not. To use, just use the following code against your custom class: public class UserProfile { public int UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } public List FillUserProfileList()
{
SqlCommand sqlCmd;
List upList = new List();
try
{
sqlCmd = (SqlCommand)db.GetSqlStringCommand("SELECT UserId, FirstName, LastName FROM MyUserTable WHERE UserId = 1");
SqlDataReader sqlDr = (SqlDataReader)db.ExecuteReader(sqlCmd);
Helpers.CollectionHelper.ConvertTo(sqlDr, upList, typeof(UserProfile));
}
catch
{
}
return upList;
}
{
while (sqlDr.Read())
{
T item = (T)Activator.CreateInstance(type);
// Get all the properties of the type
PropertyInfo[] properties = ((Type)item.GetType()).GetProperties();
for (int j = 0; j < sqlDr.FieldCount; j++) { if (sqlDr.GetName(j) == properties[j].Name) { properties[j].SetValue(item, sqlDr[j], null); } } list.Add(item); } } Much simpler, although I have no idea if his way is more efficient or not. To use, just use the following code against your custom class: public class UserProfile { public int UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } public List
{
SqlCommand sqlCmd;
List
try
{
sqlCmd = (SqlCommand)db.GetSqlStringCommand("SELECT UserId, FirstName, LastName FROM MyUserTable WHERE UserId = 1");
SqlDataReader sqlDr = (SqlDataReader)db.ExecuteReader(sqlCmd);
Helpers.CollectionHelper.ConvertTo(sqlDr, upList, typeof(UserProfile));
}
catch
{
}
return upList;
}
| Reactions: |
Friday, November 4, 2011
using vs 2010 work flows sp 2010
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;
namespace MyWorkflow.Workflow1
{
public sealed partial class Workflow1 : SequentialWorkflowActivity
{
public Workflow1()
{
InitializeComponent();
}
public Guid workflowId = default(System.Guid);
public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();
private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{
double ddlMaxSellingPrice = Convert.ToDouble(workflowProperties.InitiationData);
SPWeb myweb = workflowProperties.Web;
SPList mylist = myweb.Lists["Products"];
foreach (SPListItem item in mylist.Items)
{
//if (Convert.ToDouble(item["sellingprice"]).ToString() > ddlMaxSellingPrice)
//{
//}
if (Convert.ToDouble(item["sellingprice"].ToString()) > ddlMaxSellingPrice)
{
item.ModerationInformation.Comment = "price is too high ";
item.ModerationInformation.Status = SPModerationStatusType.Denied;
item.Update();
}
else
{
item.ModerationInformation.Comment = "Congrats , product i approved ";
item.ModerationInformation.Status = SPModerationStatusType.Approved;
item.Update();
}
}
}
}
}
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;
namespace MyWorkflow.Workflow1
{
public sealed partial class Workflow1 : SequentialWorkflowActivity
{
public Workflow1()
{
InitializeComponent();
}
public Guid workflowId = default(System.Guid);
public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();
private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{
double ddlMaxSellingPrice = Convert.ToDouble(workflowProperties.InitiationData);
SPWeb myweb = workflowProperties.Web;
SPList mylist = myweb.Lists["Products"];
foreach (SPListItem item in mylist.Items)
{
//if (Convert.ToDouble(item["sellingprice"]).ToString() > ddlMaxSellingPrice)
//{
//}
if (Convert.ToDouble(item["sellingprice"].ToString()) > ddlMaxSellingPrice)
{
item.ModerationInformation.Comment = "price is too high ";
item.ModerationInformation.Status = SPModerationStatusType.Denied;
item.Update();
}
else
{
item.ModerationInformation.Comment = "Congrats , product i approved ";
item.ModerationInformation.Status = SPModerationStatusType.Approved;
item.Update();
}
}
}
}
}
| Reactions: |
Thursday, November 3, 2011
Wednesday, November 2, 2011
how to create events in sharepoint 2010
http://www.gmail.com:24413/Lists/orders
EventReceiver1ItemAdding
ItemAdding
$SharePoint.Project.AssemblyFullName$
MyEvents.EventReceiver1.EventReceiver1
10000
EventReceiver1ItemDeleting
ItemDeleting
$SharePoint.Project.AssemblyFullName$
MyEvents.EventReceiver1.EventReceiver1
10000
EventReceiver1ItemUpdated
ItemUpdated
$SharePoint.Project.AssemblyFullName$
MyEvents.EventReceiver1.EventReceiver1
10000
-----------------------------(check the receivers tag only it was changee below)
EventReceiver1ItemAdding
ItemAdding
$SharePoint.Project.AssemblyFullName$
MyEvents.EventReceiver1.EventReceiver1
10000
EventReceiver1ItemDeleting
ItemDeleting
$SharePoint.Project.AssemblyFullName$
MyEvents.EventReceiver1.EventReceiver1
10000
EventReceiver1ItemUpdated
ItemUpdated
$SharePoint.Project.AssemblyFullName$
MyEvents.EventReceiver1.EventReceiver1
10000
------------------------------
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
namespace MyEvents.EventReceiver1
{
///
/// List Item Events
///
public class EventReceiver1 : SPItemEventReceiver
{
///
/// An item is being added.
///
public override void ItemAdding(SPItemEventProperties properties)
{
//base.ItemAdding(properties);
generateAmount(properties);
}
///
/// An item is being deleted.
///
public override void ItemDeleting(SPItemEventProperties properties)
{
// base.ItemDeleting(properties);
properties.ErrorMessage = " Sorry , cannot delete try later ";
properties.Cancel = true;
}
///
/// An item was updated.
///
public override void ItemUpdated(SPItemEventProperties properties)
{
// base.ItemUpdated(properties);
generateAmount(properties);
}
void generateAmount(SPItemEventProperties properties)
{
SPListItem myorder =properties.ListItem; // this wil get the row(current row)
double myprise = Convert.ToDouble(myorder["Price"]);
int qty = Convert.ToInt32(myorder["Qty"]);
myorder["Amount"] = (myprise * qty);
myorder.Update();
}
}
}
-----------------------------(check the receivers tag only it was changee below)
------------------------------
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
namespace MyEvents.EventReceiver1
{
///
/// List Item Events
///
public class EventReceiver1 : SPItemEventReceiver
{
///
/// An item is being added.
///
public override void ItemAdding(SPItemEventProperties properties)
{
//base.ItemAdding(properties);
generateAmount(properties);
}
///
/// An item is being deleted.
///
public override void ItemDeleting(SPItemEventProperties properties)
{
// base.ItemDeleting(properties);
properties.ErrorMessage = " Sorry , cannot delete try later ";
properties.Cancel = true;
}
///
/// An item was updated.
///
public override void ItemUpdated(SPItemEventProperties properties)
{
// base.ItemUpdated(properties);
generateAmount(properties);
}
void generateAmount(SPItemEventProperties properties)
{
SPListItem myorder =properties.ListItem; // this wil get the row(current row)
double myprise = Convert.ToDouble(myorder["Price"]);
int qty = Convert.ToInt32(myorder["Qty"]);
myorder["Amount"] = (myprise * qty);
myorder.Update();
}
}
}
| Reactions: |
Intro to SharePoint Development: How to Build and Deploy a Web Part
this is really sounds,
note: for my own referece only.
note: for my own referece only.
| Reactions: |
adding quick launch
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
namespace Features.Features.Feature1
{
///
/// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
///
///
/// The GUID attached to this class may be used during packaging and should not be modified.
///
[Guid("b786dac8-72c1-4e5a-b4f6-bf293a24d31b")]
public class Feature1EventReceiver : SPFeatureReceiver
{
// Uncomment the method below to handle the event raised after a feature has been activated.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb myWeb =(SPWeb) properties.Feature.Parent; // thsi returens the website.
myWeb.Title = "Kanbay Corp";
myWeb.RecycleBin.DeleteAll();
myWeb.QuickLaunchEnabled = false;
myWeb.Update();
}
// this is for which exampleple
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPWeb myWeb = (SPWeb)properties.Feature.Parent; // thsi returens the website.
myWeb.Title = "Cg Corp";
//myWeb.RecycleBin.DeleteAll();
myWeb.QuickLaunchEnabled = true;
myWeb.Update();
}
// Uncomment the method below to handle the event raised after a feature has been installed.
//public override void FeatureInstalled(SPFeatureReceiverProperties properties)
//{
//}
// Uncomment the method below to handle the event raised before a feature is uninstalled.
//public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
//{
//}
// Uncomment the method below to handle the event raised when a feature is upgrading.
//public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary parameters)
//{
//}
}
}
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
namespace Features.Features.Feature1
{
///
/// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
///
///
/// The GUID attached to this class may be used during packaging and should not be modified.
///
[Guid("b786dac8-72c1-4e5a-b4f6-bf293a24d31b")]
public class Feature1EventReceiver : SPFeatureReceiver
{
// Uncomment the method below to handle the event raised after a feature has been activated.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb myWeb =(SPWeb) properties.Feature.Parent; // thsi returens the website.
myWeb.Title = "Kanbay Corp";
myWeb.RecycleBin.DeleteAll();
myWeb.QuickLaunchEnabled = false;
myWeb.Update();
}
// this is for which exampleple
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPWeb myWeb = (SPWeb)properties.Feature.Parent; // thsi returens the website.
myWeb.Title = "Cg Corp";
//myWeb.RecycleBin.DeleteAll();
myWeb.QuickLaunchEnabled = true;
myWeb.Update();
}
// Uncomment the method below to handle the event raised after a feature has been installed.
//public override void FeatureInstalled(SPFeatureReceiverProperties properties)
//{
//}
// Uncomment the method below to handle the event raised before a feature is uninstalled.
//public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
//{
//}
// Uncomment the method below to handle the event raised when a feature is upgrading.
//public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary
//{
//}
}
}
| Reactions: |
Tuesday, November 1, 2011
sandbox example in sharepoint
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Security;
namespace Sandboxsol.SandBox
{
[ToolboxItemAttribute(false)]
public class SandBox : WebPart
{
Button btnCountWebs;
Button btnRunAsFarmAdmin;
Button btnInfiniteForLoop;
LiteralControl ltrOutput;
protected override void CreateChildControls()
{
btnCountWebs = new Button();
btnRunAsFarmAdmin = new Button();
btnInfiniteForLoop = new Button();
ltrOutput = new LiteralControl();
btnCountWebs.Text = "Count sub Titles";
btnInfiniteForLoop.Text = " infinite For Loop";
btnRunAsFarmAdmin.Text = " Run as Farm Admin";
ltrOutput.Text = " ......";
btnCountWebs.Click += new EventHandler(btnCountWebs_Click);
btnRunAsFarmAdmin.Click += new EventHandler(btnRunAsFarmAdmin_Click);
btnInfiniteForLoop.Click += new EventHandler(btnInfiniteForLoop_Click);
this.Controls.Add(btnCountWebs);
this.Controls.Add(btnInfiniteForLoop);
this.Controls.Add(btnRunAsFarmAdmin);
this.Controls.Add(new LiteralControl("
"));
this.Controls.Add(ltrOutput);
}
void btnInfiniteForLoop_Click(object sender, EventArgs e)
{
try
{
for (; ; )
{
}
}
catch (Exception ex)
{
ltrOutput.Text = " from upen" + ex.Message.ToString();
}
}
void btnRunAsFarmAdmin_Click(object sender, EventArgs e)
{
try
{
SPSecurity.RunWithElevatedPrivileges(CallME);
}
catch (Exception ex)
{
ltrOutput.Text = "from upen" + ex.Message.ToString();
}
}
void CallME()
{
SPWeb myWeb = SPContext.Current.Web;
ltrOutput.Text = string.Format("no of Subsites are{0}", myWeb.Webs.Count);
}
void btnCountWebs_Click(object sender, EventArgs e)
{
SPWeb myWeb = SPContext.Current.Web;
ltrOutput.Text = string.Format("no of Subsites are{0}", myWeb.Webs.Count);
}
}
}
now go the website(http://www.gmail.com:24413/SitePages/Home.aspx)
->siteaction ->sitesettings->galleries->solutions (here u need to chek the .net object has created or not.
now if u want to add this to welcome page at(http://www.gmail.com:24413/SitePages/Home.aspx)
then do follwing steps ->Edit->Insert->Webpart -> click on'customs' ->Add
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Security;
namespace Sandboxsol.SandBox
{
[ToolboxItemAttribute(false)]
public class SandBox : WebPart
{
Button btnCountWebs;
Button btnRunAsFarmAdmin;
Button btnInfiniteForLoop;
LiteralControl ltrOutput;
protected override void CreateChildControls()
{
btnCountWebs = new Button();
btnRunAsFarmAdmin = new Button();
btnInfiniteForLoop = new Button();
ltrOutput = new LiteralControl();
btnCountWebs.Text = "Count sub Titles";
btnInfiniteForLoop.Text = " infinite For Loop";
btnRunAsFarmAdmin.Text = " Run as Farm Admin";
ltrOutput.Text = " ......";
btnCountWebs.Click += new EventHandler(btnCountWebs_Click);
btnRunAsFarmAdmin.Click += new EventHandler(btnRunAsFarmAdmin_Click);
btnInfiniteForLoop.Click += new EventHandler(btnInfiniteForLoop_Click);
this.Controls.Add(btnCountWebs);
this.Controls.Add(btnInfiniteForLoop);
this.Controls.Add(btnRunAsFarmAdmin);
this.Controls.Add(new LiteralControl("
"));
this.Controls.Add(ltrOutput);
}
void btnInfiniteForLoop_Click(object sender, EventArgs e)
{
try
{
for (; ; )
{
}
}
catch (Exception ex)
{
ltrOutput.Text = " from upen" + ex.Message.ToString();
}
}
void btnRunAsFarmAdmin_Click(object sender, EventArgs e)
{
try
{
SPSecurity.RunWithElevatedPrivileges(CallME);
}
catch (Exception ex)
{
ltrOutput.Text = "from upen" + ex.Message.ToString();
}
}
void CallME()
{
SPWeb myWeb = SPContext.Current.Web;
ltrOutput.Text = string.Format("no of Subsites are{0}", myWeb.Webs.Count);
}
void btnCountWebs_Click(object sender, EventArgs e)
{
SPWeb myWeb = SPContext.Current.Web;
ltrOutput.Text = string.Format("no of Subsites are{0}", myWeb.Webs.Count);
}
}
}
now go the website(http://www.gmail.com:24413/SitePages/Home.aspx)
->siteaction ->sitesettings->galleries->solutions (here u need to chek the .net object has created or not.
now if u want to add this to welcome page at(http://www.gmail.com:24413/SitePages/Home.aspx)
then do follwing steps ->Edit->Insert->Webpart -> click on'customs' ->Add
| Reactions: |
Resource Usage Limits on Sandboxed Solutions in SharePoint 2010
http://msdn.microsoft.com/en-us/library/gg615462.aspx
| Reactions: |
Fix for Not able to connect to SharePoint 2010 server web sites through Visual Studio 2010
Solution:
It's simple that the platform target in build options was set to the x86 format by default. It should be set to x64 to work correct
It's simple that the platform target in build options was set to the x86 format by default. It should be set to x64 to work correct
| Reactions: |
Tuesday, August 23, 2011
Building Layered Web Applications with Microsoft ASP.NET 2.0 - Part 1
This is a very Good Resource to learn.net
| Reactions: |
Tuesday, December 14, 2010
Monday, December 13, 2010
Securing My Website Using SSL in Local IIS (5.1 and Above)?
Securing My Website Using SSL in Local IIS (5.1 and Above)?
| Reactions: |
WCF Transport Layer Security using wsHttpBinding and SSL
This is useful when working and implemment the ssl.
| Reactions: |
Tuesday, November 9, 2010
Monday, November 8, 2010
Wednesday, October 27, 2010
Handling Parameters while using the microsoft application blocks
this was very use ful while implement the microsoft application blocks.
following was use ful for the how to use the en-application blocks
http://aspalliance.com/688_Get_Started_with_the_Enterprise_Library_Data_Access_Application_Block.all
following was use ful for the how to use the en-application blocks
http://aspalliance.com/688_Get_Started_with_the_Enterprise_Library_Data_Access_Application_Block.all
| Reactions: |
Thursday, October 14, 2010
Tips, Tricks, Notes on Entity Frameworks 4.0
Rate This
The Entity Framework enables you to query, insert, update, and delete data, expressed as typed common language runtime (CLR) objects that are instances of entity types. The entity types represent the entities defined in the conceptual model. The Entity Framework maps entities and relationships that are defined in a conceptual model to a data source. The Entity Framework provides facilities to do the following: materialize data returned from the data source as objects; track changes that were made to the objects; handle concurrency; propagate object changes back to the data source; and bind objects to controls. You can use LINQ to Entities, Entity SQL Language, or Query Builder Methods (Entity Framework) to execute queries against the conceptual model.
Customizable Code-Generation: EF4 leverages the T4 code generation templating engine in Visual Studio. You can now write your own templates that specify exactly how you want code generation to happen; or you can modify the built-in templates such as the Entity Object Code Generator or Self Tracking Entities Code Generator templates: http://blogs.msdn.com/adonet/archive/2009/05/19/sneak-peek-using-code-generation-templates-with-the-entity-framework-4-0.aspx
Self-Tracking Entities & N-Tier support: Visual Studio 2010 includes code-generation templates for Self Tracking Entities that allow you to easily build N-Tier applications. There are also new APIs in the product that offer you more control in N-Tier scenarios. : http://msdn.microsoft.com/en-us/library/ee789839(v=VS.100).aspx
Model Defined Functions LINQ support: Model Defined Functions allow you to define composable functions in your model using Entity SQL. http://blogs.msdn.com/adonet/archive/2009/05/14/sneak-preview-model-defined-functions.aspx
EntityDataSource support for QueryExtender, POCO and FKs: EntityDataSource control now includes support for ASP.NET QueryExtender and POCO entities. QueryExtender is a new addition to ASP.NET, which allows you to have more control over the data retrieval query of a Data Source while leveraging LINQ capabilities of EF.
The Entity Data Model Tools can generate a class derived from ObjectContext that represents the entity container in the conceptual model. This object context provides the facilities for tracking changes and managing identities, concurrency, and relationships. This class also exposes a SaveChanges method that writes inserts, updates, and deletes to the data source. Like queries, these changes are either made by commands automatically generated by the system or by stored procedures that are specified by the developer.
The EntityClient provider extends the ADO.NET provider model by accessing data in terms of conceptual entities and relationships. It executes queries that use Entity SQL. Entity SQL provides the underlying query language that enables EntityClient to communicate with the database
——————————————————————————————————————————-
•Address
•Contact
•Product
•SalesOrderDetail
•SalesOrderHeader
——————————————————————————————————————————-
QueryExtender and Model-Defined Functions
ADO.NET EntityObject Generator
——————————————————————————————————————————-
http://blogs.msdn.com/efdesign/archive/2009/01/22/customizing-entity-classes-with-t4.aspx
ADO.NET Entity Designer generates classes from the CSDL portion of the EDMX file using the EntityClassGenerator APIs.
how to customize the code generation for a variety of scenarios:
Make the generated ObjectContext internal
Make the generated ObjectContext and Entity classes implement a user-defined interface
Add user-defined CLR attributes to generated ObjectContext and generated Entity classes
Influence generated classes based on structural annotations in CSDL
Generate the ObjectContext and Entity classes into separate files
Generate “proxy classes” for the generated classes
Partially or fully change how classes are generated, maybe even generate additional (non code) artifacts in the project
Completely replace entity framework code generation with custom code
Generate POCO classes from the model to use as a starting point in my applications
Generate self-tracking entity classes
——————————————————————————————————————————-
http://blogs.msdn.com/adonet/archive/2008/01/24/customizing-code-generation-in-the-ado-net-entity-designer.aspx
SSDL – store schema definition language
Mapping specification language (MSL)
TT – Text Templates 4 TT4
http://msdn.microsoft.com/en-us/library/bb126445.aspx
Conceptual schema definition language (CSDL) is an XML-based language that describes the entities, relationships, and functions that make up a conceptual model of a data-driven application. This conceptual model can be used by the Entity Framework or ADO.NET Data Services. The metadata that is described with CSDL is used by the Entity Framework to map entities and relationships that are defined in a conceptual model to a data source. For more information, see SSDL Specification and MSL Specification.
——————————————————————————————————————————-
CSDL is the Entity Framework’s implementation of the Entity Data Model.
In an Entity Framework application, conceptual model metadata is loaded from a .csdl file (written in CSDL) into an instance of the System.Data.Metadata.Edm.EdmItemCollection and is accessible by using methods in the System.Data.Metadata.Edm.MetadataWorkspace class. The Entity Framework uses conceptual model metadata to translate queries against the conceptual model to data source-specific commands.
——————————————————————————————————————————-
Entity Data Model Designer (Entity Designer):: http://msdn.microsoft.com/en-us/library/cc716685.aspx
.edmx File Overview.:: http://msdn.microsoft.com/en-us/library/cc982042.aspx
Entity Data Model.: http://msdn.microsoft.com/en-us/library/ee382825.aspx
——————————————————————————————————————————-
The conceptual model metadata can be used to generate the object-layer code for an Entity Framework application. For more information, see Generated Code Overview (Entity Data Model Designer) http://msdn.microsoft.com/en-us/library/cc982041.aspx and How to: Use EdmGen.exe to Generate Object-Layer Code. http://msdn.microsoft.com/en-us/library/cc716790.aspx
——————————————————————————————————————————-
Entity Framework Overview:: http://msdn.microsoft.com/en-us/library/bb399567.aspx
ADO.NET Entity Data Model Tools:: http://msdn.microsoft.com/en-us/library/bb399249.aspx
——————————————————————————————————————————-
ObjectContext.ObjectMaterialized Event
This event is raised after all scalar, complex, and reference properties have been set on an object, but before collections are loaded. If an object with the same key value exists in the object context, the Entity Framework will not recreate the object and this event will not be raised.
——————————————————————————————————————————-
ObjectContext Class
Provides facilities for querying and working with entity data as objects.
The ObjectContext class is the primary class for interacting with data as objects that are instances of entity types that are defined in a conceptual model. An instance of the ObjectContext class encapsulates the following:
•A connection to the database, in the form of an EntityConnection object.
•Metadata that describes the model, in the form of a MetadataWorkspace object.
•An ObjectStateManager object that manages objects persisted in the cache. tracks objects during create, update, and delete operations
When the object layer that represents a conceptual model is generated by the Entity Data Model tools, the class that represents the EntityContainer for the model is derived from the ObjectContext.
EntityObject
By default, the ADO.NET Entity Data Model tools generate EntityObject derived entity types. When you work with EntityObject derived types, the object context manages the relationships between your objects, tracks changes as they occur, and supports lazy loading in the most efficient manner. However, the EntityObject derived types have strong dependency on the Entity Framework. If you are working with architectures that require persistence ignorance (for example, test- driven development or domain-driven development) or you have existing domain classes, consider using POCO or POCO proxies.
Self-Tracking Entities
The EntityObjectderived types, POCO, and POCO proxy types work well in applications where entity objects can be attached to the object context that handles change tracking. However, when you have to transfer full graphs of entities to a tier where the object context is not available, you must decide how to track changes and report those changes back to the object context. Starting with the .NET Framework version 4, self-tracking entities can record changes to scalar, complex, and navigation properties. Self-tracking entities do not depend on the Entity Framework. The ADO.NET Self-Tracking Entity Generator template generates self-tracking entities
——————————————————————————————————————————-
——————————————————————————————————————————-
// Create the ObjectContext.
ObjectContext context =
new ObjectContext("name=AdventureWorksEntities");
// Set the DefaultContainerName for the ObjectContext.
// When DefaultContainerName is set, the Entity Framework only
// searches for the type in the specified container.
// Note that if a type is defined only once in the metadata workspace
// you do not have to set the DefaultContainerName.
context.DefaultContainerName = "AdventureWorksEntities";
ObjectSet query = context.CreateObjectSet();
// Iterate through the collection of Products.
foreach (Product result in query)
Console.WriteLine("Product Name: {0}", result.Name);
-------------------------------------------------------------------------------------------------------------------------------——————————————————————————————————————————-
http://blogs.msdn.com/adonet/archive/2008/01/24/sampleedmxcodegenerator-sources.aspx
How to add custom attributes to my generated classes
——————————————————————————————————————————-
“Database Script Generation” properties:
Database Generation Workflow – Controls the overall process by which the conceptual model is translated into a database script. The default workflow is “TablePerTypeStrategy.xaml”.
DDL Generation Template – Is called by the default database generation workflow to transform the generated database model to DDL. More on this below.
First, let’s take a look at TablePerTypeStrategy.xaml – it is located in Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\DBGen. If we open this file in Visual Studio, we see that it is a Workflow Foundation (WF) workflow
The first activity, “CsdlToSsdlAndMslActivity” generates the store model (SSDL) for the EDM, and then generates the mappings (MSL) that connect the two. It has the following properties
The “MslOutputGeneratorType” specifies a class that generates MSL based on a table-per-type mapping strategy. The “OuputGeneratorType” generates SSDL. Rather than replacing this activity and all of the plumbing it provides, you can replace these two classes with your own if you want to change the mapping strategy or otherwise alter the system.
http://blogs.msdn.com/adonet/archive/2009/11/05/model-first-with-the-entity-framework-4.aspx
——————————————————————————————————————————-
Query builder methods
These methods of ObjectQuery enable you to construct queries that are the same as Entity SQL without having to construct a query string. Because these methods always return an ObjectQuery, you can build queries by calling methods in series or use them to extend an Entity SQL query. Some methods, such as Where and OrderBy, take Entity SQL fragments as parameters. Query builder methods can be followed by certain LINQ standard query operators
The ObjectQuery generic class represents a query that can return a collection of zero or more typed objects. An ObjectQuery belongs to an ObjectContext that contains the connection and metadata information that is necessary to compose and execute the query. You can construct an ObjectQuery with a new operator and pass a query string and the object context to the constructor. However, a more common scenario is to use properties on an ObjectContext derived class to get an ObjectQuery instance that represents a collection of entity sets. Typically, the ObjectContext is subclassed, either by a class generated by the Entity Framework tools or by your POCO classes, and the properties on the object context return entity sets as either an ObjectQuery (in .NET Framework version 3.5 SP1) or as an ObjectSet (in .NET Framework version 4). The ObjectSet class extends the ObjectQuery class to provide functionality, such as adding and deleting objects, in the context of a typed entity set.
This is the query builder method example.
string firstName = @"Frances";
string lastName = @"Adams";
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
// Get the contacts with the specified name.
ObjectQuery contactQuery = context.Contacts
.Where("it.LastName = @ln AND it.FirstName = @fn",
new ObjectParameter("ln", lastName),
new ObjectParameter("fn", firstName));
// Iterate through the collection of Contact items.
foreach (Contact result in contactQuery)
Console.WriteLine("Last Name: {0}; First Name: {1}",
result.LastName, result.FirstName);
}
An object query is executed when:
•It is enumerated by a foreach (C#) or For Each (Visual Basic) statement.
•It is enumerated by a collection operation such as ToArray, ToDictionary or ToList.
•The Execute method is explicitly called.
•LINQ operators such, as First or Any are specified in the outermost part of the query. For more information, see Query Builder Methods (Entity Framework).
Note, if as a result of a query execution, nothing was returned from the data source, the results will contain an empty collection and not a null.
——————————————————————————————————————————-
Entity Framework Features Not Supported by the Entity Designer
The following are Entity Framework features that are not currently supported by the Entity Designer.
•Multiple entity sets per type.
•Creating entity sets for non-root types.
•Table-per-concrete class mapping.
•Using EntityType properties in mapping conditions.
•Unmapped abstract types. When you create an abstract entity type with the Entity Designer, the type must be mapped to a table or view.
•Creating conditions on association mappings.
•Mapping associations directly to stored procedures. Mapping many-to-many associations is not supported. You can indirectly map other associations to stored procedures along with entity types by mapping the appropriate navigation properties to stored procedure parameters.
•Creating conditions on Function Import mappings.
•Annotations.
•Query views.
•Models that contain references to other models.
•Creating associations without corresponding navigation properties.
•Adding or editing storage model objects. (Deleting storage model objects is supported.)
•Adding, editing, or deleting functions that are defined in the conceptual model.
————————————————————————————————————————
Building N-Tier Applications (Entity Framework)
Entity types generated by the Entity Data Model generator tool (EdmGen.exe) and the Entity Data Model Wizard have SerializableAttribute and DataContractAttribute applied. This enables objects to be serialized by using binary serialization, XML serialization, and Windows Communication Foundation (WCF) data contract serialization.
Extending Partial Classes :: How to: Customize Generated Data Objects (Entity Framework).
When data classes are generated by the Entity Data Model tools, they are implemented in partial classes. You can add functionality to objects by extending the generated partial data classes. Having partial classes enables you to extend these classes with custom methods and properties in a separate source file without having to worry about losing your customization when the generated files are refreshed.
——————————————————————————————————————————-
Managing Connections and Transactions
By default, the Entity Framework manages the connection to the database. However, you can manually manage both connections and transactions in your Entity Framework application.
By default, the Entity Framework implements an optimistic concurrency model. This means that locks are not held on data in the data source between when the data is queried and the data is updated. The Entity Framework saves object changes to the database without checking for concurrency. For entities that might experience a high degree of concurrency, we recommend that the entity define a property in the conceptual layer with an attribute of ConcurrencyMode=”fixed”
When this attribute is used, the Entity Framework checks for changes in the database before saving changes to the database. Any conflicting changes will cause an OptimisticConcurrencyException.
An OptimisticConcurrencyException can also occur when you define an Entity Data Model that uses stored procedures to make updates to the data source. In this case, the exception is raised when the stored procedure that is used to perform updates reports that zero rows were updated.
You may choose to use transactions as an alternative to optimistic concurrency.
The Entity Framework opens connections only when required, for example to execute a query or to call SaveChanges, and then closes the connection when the operation is complete.
Calling any of the following methods opens the connection:
•SaveChanges or Refresh on ObjectContext.
•FirstOrDefault, or First on ObjectQuery.
•Load on EntityCollection.
•Load on EntityReference.
•Any Language-Integrated Query (LINQ) method or ObjectQuery query builder method, such as Where, OrderBy, or Select.
When a query method is called, the connection is opened, and it remains open until the ObjectResult has been completely consumed or disposed.
The Entity Framework supports automatic transaction enlistment. This means that activities performed within an object context, such as executing queries and saving changes to data in the data source, can be isolated in the data source by executing the operation within a System.Transactions transaction. Transactions are used in the Entity Framework to do the following actions:
•To execute multiple operations against the data source that must be highly consistent, such as queries that depend on the successful completion of object changes.
•To coordinate changes in the object context with other distributed operations, such as sending an e-mail notification or writing to a message queue.
Transactions that require the enlistment of additional resource managers are called distributed transactions. Distributed transactions use a distributed transaction coordinator (DTC) to manage the resources that are required to complete the transaction. Promotion of a transaction to a DTC can be a relatively expensive process to establish and complete. Some resource managers, like SQL Server 2005, support the Promotable Single Phase Enlistment (PSPE) transaction protocol. This allows a resource manager to host a transaction that can later be escalated to be managed by the distributed transaction coordinator (DTC) if necessary.
——————————————————————————————————————————-
•When you call SaveChanges, if a current transaction exists, the Entity Framework uses this transaction for operations against the data source. Otherwise, it creates a new transaction for the operation. You can define transactions by using EntityTransaction, Transaction, or TransactionScope.
•Promotion of a transaction to a DTC may occur when a connection is closed and reopened within a single transaction. Because the Entity Framework opens and closes the connection automatically, you should consider manually opening and closing the connection to avoid transaction promotion.
To enlist in an existing transaction, the Entity Framework might close and reopen the connection.
——————————————————————————————————————————-
This example defines a TransactionScope. The TransactionScope ensures that changes to objects in the object context are coordinated with a message queue. The Entity Framework uses this transaction when it saves changes to the database. When an UpdateException occurs, the operation is retried up to two times. When the operation succeeds, the changes in the object context are accepted. For more information, see Managing Connections and Transactions (Entity Framework).
This example uses a long-running object context, which is disposed after the transaction succeeds or after all retries have been attempted.
——————————————————————————————————————————-
http://msdn.microsoft.com/en-us/library/bb896325.aspx
The following considerations apply when you use transactions with the Entity Framework:
•Only operations against the data source are transacted. Changes made to objects in the object context are not transacted. Changes to objects in the context are visible outside the transaction scope.
•When the Entity Framework creates a new transaction for a SaveChanges operation, changes to objects in the object context are not accepted until the transaction completes. This ensures that the state of the object context and the data source are consistent.
•When you plan to retry operations in a transaction, you must ensure that the status of objects in the context is not reset before the transaction is completed. To do this, you must call SaveChanges with a value of false for the acceptChangesDuringSave parameter, and then call AcceptAllChanges only after other operations in the transaction have completed successfully.
——————————————————————————————————————————-
Managing Transactions
In the Entity Framework, there are two ways to use transactions: automatic and explicit. Automatic transactions use the System.Transactions namespace, and explicit transactions use the EntityTransaction class.
The Entity Framework enables you to query, insert, update, and delete data, expressed as typed common language runtime (CLR) objects that are instances of entity types. The entity types represent the entities defined in the conceptual model. The Entity Framework maps entities and relationships that are defined in a conceptual model to a data source. The Entity Framework provides facilities to do the following: materialize data returned from the data source as objects; track changes that were made to the objects; handle concurrency; propagate object changes back to the data source; and bind objects to controls. You can use LINQ to Entities, Entity SQL Language, or Query Builder Methods (Entity Framework) to execute queries against the conceptual model.
Customizable Code-Generation: EF4 leverages the T4 code generation templating engine in Visual Studio. You can now write your own templates that specify exactly how you want code generation to happen; or you can modify the built-in templates such as the Entity Object Code Generator or Self Tracking Entities Code Generator templates: http://blogs.msdn.com/adonet/archive/2009/05/19/sneak-peek-using-code-generation-templates-with-the-entity-framework-4-0.aspx
Self-Tracking Entities & N-Tier support: Visual Studio 2010 includes code-generation templates for Self Tracking Entities that allow you to easily build N-Tier applications. There are also new APIs in the product that offer you more control in N-Tier scenarios. : http://msdn.microsoft.com/en-us/library/ee789839(v=VS.100).aspx
Model Defined Functions LINQ support: Model Defined Functions allow you to define composable functions in your model using Entity SQL. http://blogs.msdn.com/adonet/archive/2009/05/14/sneak-preview-model-defined-functions.aspx
EntityDataSource support for QueryExtender, POCO and FKs: EntityDataSource control now includes support for ASP.NET QueryExtender and POCO entities. QueryExtender is a new addition to ASP.NET, which allows you to have more control over the data retrieval query of a Data Source while leveraging LINQ capabilities of EF.
The Entity Data Model Tools can generate a class derived from ObjectContext that represents the entity container in the conceptual model. This object context provides the facilities for tracking changes and managing identities, concurrency, and relationships. This class also exposes a SaveChanges method that writes inserts, updates, and deletes to the data source. Like queries, these changes are either made by commands automatically generated by the system or by stored procedures that are specified by the developer.
The EntityClient provider extends the ADO.NET provider model by accessing data in terms of conceptual entities and relationships. It executes queries that use Entity SQL. Entity SQL provides the underlying query language that enables EntityClient to communicate with the database
——————————————————————————————————————————-
•Address
•Contact
•Product
•SalesOrderDetail
•SalesOrderHeader
——————————————————————————————————————————-
QueryExtender and Model-Defined Functions
ADO.NET EntityObject Generator
——————————————————————————————————————————-
http://blogs.msdn.com/efdesign/archive/2009/01/22/customizing-entity-classes-with-t4.aspx
ADO.NET Entity Designer generates classes from the CSDL portion of the EDMX file using the EntityClassGenerator APIs.
how to customize the code generation for a variety of scenarios:
Make the generated ObjectContext internal
Make the generated ObjectContext and Entity classes implement a user-defined interface
Add user-defined CLR attributes to generated ObjectContext and generated Entity classes
Influence generated classes based on structural annotations in CSDL
Generate the ObjectContext and Entity classes into separate files
Generate “proxy classes” for the generated classes
Partially or fully change how classes are generated, maybe even generate additional (non code) artifacts in the project
Completely replace entity framework code generation with custom code
Generate POCO classes from the model to use as a starting point in my applications
Generate self-tracking entity classes
——————————————————————————————————————————-
http://blogs.msdn.com/adonet/archive/2008/01/24/customizing-code-generation-in-the-ado-net-entity-designer.aspx
SSDL – store schema definition language
Mapping specification language (MSL)
TT – Text Templates 4 TT4
http://msdn.microsoft.com/en-us/library/bb126445.aspx
Conceptual schema definition language (CSDL) is an XML-based language that describes the entities, relationships, and functions that make up a conceptual model of a data-driven application. This conceptual model can be used by the Entity Framework or ADO.NET Data Services. The metadata that is described with CSDL is used by the Entity Framework to map entities and relationships that are defined in a conceptual model to a data source. For more information, see SSDL Specification and MSL Specification.
——————————————————————————————————————————-
CSDL is the Entity Framework’s implementation of the Entity Data Model.
In an Entity Framework application, conceptual model metadata is loaded from a .csdl file (written in CSDL) into an instance of the System.Data.Metadata.Edm.EdmItemCollection and is accessible by using methods in the System.Data.Metadata.Edm.MetadataWorkspace class. The Entity Framework uses conceptual model metadata to translate queries against the conceptual model to data source-specific commands.
——————————————————————————————————————————-
Entity Data Model Designer (Entity Designer):: http://msdn.microsoft.com/en-us/library/cc716685.aspx
.edmx File Overview.:: http://msdn.microsoft.com/en-us/library/cc982042.aspx
Entity Data Model.: http://msdn.microsoft.com/en-us/library/ee382825.aspx
——————————————————————————————————————————-
The conceptual model metadata can be used to generate the object-layer code for an Entity Framework application. For more information, see Generated Code Overview (Entity Data Model Designer) http://msdn.microsoft.com/en-us/library/cc982041.aspx and How to: Use EdmGen.exe to Generate Object-Layer Code. http://msdn.microsoft.com/en-us/library/cc716790.aspx
——————————————————————————————————————————-
Entity Framework Overview:: http://msdn.microsoft.com/en-us/library/bb399567.aspx
ADO.NET Entity Data Model Tools:: http://msdn.microsoft.com/en-us/library/bb399249.aspx
——————————————————————————————————————————-
ObjectContext.ObjectMaterialized Event
This event is raised after all scalar, complex, and reference properties have been set on an object, but before collections are loaded. If an object with the same key value exists in the object context, the Entity Framework will not recreate the object and this event will not be raised.
——————————————————————————————————————————-
ObjectContext Class
Provides facilities for querying and working with entity data as objects.
The ObjectContext class is the primary class for interacting with data as objects that are instances of entity types that are defined in a conceptual model. An instance of the ObjectContext class encapsulates the following:
•A connection to the database, in the form of an EntityConnection object.
•Metadata that describes the model, in the form of a MetadataWorkspace object.
•An ObjectStateManager object that manages objects persisted in the cache. tracks objects during create, update, and delete operations
When the object layer that represents a conceptual model is generated by the Entity Data Model tools, the class that represents the EntityContainer for the model is derived from the ObjectContext.
EntityObject
By default, the ADO.NET Entity Data Model tools generate EntityObject derived entity types. When you work with EntityObject derived types, the object context manages the relationships between your objects, tracks changes as they occur, and supports lazy loading in the most efficient manner. However, the EntityObject derived types have strong dependency on the Entity Framework. If you are working with architectures that require persistence ignorance (for example, test- driven development or domain-driven development) or you have existing domain classes, consider using POCO or POCO proxies.
Self-Tracking Entities
The EntityObjectderived types, POCO, and POCO proxy types work well in applications where entity objects can be attached to the object context that handles change tracking. However, when you have to transfer full graphs of entities to a tier where the object context is not available, you must decide how to track changes and report those changes back to the object context. Starting with the .NET Framework version 4, self-tracking entities can record changes to scalar, complex, and navigation properties. Self-tracking entities do not depend on the Entity Framework. The ADO.NET Self-Tracking Entity Generator template generates self-tracking entities
——————————————————————————————————————————-
——————————————————————————————————————————-
// Create the ObjectContext.
ObjectContext context =
new ObjectContext("name=AdventureWorksEntities");
// Set the DefaultContainerName for the ObjectContext.
// When DefaultContainerName is set, the Entity Framework only
// searches for the type in the specified container.
// Note that if a type is defined only once in the metadata workspace
// you do not have to set the DefaultContainerName.
context.DefaultContainerName = "AdventureWorksEntities";
ObjectSet
// Iterate through the collection of Products.
foreach (Product result in query)
Console.WriteLine("Product Name: {0}", result.Name);
-------------------------------------------------------------------------------------------------------------------------------——————————————————————————————————————————-
http://blogs.msdn.com/adonet/archive/2008/01/24/sampleedmxcodegenerator-sources.aspx
How to add custom attributes to my generated classes
——————————————————————————————————————————-
“Database Script Generation” properties:
Database Generation Workflow – Controls the overall process by which the conceptual model is translated into a database script. The default workflow is “TablePerTypeStrategy.xaml”.
DDL Generation Template – Is called by the default database generation workflow to transform the generated database model to DDL. More on this below.
First, let’s take a look at TablePerTypeStrategy.xaml – it is located in Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\DBGen. If we open this file in Visual Studio, we see that it is a Workflow Foundation (WF) workflow
The first activity, “CsdlToSsdlAndMslActivity” generates the store model (SSDL) for the EDM, and then generates the mappings (MSL) that connect the two. It has the following properties
The “MslOutputGeneratorType” specifies a class that generates MSL based on a table-per-type mapping strategy. The “OuputGeneratorType” generates SSDL. Rather than replacing this activity and all of the plumbing it provides, you can replace these two classes with your own if you want to change the mapping strategy or otherwise alter the system.
http://blogs.msdn.com/adonet/archive/2009/11/05/model-first-with-the-entity-framework-4.aspx
——————————————————————————————————————————-
Query builder methods
These methods of ObjectQuery enable you to construct queries that are the same as Entity SQL without having to construct a query string. Because these methods always return an ObjectQuery, you can build queries by calling methods in series or use them to extend an Entity SQL query. Some methods, such as Where and OrderBy, take Entity SQL fragments as parameters. Query builder methods can be followed by certain LINQ standard query operators
The ObjectQuery generic class represents a query that can return a collection of zero or more typed objects. An ObjectQuery belongs to an ObjectContext that contains the connection and metadata information that is necessary to compose and execute the query. You can construct an ObjectQuery with a new operator and pass a query string and the object context to the constructor. However, a more common scenario is to use properties on an ObjectContext derived class to get an ObjectQuery instance that represents a collection of entity sets. Typically, the ObjectContext is subclassed, either by a class generated by the Entity Framework tools or by your POCO classes, and the properties on the object context return entity sets as either an ObjectQuery (in .NET Framework version 3.5 SP1) or as an ObjectSet (in .NET Framework version 4). The ObjectSet class extends the ObjectQuery class to provide functionality, such as adding and deleting objects, in the context of a typed entity set.
This is the query builder method example.
string firstName = @"Frances";
string lastName = @"Adams";
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
// Get the contacts with the specified name.
ObjectQuery
.Where("it.LastName = @ln AND it.FirstName = @fn",
new ObjectParameter("ln", lastName),
new ObjectParameter("fn", firstName));
// Iterate through the collection of Contact items.
foreach (Contact result in contactQuery)
Console.WriteLine("Last Name: {0}; First Name: {1}",
result.LastName, result.FirstName);
}
An object query is executed when:
•It is enumerated by a foreach (C#) or For Each (Visual Basic) statement.
•It is enumerated by a collection operation such as ToArray, ToDictionary or ToList.
•The Execute method is explicitly called.
•LINQ operators such, as First or Any are specified in the outermost part of the query. For more information, see Query Builder Methods (Entity Framework).
Note, if as a result of a query execution, nothing was returned from the data source, the results will contain an empty collection and not a null.
——————————————————————————————————————————-
Entity Framework Features Not Supported by the Entity Designer
The following are Entity Framework features that are not currently supported by the Entity Designer.
•Multiple entity sets per type.
•Creating entity sets for non-root types.
•Table-per-concrete class mapping.
•Using EntityType properties in mapping conditions.
•Unmapped abstract types. When you create an abstract entity type with the Entity Designer, the type must be mapped to a table or view.
•Creating conditions on association mappings.
•Mapping associations directly to stored procedures. Mapping many-to-many associations is not supported. You can indirectly map other associations to stored procedures along with entity types by mapping the appropriate navigation properties to stored procedure parameters.
•Creating conditions on Function Import mappings.
•Annotations.
•Query views.
•Models that contain references to other models.
•Creating associations without corresponding navigation properties.
•Adding or editing storage model objects. (Deleting storage model objects is supported.)
•Adding, editing, or deleting functions that are defined in the conceptual model.
————————————————————————————————————————
Building N-Tier Applications (Entity Framework)
Entity types generated by the Entity Data Model generator tool (EdmGen.exe) and the Entity Data Model Wizard have SerializableAttribute and DataContractAttribute applied. This enables objects to be serialized by using binary serialization, XML serialization, and Windows Communication Foundation (WCF) data contract serialization.
Extending Partial Classes :: How to: Customize Generated Data Objects (Entity Framework).
When data classes are generated by the Entity Data Model tools, they are implemented in partial classes. You can add functionality to objects by extending the generated partial data classes. Having partial classes enables you to extend these classes with custom methods and properties in a separate source file without having to worry about losing your customization when the generated files are refreshed.
——————————————————————————————————————————-
Managing Connections and Transactions
By default, the Entity Framework manages the connection to the database. However, you can manually manage both connections and transactions in your Entity Framework application.
By default, the Entity Framework implements an optimistic concurrency model. This means that locks are not held on data in the data source between when the data is queried and the data is updated. The Entity Framework saves object changes to the database without checking for concurrency. For entities that might experience a high degree of concurrency, we recommend that the entity define a property in the conceptual layer with an attribute of ConcurrencyMode=”fixed”
When this attribute is used, the Entity Framework checks for changes in the database before saving changes to the database. Any conflicting changes will cause an OptimisticConcurrencyException.
An OptimisticConcurrencyException can also occur when you define an Entity Data Model that uses stored procedures to make updates to the data source. In this case, the exception is raised when the stored procedure that is used to perform updates reports that zero rows were updated.
You may choose to use transactions as an alternative to optimistic concurrency.
The Entity Framework opens connections only when required, for example to execute a query or to call SaveChanges, and then closes the connection when the operation is complete.
Calling any of the following methods opens the connection:
•SaveChanges or Refresh on ObjectContext.
•FirstOrDefault, or First on ObjectQuery.
•Load on EntityCollection.
•Load on EntityReference.
•Any Language-Integrated Query (LINQ) method or ObjectQuery query builder method, such as Where, OrderBy, or Select.
When a query method is called, the connection is opened, and it remains open until the ObjectResult has been completely consumed or disposed.
The Entity Framework supports automatic transaction enlistment. This means that activities performed within an object context, such as executing queries and saving changes to data in the data source, can be isolated in the data source by executing the operation within a System.Transactions transaction. Transactions are used in the Entity Framework to do the following actions:
•To execute multiple operations against the data source that must be highly consistent, such as queries that depend on the successful completion of object changes.
•To coordinate changes in the object context with other distributed operations, such as sending an e-mail notification or writing to a message queue.
Transactions that require the enlistment of additional resource managers are called distributed transactions. Distributed transactions use a distributed transaction coordinator (DTC) to manage the resources that are required to complete the transaction. Promotion of a transaction to a DTC can be a relatively expensive process to establish and complete. Some resource managers, like SQL Server 2005, support the Promotable Single Phase Enlistment (PSPE) transaction protocol. This allows a resource manager to host a transaction that can later be escalated to be managed by the distributed transaction coordinator (DTC) if necessary.
——————————————————————————————————————————-
•When you call SaveChanges, if a current transaction exists, the Entity Framework uses this transaction for operations against the data source. Otherwise, it creates a new transaction for the operation. You can define transactions by using EntityTransaction, Transaction, or TransactionScope.
•Promotion of a transaction to a DTC may occur when a connection is closed and reopened within a single transaction. Because the Entity Framework opens and closes the connection automatically, you should consider manually opening and closing the connection to avoid transaction promotion.
To enlist in an existing transaction, the Entity Framework might close and reopen the connection.
——————————————————————————————————————————-
This example defines a TransactionScope. The TransactionScope ensures that changes to objects in the object context are coordinated with a message queue. The Entity Framework uses this transaction when it saves changes to the database. When an UpdateException occurs, the operation is retried up to two times. When the operation succeeds, the changes in the object context are accepted. For more information, see Managing Connections and Transactions (Entity Framework).
This example uses a long-running object context, which is disposed after the transaction succeeds or after all retries have been attempted.
——————————————————————————————————————————-
http://msdn.microsoft.com/en-us/library/bb896325.aspx
The following considerations apply when you use transactions with the Entity Framework:
•Only operations against the data source are transacted. Changes made to objects in the object context are not transacted. Changes to objects in the context are visible outside the transaction scope.
•When the Entity Framework creates a new transaction for a SaveChanges operation, changes to objects in the object context are not accepted until the transaction completes. This ensures that the state of the object context and the data source are consistent.
•When you plan to retry operations in a transaction, you must ensure that the status of objects in the context is not reset before the transaction is completed. To do this, you must call SaveChanges with a value of false for the acceptChangesDuringSave parameter, and then call AcceptAllChanges only after other operations in the transaction have completed successfully.
——————————————————————————————————————————-
Managing Transactions
In the Entity Framework, there are two ways to use transactions: automatic and explicit. Automatic transactions use the System.Transactions namespace, and explicit transactions use the EntityTransaction class.
| Reactions: |
Wednesday, September 29, 2010
MSDN Magazine: ADO / ADO.NET
here you can find all the real time scenarios.
use this when u get the doubt.
use this when u get the doubt.
| Reactions: |
DataSet and DataTable in ADO.NET 2.0 Lightweight and Fast Looping
DataTableReader is a lighter weight object than the DataTable and, unlike the DataReader (SqlDataReader), the DataTableReader is disconnected.
you just brush up all the things.
you just brush up all the things.
| Reactions: |
Wednesday, September 22, 2010
Using the Visual Studio .NET 2003 Debugger with ASP.NET Applications
Refer allways the support.microsoft.
| Reactions: |
How To Raise a "File Download" Dialog Box for Excel a Known MIME Type
string fileExcel, filePath, fileName, strLine, sql;
FileStream objFileStream;
StreamWriter objStreamWriter;
fileName = @"c:\upendra\Reports.xls";
objFileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
objStreamWriter = new StreamWriter(objFileStream);
OracleConnection con=new OracleConnection("datasource:localhost;user id="name;pwd="); // change this connection.
DataSet ds = new DataSet();
con.Open();
OracleCommand cmd = new OracleCommand("USP_GET_APPLICATION_NAMES",con);
cmd.CommandType = CommandType.StoredProcedure;
//OracleDataAdapter da = new OracleDataAdapter();
OracleParameter parm;
parm = cmd.Parameters.Add("O_RESULTSET", OracleType.Cursor);
parm.Direction = ParameterDirection.Output;
OracleDataReader dr = cmd.ExecuteReader();
strLine = "";
for (int i = 0; i <= dr.FieldCount - 1; i++)
{
strLine = strLine + dr.GetName(i).ToString() + Convert.ToChar(9);
}
objStreamWriter.WriteLine(strLine);
while (dr.Read())
{
for (int i = 0; i <= dr.FieldCount - 1; i++)
{
strLine = strLine + dr.GetValue(i).ToString() + Convert.ToChar(9);
}
objStreamWriter.WriteLine(strLine);
strLine = "";
}
//Clean up.
dr.Close();
con.Close();
objStreamWriter.Close();
objFileStream.Close();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "";
response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=c:\\upendra\\Reports.xls");
//Response.TransmitFile(Server.MapPath("~\Reports.xls"));
Response.TransmitFile("c:\\upendra\\Reports.xls");
Response.End();
//Response.Write(dr.FieldCount.ToString());
FileStream objFileStream;
StreamWriter objStreamWriter;
fileName = @"c:\upendra\Reports.xls";
objFileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
objStreamWriter = new StreamWriter(objFileStream);
OracleConnection con=new OracleConnection("datasource:localhost;user id="name;pwd="); // change this connection.
DataSet ds = new DataSet();
con.Open();
OracleCommand cmd = new OracleCommand("USP_GET_APPLICATION_NAMES",con);
cmd.CommandType = CommandType.StoredProcedure;
//OracleDataAdapter da = new OracleDataAdapter();
OracleParameter parm;
parm = cmd.Parameters.Add("O_RESULTSET", OracleType.Cursor);
parm.Direction = ParameterDirection.Output;
OracleDataReader dr = cmd.ExecuteReader();
strLine = "";
for (int i = 0; i <= dr.FieldCount - 1; i++)
{
strLine = strLine + dr.GetName(i).ToString() + Convert.ToChar(9);
}
objStreamWriter.WriteLine(strLine);
while (dr.Read())
{
for (int i = 0; i <= dr.FieldCount - 1; i++)
{
strLine = strLine + dr.GetValue(i).ToString() + Convert.ToChar(9);
}
objStreamWriter.WriteLine(strLine);
strLine = "";
}
//Clean up.
dr.Close();
con.Close();
objStreamWriter.Close();
objFileStream.Close();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "";
response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=c:\\upendra\\Reports.xls");
//Response.TransmitFile(Server.MapPath("~\Reports.xls"));
Response.TransmitFile("c:\\upendra\\Reports.xls");
Response.End();
//Response.Write(dr.FieldCount.ToString());
| Reactions: |
Tuesday, August 31, 2010
Tuesday, August 24, 2010
downlod ssrs
http://www.free-ebooks-download.org/free-ebook/dotnet/SQL/learning-sql-server-2008-reporting-services.php
| Reactions: |
Monday, August 23, 2010
About the ssas Refer the Following Insetead Of timewaste
http://www.accelebrate.com/sql_training/ssas_tutorial.htm
http://www.ssas-info.com/analysis-services-articles/48-uncategorized/1151-ssas-tutorial-by-exforsys
http://www.accelebrate.com/sql_training/ssas_2008_tutorial.htm
http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx
http://www.sqlteam.com/article/using-isnull
http://www.sql-server-performance.com/articles/dba/delete_duplicates_p2.aspx
http://www.ssas-info.com/analysis-services-articles/48-uncategorized/1151-ssas-tutorial-by-exforsys
http://www.accelebrate.com/sql_training/ssas_2008_tutorial.htm
http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx
http://www.sqlteam.com/article/using-isnull
http://www.sql-server-performance.com/articles/dba/delete_duplicates_p2.aspx
| Reactions: |
Friday, August 20, 2010
Tips for Migrating Your Applications to the Cloud
Entity Framework 4.0 and WCF Data Services 4.0 in Visual Studio 2010(http://msdn.microsoft.com/en-us/magazine/ee336128.aspx)
total datagrid and some asp.net advanced.(http://msdn.microsoft.com/en-us/magazine/ee532094.aspx?sdmr=datagrid&sdmi=topics) This is one stop for all the .net needs.
The Entity Framework In Layered Architectures(http://msdn.microsoft.com/en-us/magazine/cc700340.aspx)
total datagrid and some asp.net advanced.(http://msdn.microsoft.com/en-us/magazine/ee532094.aspx?sdmr=datagrid&sdmi=topics) This is one stop for all the .net needs.
The Entity Framework In Layered Architectures(http://msdn.microsoft.com/en-us/magazine/cc700340.aspx)
| Reactions: |
The Entity Framework In Layered Architectures
Entity Framework 4.0 and WCF Data Services 4.0 in Visual Studio 2010
Tips for Migrating Your Applications to the Cloud(http://msdn.microsoft.com/en-us/magazine/ff872379.aspx).
3). The best LEarn the ssas(http://www.ssas-info.com/analysis-services-faq/29-mgmt/242-how-install-adventure-works-dw-database-analysis-services-2005-sample-database)
how to add the database to sqlserver.
Tips for Migrating Your Applications to the Cloud(http://msdn.microsoft.com/en-us/magazine/ff872379.aspx).
3). The best LEarn the ssas(http://www.ssas-info.com/analysis-services-faq/29-mgmt/242-how-install-adventure-works-dw-database-analysis-services-2005-sample-database)
how to add the database to sqlserver.
| Reactions: |
how many types of Functions
Functions
SQL Server 2000The Transact-SQL programming language provides three types of functions:
•Rowset functions
Can be used like table references in an SQL statement. For more information about a list of these functions, see Rowset Functions.
•Aggregate functions
Operate on a collection of values but return a single, summarizing value. For more information about a list of these functions, see Aggregate Functions.
•Scalar functions
Operate on a single value and then return a single value. Scalar functions can be used wherever an expression is valid. This table categorizes the scalar functions.
SQL Server 2000The Transact-SQL programming language provides three types of functions:
•Rowset functions
Can be used like table references in an SQL statement. For more information about a list of these functions, see Rowset Functions.
•Aggregate functions
Operate on a collection of values but return a single, summarizing value. For more information about a list of these functions, see Aggregate Functions.
•Scalar functions
Operate on a single value and then return a single value. Scalar functions can be used wherever an expression is valid. This table categorizes the scalar functions.
| Reactions: |
Thursday, August 19, 2010
creating own dal
http://msdn.microsoft.com/en-us/magazine/cc188750.aspx
http://www.sqlteam.com/tag/sql-server-queries ( sql queries
http://www.sqlteam.com/tag/sql-server-queries ( sql queries
| Reactions: |
Wednesday, August 18, 2010
Partitioning and Layering a Software
Hi in this blog we can learn alot about the desing and architecture of the application.
u can refert this alwas,
there given good explanation how to use interfaces and claass given good ooad.
Partitioning and Layer Fundamentals
In this module you'll learn the fundamental principles of partitioning and layering. We will start to demonstrate these principles with interface-based design.
Article: Basic Principles of Partitioning and Layering
Slide-cast: Basic Principles of Partitioning and Layering
PowerPoint: Basic Principles of Partitioning and Layering
Code-cast: Basic Principles of Partitioning and Layering
Examples: Basic Principles of Partitioning and Layering
u can refert this alwas,
there given good explanation how to use interfaces and claass given good ooad.
Partitioning and Layer Fundamentals
In this module you'll learn the fundamental principles of partitioning and layering. We will start to demonstrate these principles with interface-based design.
Article: Basic Principles of Partitioning and Layering
Slide-cast: Basic Principles of Partitioning and Layering
PowerPoint: Basic Principles of Partitioning and Layering
Code-cast: Basic Principles of Partitioning and Layering
Examples: Basic Principles of Partitioning and Layering
| Reactions: |
Thursday, August 12, 2010
ASP.NET application and page life cycle
a good one
i u want to know more about the c# use "c# tutorials".
i u want to know more about the c# use "c# tutorials".
| Reactions: |
Wednesday, August 11, 2010
about the iis
http://blogs.iis.net/bills/archive/2010/08/05/web-farm-framework-2-0-beta-released.aspx
| Reactions: |
How to set up your first IIS Web site
Configure a default Web site
When you install IIS, it is preconfigured to serve as a default Web site; however, you may want to change some of the settings. To change the basic settings for the Web site and to emulate the steps that are required to set up Apache for the first time by using the configuration file:
Log on to the Web server computer as an administrator.
Click Start, point to Settings, and then click Control Panel.
Double-click Administrative Tools, and then double-click Internet Services Manager.
Right-click the Web site that you want to configure in the left pane, and then click Properties.
Click the Web site tab.
Type a description for the Web site in the Description box.
Type the Internet Protocol (IP) address to use for the Web site or leave the All (Unassigned) default setting.
Modify the Transmission Control Protocol (TCP) port as appropriate.
Click the Home Directory tab.
To use a folder on the local computer, click A directory on this computer, and then click Browse to locate the folder that you want to use.
To use a folder that has been shared from another computer on the network, click A share located on another computer, and then either type the network path or click Browse to select the shared folder.
Click Read to grant read access to the folder (required).
Click OK to accept the Web site properties.
Back to the top
Create a new Web site
To create a new Web site in Apache, you must set up a virtual host and configure the individual settings for the host. If you are using IIS, you can create a new Web site by translating the following terms to the IIS equivalents:Collapse this tableExpand this tableApache term IIS term
DocumentRoot IIS Web Site Home Directory
ServerName IIS Host Header
Listen IIS IP Address and TCP Port
To create a new Web site in IIS, follow these steps:
Log on to the Web server computer as an administrator.
Click Start, point to Settings, and then click Control Panel.
Double-click Administrative Tools, and then double-click Internet Services Manager.
Click Action, point to New, and then click Web Site.
After the Web Site Creation Wizard starts, click Next.
Type a description for the Web site.
This description is used internally to identify the Web site in Internet Services Manager only.
Select the IP address to use for the site.
If you select All (unassigned), the Web site is accessible on all interfaces and all configured IP addresses.
Type the TCP port number to publish the site on.
Type the Host Header name (the real name that is used to access this site).
Click Next.
Either type the path to the folder that is holding the Web site documents or click Browse to select the folder, and then click Next.
Select the access permissions for the Web site, and then click Next.
Click Finish
When you install IIS, it is preconfigured to serve as a default Web site; however, you may want to change some of the settings. To change the basic settings for the Web site and to emulate the steps that are required to set up Apache for the first time by using the configuration file:
Log on to the Web server computer as an administrator.
Click Start, point to Settings, and then click Control Panel.
Double-click Administrative Tools, and then double-click Internet Services Manager.
Right-click the Web site that you want to configure in the left pane, and then click Properties.
Click the Web site tab.
Type a description for the Web site in the Description box.
Type the Internet Protocol (IP) address to use for the Web site or leave the All (Unassigned) default setting.
Modify the Transmission Control Protocol (TCP) port as appropriate.
Click the Home Directory tab.
To use a folder on the local computer, click A directory on this computer, and then click Browse to locate the folder that you want to use.
To use a folder that has been shared from another computer on the network, click A share located on another computer, and then either type the network path or click Browse to select the shared folder.
Click Read to grant read access to the folder (required).
Click OK to accept the Web site properties.
Back to the top
Create a new Web site
To create a new Web site in Apache, you must set up a virtual host and configure the individual settings for the host. If you are using IIS, you can create a new Web site by translating the following terms to the IIS equivalents:Collapse this tableExpand this tableApache term IIS term
DocumentRoot IIS Web Site Home Directory
ServerName IIS Host Header
Listen IIS IP Address and TCP Port
To create a new Web site in IIS, follow these steps:
Log on to the Web server computer as an administrator.
Click Start, point to Settings, and then click Control Panel.
Double-click Administrative Tools, and then double-click Internet Services Manager.
Click Action, point to New, and then click Web Site.
After the Web Site Creation Wizard starts, click Next.
Type a description for the Web site.
This description is used internally to identify the Web site in Internet Services Manager only.
Select the IP address to use for the site.
If you select All (unassigned), the Web site is accessible on all interfaces and all configured IP addresses.
Type the TCP port number to publish the site on.
Type the Host Header name (the real name that is used to access this site).
Click Next.
Either type the path to the folder that is holding the Web site documents or click Browse to select the folder, and then click Next.
Select the access permissions for the Web site, and then click Next.
Click Finish
| Reactions: |
How To Set Up an HTTPS Service in IIS
Upgrade your Internet experience
Don't show me this againUnited States Change | All Microsoft Sites
Microsoft Support Search Microsoft SupportSearch Microsoft.comSearch the web
Support Home Solution Centers Advanced Search Buy products
Article ID: 324069 - Last Review: November 21, 2006 - Revision: 3.3
How To Set Up an HTTPS Service in IIS
View products that this article applies to.
System Tip
This article applies to a different version of Windows than the one you are using. Content in this article may not be relevant to you.Visit the Windows XP Solution Center
This article was previously published under Q324069
On This PageSUMMARY
Configuring Your Web Server for SSL
Configure Folder or Web Site to Use SSL/HTTPS
REFERENCES
Expand all | Collapse all
SUMMARYHTTPS is a secure communications channel that is used to exchange information be...HTTPS is a secure communications channel that is used to exchange information between a client computer and a server. It uses Secure Sockets Layer (SSL). This article describes how to configure the SSL/HTTPS service in Internet Information Services (IIS) and compares this process to the similar process in Apache.
Back to the top
Configuring Your Web Server for SSL
To enable SSL in IIS, you must first obtain a certificate that is used to encrypt and decrypt the information that is transferred over the network. IIS includes its own certificate request tool that you can use to send a certificate request to a certification authority. This tool simplifies the process of obtaining a certificate. If you use Apache, you must obtain the certificate manually.
In both IIS and Apache, you receive a certificate file from the certification authority, which you must configure on the computer. Apache reads the certificate from its source file by using the SSLCACertificateFile directive. However, in IIS, you can configure and manage certificates by using the Directory Security tab of the Web site or folder properties.
You can migrate certificates from Apache to IIS; however, Microsoft recommends that you re-create or obtain a new certificate for IIS.
Configure Folder or Web Site to Use SSL/HTTPS
This procedure assumes that your site has already has a certificate assigned to it.
Log on to the Web server computer as an administrator.
Click Start, point to Settings, and then click Control Panel.
Double-click Administrative Tools, and then double click Internet Services Manager.
Select the Web site from the list of different served sites in the left pane.
Right-click the Web site, folder, or file for which you want to configure SSL communication, and then click Properties.
Click the Directory Security tab.
Click Edit.
Click Require secure-channel (SSL) if you want the Web site, folder, or file to require SSL communications.
Click Require 128-bit encryption to configure 128-bit (instead of 40-bit) encryption support.
To allow users to connect without supplying their own certificate, click Ignore client certificates.
Alternatively, to allow a user to supply their own certificate, use Accept client certificates.
To configure client mapping, click Enable client certificate mapping, and then click Edit to map client certificates to users.
If you configure this functionality, you can map client certificates to individual users in Active Directory. You can use this functionality to automatically identify a user according to the certificate they supplied when they access the Web site. You can map users to certificates on a one-to-one basis (one certificate identifies one user) or you can map many certificates to one user (a list of certificates is matched against a specific user according to specific rules. The first valid match becomes the mapping).
Click OK.
Back to the top
REFERENCESFor additional information about how to set other preferences for log files in I...For additional information about how to set other preferences for log files in IIS, click the article number below to view the article in the Microsoft Knowledge Base:
310178 (http://support.microsoft.com/kb/310178/EN-US/ ) How To Install Imported Certificates on a Web Server in Windows 2000
For additional information about securing IIS for a migration from UNIX to Windows, click the article number below to view the article in the Microsoft Knowledge Base:
324216 (http://support.microsoft.com/kb/324216/EN-US/ ) How To Secure IIS in a UNIX-to-Windows Migration
Back to the top
--------------------------------------------------------------------------------
APPLIES TO
Microsoft Windows 2000 Server
Microsoft Windows 2000 Advanced Server
Microsoft Windows 2000 Professional Edition
Microsoft Small Business Server 2000 Standard Edition
Microsoft Internet Information Services 5.0
Back to the top
Keywords: kbhowto kbhowtomaster KB324069
Back to the top
Provide feedback on this information
Did this information solve your problem?
Yes
No
I don't know
Was this information relevant?
Yes
No
What can we do to improve this information?
To protect your privacy, do not include contact information in your feedback.
Thank you! Your feedback is used to help us improve our support content. For more assistance options, please visit the Help and Support Home Page.
Other Resources
Other Support SitesSolution Centers
Microsoft Fix It Solutions
Windows Help and How-to
Office Online
Microsoft Partner Network
CommunityAnswers Forums
Technet Forums
Microsoft Developer Network (MSDN)
Get Help NowContact a Support Professional by Email, Online, or PhoneArticle TranslationsArabicCzechDutchFrenchGermanItalianJapaneseKoreanPolishPortuguese (Brazil)Portuguese (Portugal)Simplified ChineseSpanishTraditional ChineseTurkish
View related contentHow to implement SSL in IIS
How to create a secure WebDAV publishing directory
How to redirect an HTTP connection to HTTPS for Outlook Web Access ...
How to: Enable Internet Information Services (IIS)
How to set up your first IIS Web site
Search related topicsSetup https
Windows Mail设置
Windows IIS https
Https IIS support
How to enable IIS
Related Support CentersWindows 2000 Server
Windows 2000
Windows 2000 Advanced Server
Windows 2000 Professional Edition
Small Business Server 2000
Page ToolsPrint this page
E-mail this page
Get Help Now
Contact a support professional by E-mail, Online, or Phone
Microsoft Support Feedback | Services Agreement
Contact Us | Terms of Use | Trademarks | Privacy Statement
©2010 Microsoft
Don't show me this againUnited States Change | All Microsoft Sites
Microsoft Support Search Microsoft SupportSearch Microsoft.comSearch the web
Support Home Solution Centers Advanced Search Buy products
Article ID: 324069 - Last Review: November 21, 2006 - Revision: 3.3
How To Set Up an HTTPS Service in IIS
View products that this article applies to.
System Tip
This article applies to a different version of Windows than the one you are using. Content in this article may not be relevant to you.Visit the Windows XP Solution Center
This article was previously published under Q324069
On This PageSUMMARY
Configuring Your Web Server for SSL
Configure Folder or Web Site to Use SSL/HTTPS
REFERENCES
Expand all | Collapse all
SUMMARYHTTPS is a secure communications channel that is used to exchange information be...HTTPS is a secure communications channel that is used to exchange information between a client computer and a server. It uses Secure Sockets Layer (SSL). This article describes how to configure the SSL/HTTPS service in Internet Information Services (IIS) and compares this process to the similar process in Apache.
Back to the top
Configuring Your Web Server for SSL
To enable SSL in IIS, you must first obtain a certificate that is used to encrypt and decrypt the information that is transferred over the network. IIS includes its own certificate request tool that you can use to send a certificate request to a certification authority. This tool simplifies the process of obtaining a certificate. If you use Apache, you must obtain the certificate manually.
In both IIS and Apache, you receive a certificate file from the certification authority, which you must configure on the computer. Apache reads the certificate from its source file by using the SSLCACertificateFile directive. However, in IIS, you can configure and manage certificates by using the Directory Security tab of the Web site or folder properties.
You can migrate certificates from Apache to IIS; however, Microsoft recommends that you re-create or obtain a new certificate for IIS.
Configure Folder or Web Site to Use SSL/HTTPS
This procedure assumes that your site has already has a certificate assigned to it.
Log on to the Web server computer as an administrator.
Click Start, point to Settings, and then click Control Panel.
Double-click Administrative Tools, and then double click Internet Services Manager.
Select the Web site from the list of different served sites in the left pane.
Right-click the Web site, folder, or file for which you want to configure SSL communication, and then click Properties.
Click the Directory Security tab.
Click Edit.
Click Require secure-channel (SSL) if you want the Web site, folder, or file to require SSL communications.
Click Require 128-bit encryption to configure 128-bit (instead of 40-bit) encryption support.
To allow users to connect without supplying their own certificate, click Ignore client certificates.
Alternatively, to allow a user to supply their own certificate, use Accept client certificates.
To configure client mapping, click Enable client certificate mapping, and then click Edit to map client certificates to users.
If you configure this functionality, you can map client certificates to individual users in Active Directory. You can use this functionality to automatically identify a user according to the certificate they supplied when they access the Web site. You can map users to certificates on a one-to-one basis (one certificate identifies one user) or you can map many certificates to one user (a list of certificates is matched against a specific user according to specific rules. The first valid match becomes the mapping).
Click OK.
Back to the top
REFERENCESFor additional information about how to set other preferences for log files in I...For additional information about how to set other preferences for log files in IIS, click the article number below to view the article in the Microsoft Knowledge Base:
310178 (http://support.microsoft.com/kb/310178/EN-US/ ) How To Install Imported Certificates on a Web Server in Windows 2000
For additional information about securing IIS for a migration from UNIX to Windows, click the article number below to view the article in the Microsoft Knowledge Base:
324216 (http://support.microsoft.com/kb/324216/EN-US/ ) How To Secure IIS in a UNIX-to-Windows Migration
Back to the top
--------------------------------------------------------------------------------
APPLIES TO
Microsoft Windows 2000 Server
Microsoft Windows 2000 Advanced Server
Microsoft Windows 2000 Professional Edition
Microsoft Small Business Server 2000 Standard Edition
Microsoft Internet Information Services 5.0
Back to the top
Keywords: kbhowto kbhowtomaster KB324069
Back to the top
Provide feedback on this information
Did this information solve your problem?
Yes
No
I don't know
Was this information relevant?
Yes
No
What can we do to improve this information?
To protect your privacy, do not include contact information in your feedback.
Thank you! Your feedback is used to help us improve our support content. For more assistance options, please visit the Help and Support Home Page.
Other Resources
Other Support SitesSolution Centers
Microsoft Fix It Solutions
Windows Help and How-to
Office Online
Microsoft Partner Network
CommunityAnswers Forums
Technet Forums
Microsoft Developer Network (MSDN)
Get Help NowContact a Support Professional by Email, Online, or PhoneArticle TranslationsArabicCzechDutchFrenchGermanItalianJapaneseKoreanPolishPortuguese (Brazil)Portuguese (Portugal)Simplified ChineseSpanishTraditional ChineseTurkish
View related contentHow to implement SSL in IIS
How to create a secure WebDAV publishing directory
How to redirect an HTTP connection to HTTPS for Outlook Web Access ...
How to: Enable Internet Information Services (IIS)
How to set up your first IIS Web site
Search related topicsSetup https
Windows Mail设置
Windows IIS https
Https IIS support
How to enable IIS
Related Support CentersWindows 2000 Server
Windows 2000
Windows 2000 Advanced Server
Windows 2000 Professional Edition
Small Business Server 2000
Page ToolsPrint this page
E-mail this page
Get Help Now
Contact a support professional by E-mail, Online, or Phone
Microsoft Support Feedback | Services Agreement
Contact Us | Terms of Use | Trademarks | Privacy Statement
©2010 Microsoft
| Reactions: |
How to: Set Up Secure Sockets Layer (SSL)
You can optionally use the Secure Sockets Layer (SSL) protocol to secure the communication link between Visual SourceSafe clients and the server. When you configure the server for SSL, all data transmitted can be encrypted to ensure confidentiality.
Use of SSL requires a server certificate issued by a certificate authority (CA). Your company might have its own certificate. If not, you can get one from the certificate authority used by your site.
For SSL to work, you must install the server certificate on the server machine. Each client machine needing secure database access must also have a root CA certificate from the authority used by the server.
SSL only works for TCP/IP. You can configure the server to force the use of encryption for all connections.
Enabling SSL
To create a certificate
1.Ensure that Windows Server 2003 is installed on your computer.
2.Make sure that IIS is installed and enabled. For more information, see How to: Enable Internet Information Services (IIS).
3.Install Microsoft Certificate Services for your operating system, to allow creation of server authentication certificates.
Note
You can also use the SelfSSL utility from the IIS resource kit to help create an SSL certificate and assign it to IIS. For more information, download the IIS 6.0 Resource Kit Tools.
4.Start Internet Explorer and browse to Microsoft Certificate Services, for example: http://MyCA/certsrv.
5.Click Request a certificate, then click Next.
6.Click Advanced request, then click Next.
7.Click Submit a certificate request to this CA using a form, then click Next to show the certificate request form.
8.Fill in the fully qualified domain name of the server machine, for example, sq101.adventureworks.com.
9.In the Intended Purpose (or Type of Certificate Needed) field, click Server Authentication Certificate.
10.For the cryptographic service provider (CSP), select Microsoft RSA SChannel Cryptographic Provider, Microsoft Base Crypto Provider version 1.0, or Microsoft Enhanced Cryptographic Provider. Do not select the Microsoft Strong Cryptographic Provider.
11.Select the Use local machine store box.
12.Ensure that Enable strong private key protection is not selected.
13.Click Submit to send the request.
14.If the certificate server automatically issues certificates, you can install the certificate now. Otherwise, you can install it after it has been issued by the CA administrator.
To assign an SSL server certificate to a Web site
To assign an SSL server certificate to a Web site
1.In IIS Manager, expand the local computer, and then expand the Web Sites folder.
2.Right-click the Web site to which you want to assign the certificate and click Properties.
3.Select the Directory Security tab and under Secure communications, click Server Certificate.
4.In the Web Server Certificate Wizard, click Assign an existing certificate.
5.Follow the steps in the Web Server Certificate Wizard, which guides you through the process of installing a server certificate. After you have completed the wizard, you can view the information about the certificate by clicking the View Certificate button on the Directory Security tab of the Web sites Properties page.
Installing the CA Certificate
To install the CA certificate
1.Start Internet Explorer and browse to Microsoft Certificate Services, for example: http://MyCA/certsrv.
2.Select Check on a pending certificate.
3.Click Start, and then click Run.
4.Type mmc, and then click OK.
5.On the Console menu, click Add/Remove Snap-in.
6.Click Add.
7.Click Certificates and then click Add.
8.Click Computer account and then click Next.
9.Ensure that Local computer:(the server computer) is selected and click Finish.
10.Click Close.
11.In the left pane tree view, expand Certificates (Local Computer), expand Personal, and then select Certificates.
12.Verify that there is exactly one certificate with the fully qualified domain name that you specified. You can double-click to view details.
13.Distribute the public key for the certificate to users who might want to access the Visual SourceSafe database using a secure connection, for example, users of the SourceSafe Internet plug-in for Visual Studio. You can either use e-mail or copy the key from your computer to a user over the network.
See Also
Tasks
How to: Enable Internet Information Services (IIS)
Use of SSL requires a server certificate issued by a certificate authority (CA). Your company might have its own certificate. If not, you can get one from the certificate authority used by your site.
For SSL to work, you must install the server certificate on the server machine. Each client machine needing secure database access must also have a root CA certificate from the authority used by the server.
SSL only works for TCP/IP. You can configure the server to force the use of encryption for all connections.
Enabling SSL
To create a certificate
1.Ensure that Windows Server 2003 is installed on your computer.
2.Make sure that IIS is installed and enabled. For more information, see How to: Enable Internet Information Services (IIS).
3.Install Microsoft Certificate Services for your operating system, to allow creation of server authentication certificates.
Note
You can also use the SelfSSL utility from the IIS resource kit to help create an SSL certificate and assign it to IIS. For more information, download the IIS 6.0 Resource Kit Tools.
4.Start Internet Explorer and browse to Microsoft Certificate Services, for example: http://MyCA/certsrv.
5.Click Request a certificate, then click Next.
6.Click Advanced request, then click Next.
7.Click Submit a certificate request to this CA using a form, then click Next to show the certificate request form.
8.Fill in the fully qualified domain name of the server machine, for example, sq101.adventureworks.com.
9.In the Intended Purpose (or Type of Certificate Needed) field, click Server Authentication Certificate.
10.For the cryptographic service provider (CSP), select Microsoft RSA SChannel Cryptographic Provider, Microsoft Base Crypto Provider version 1.0, or Microsoft Enhanced Cryptographic Provider. Do not select the Microsoft Strong Cryptographic Provider.
11.Select the Use local machine store box.
12.Ensure that Enable strong private key protection is not selected.
13.Click Submit to send the request.
14.If the certificate server automatically issues certificates, you can install the certificate now. Otherwise, you can install it after it has been issued by the CA administrator.
To assign an SSL server certificate to a Web site
To assign an SSL server certificate to a Web site
1.In IIS Manager, expand the local computer, and then expand the Web Sites folder.
2.Right-click the Web site to which you want to assign the certificate and click Properties.
3.Select the Directory Security tab and under Secure communications, click Server Certificate.
4.In the Web Server Certificate Wizard, click Assign an existing certificate.
5.Follow the steps in the Web Server Certificate Wizard, which guides you through the process of installing a server certificate. After you have completed the wizard, you can view the information about the certificate by clicking the View Certificate button on the Directory Security tab of the Web sites Properties page.
Installing the CA Certificate
To install the CA certificate
1.Start Internet Explorer and browse to Microsoft Certificate Services, for example: http://MyCA/certsrv.
2.Select Check on a pending certificate.
3.Click Start, and then click Run.
4.Type mmc, and then click OK.
5.On the Console menu, click Add/Remove Snap-in.
6.Click Add.
7.Click Certificates and then click Add.
8.Click Computer account and then click Next.
9.Ensure that Local computer:(the server computer) is selected and click Finish.
10.Click Close.
11.In the left pane tree view, expand Certificates (Local Computer), expand Personal, and then select Certificates.
12.Verify that there is exactly one certificate with the fully qualified domain name that you specified. You can double-click to view details.
13.Distribute the public key for the certificate to users who might want to access the Visual SourceSafe database using a secure connection, for example, users of the SourceSafe Internet plug-in for Visual Studio. You can either use e-mail or copy the key from your computer to a user over the network.
See Also
Tasks
How to: Enable Internet Information Services (IIS)
| Reactions: |
How to set up SSL by using IIS 5.0 and Certificate Server 2.0
Upgrade your Internet experience
Don't show me this againUnited States Change | All Microsoft Sites
Microsoft Support Search Microsoft SupportSearch Microsoft.comSearch the web
Support Home Solution Centers Advanced Search Buy products
Article ID: 299525 - Last Review: November 21, 2006 - Revision: 3.2
How to set up SSL by using IIS 5.0 and Certificate Server 2.0
Retired KB Content Disclaimer
View products that this article applies to.
This article was previously published under Q299525
We strongly recommend that all users upgrade to Microsoft Internet Information Services (IIS) version 6.0 running on Microsoft Windows Server 2003. IIS 6.0 significantly increases Web infrastructure security. For more information about IIS security-related topics, visit the following Microsoft Web site:
http://www.microsoft.com/technet/security/prodtech/IIS.mspx (http://www.microsoft.com/technet/security/prodtech/IIS.mspx)
Expand all | Collapse all
SUMMARYThis article explains how to set up Secure Sockets Layer (SSL) on an Internet In...This article explains how to set up Secure Sockets Layer (SSL) on an Internet Information Services (IIS) version 5.0 computer, using Certificate Server 2.0 as the certificate provider.
Back to the top
MORE INFORMATIONFirst, the Web server must make a certificate request. To do this, follow these...First, the Web server must make a certificate request. To do this, follow these steps:
Start the Internet Service Manager (ISM), which loads the Internet Information Server snap-in for the Microsoft Management Console (MMC).
Right-click the Web site on which you want to enable SSL, and click Properties.
Click the Directory Security tab, and then click Server Certificate to start the Web Server Certificate Wizard.
Click Next to start the wizard, and select Create a new certificate.
Click Next, and select Prepare the request now, but send it later.
Click Next, and give your certificate a name. You may want to match it with the name of the Web site. Now, select a bit length; the higher the bit length, the stronger the certificate encryption. Select Server Gated Cryptography if your users may be coming from countries with encryption restrictions.
Click Next, and type your Organization and Organizational Unit. These values do not need to match any Active Directory entries.
Click Next, and enter the common name. The common name must match the fully qualified domain name of the server as listed in DNS. For example, if the URL is https://www.mydomain.com/securedir, then the common name must be www.mydomain.com.
Click Next, and type your country, state, and city or locality. Type the full name of your state here; do not abbreviate.
Click Next, and select a location and file name to save your request to.
Click Next twice, and then click Finish to close the wizard.
Process your request through Certificate Server. To do this, follow these steps:
Browse to http://CAServerName/CertSrv, and select Request a certificate.
Note Do not use "localhost" as the server name. If you browse from the Certificate Server computer, use the computer name instead.
Click Next and select Advanced request.
Click Next and select Submit a certificate request using a base64 encoded PKCS #10 file or a renewal request using a base64 encoded PKCS #7 file. Click Next, and open the request file that you saved from the Web Certificate Wizard in Notepad. Paste the entire text of the file, including the BEGIN and END lines, into the Base64 Encoded Certificate Request text box.
Note Depending on the configuration of the Certificate Server service, you may see radio buttons on this page instead of Additional Attributes. If the "Submit a Certificate Request or Renewal Request" page includes these radio buttons, select the Web server option. The default setting, Admin, will cause the SSL Web service to fail.
Click Submit. You may be presented with a Certificate Pending dialog box. If you are prompted for download, skip to step 2i.
Close your browser. On the Certificate Server computer, open the Certification Authority MMC.
Expand the tree underneath the server name, and select the Pending Requests folder. Right-click the certificate that you just submitted (scroll to the right for more information to determine which certificate is yours if there are several pending), click All Tasks, and then click Issue. You may now close the Certification Authority MMC.
Open a new browser window, and browse to the URL that is listed in step a. Select Check on a pending certificate.
Click Next, and select the request that you made earlier.
Click Next, select DER encoded, and then click the Download CA certificate link. Save the certificate file to your Web server's local drive, and close your Web browser.
Now, finish processing the request within IIS to install the certificate to the server, and enable SSL.
Open the Internet Information Services MMC, right-click the Web site on which you want to enable SSL, and click Properties.
Click the Directory Security tab, then click Server Certificate.
Click Next, and select Process the pending request and install the certificate.
Click Next, and enter the path and file name of the certificate that you saved in the last section.
Click Next twice, and then click Finish to complete the wizard.
Click the Web Site tab, and make sure that the SSL Port text box is populated with the port you would like SSL to run on. The default (and recommended) port is 443.
Click OK to close the Web site Properties dialog box.
You can now use SSL on your server. Test the setup by connecting to the Web site's home page by using https instead of http. You have a valid connection if the page comes up and a small lock appears in the status bar in the lower right-hand corner of the browser.
Back to the top
REFERENCESFor more information about how to connect to IIS through SSL, click the followin...For more information about how to connect to IIS through SSL, click the following article number to view the article in the Microsoft Knowledge Base:
290625 (http://support.microsoft.com/kb/290625/ ) How to configure SSL in a Windows 2000 IIS 5.0 test environment by using Certificate Server 2.0
Back to the top
--------------------------------------------------------------------------------
APPLIES TO
Microsoft Internet Information Services 5.0
Microsoft Certificate Services 2.0
Back to the top
Keywords: kbhowto KB299525
Back to the top
Retired KB Content Disclaimer
This article was written about products for which Microsoft no longer offers support. Therefore, this article is offered "as is" and will no longer be updated.
Back to the top
Provide feedback on this information
Did this information solve your problem?
Yes
No
I don't know
Was this information relevant?
Yes
No
How much effort did you personally put forth to use this article?
Very low
Low
Moderate
High
Very high
What can we do to improve this information?
To protect your privacy, do not include contact information in your feedback.
Thank you! Your feedback is used to help us improve our support content. For more assistance options, please visit the Help and Support Home Page.
Other Resources
Other Support SitesSolution Centers
Microsoft Fix It Solutions
Windows Help and How-to
Office Online
Microsoft Partner Network
CommunityAnswers Forums
Technet Forums
Microsoft Developer Network (MSDN)
Get Help NowContact a Support Professional by Email, Online, or PhoneArticle TranslationsArabicCzechFrenchGermanItalianJapaneseKoreanPortuguese (Brazil)Portuguese (Portugal)Simplified ChineseSpanishTraditional ChineseTurkish
View related contentHow to implement SSL in IIS
Building Secure ASP.NET Applications: Authentication, Authorization ...
How To Set Up an HTTPS Service in IIS
How to configure Certificate Services and ISA Server to publish CRLs
Step 4: Enabling Secure Sockets Layer in IIS
Search related topicsHow to set up SSL using IIS 5.0 and cer...
Microsoft Certificate Server version 2....
How to back up a server certificate in ...
Microsoft Certificate Services 2.0
How to set up a website on Windows serv...
Page ToolsPrint this page
E-mail this page
Get Help Now
Contact a support professional by E-mail, Online, or Phone
Microsoft Support Feedback | Services Agreement
Contact Us | Terms of Use | Trademarks | Privacy Statement
©2010 Microsoft
Don't show me this againUnited States Change | All Microsoft Sites
Microsoft Support Search Microsoft SupportSearch Microsoft.comSearch the web
Support Home Solution Centers Advanced Search Buy products
Article ID: 299525 - Last Review: November 21, 2006 - Revision: 3.2
How to set up SSL by using IIS 5.0 and Certificate Server 2.0
Retired KB Content Disclaimer
View products that this article applies to.
This article was previously published under Q299525
We strongly recommend that all users upgrade to Microsoft Internet Information Services (IIS) version 6.0 running on Microsoft Windows Server 2003. IIS 6.0 significantly increases Web infrastructure security. For more information about IIS security-related topics, visit the following Microsoft Web site:
http://www.microsoft.com/technet/security/prodtech/IIS.mspx (http://www.microsoft.com/technet/security/prodtech/IIS.mspx)
Expand all | Collapse all
SUMMARYThis article explains how to set up Secure Sockets Layer (SSL) on an Internet In...This article explains how to set up Secure Sockets Layer (SSL) on an Internet Information Services (IIS) version 5.0 computer, using Certificate Server 2.0 as the certificate provider.
Back to the top
MORE INFORMATIONFirst, the Web server must make a certificate request. To do this, follow these...First, the Web server must make a certificate request. To do this, follow these steps:
Start the Internet Service Manager (ISM), which loads the Internet Information Server snap-in for the Microsoft Management Console (MMC).
Right-click the Web site on which you want to enable SSL, and click Properties.
Click the Directory Security tab, and then click Server Certificate to start the Web Server Certificate Wizard.
Click Next to start the wizard, and select Create a new certificate.
Click Next, and select Prepare the request now, but send it later.
Click Next, and give your certificate a name. You may want to match it with the name of the Web site. Now, select a bit length; the higher the bit length, the stronger the certificate encryption. Select Server Gated Cryptography if your users may be coming from countries with encryption restrictions.
Click Next, and type your Organization and Organizational Unit. These values do not need to match any Active Directory entries.
Click Next, and enter the common name. The common name must match the fully qualified domain name of the server as listed in DNS. For example, if the URL is https://www.mydomain.com/securedir, then the common name must be www.mydomain.com.
Click Next, and type your country, state, and city or locality. Type the full name of your state here; do not abbreviate.
Click Next, and select a location and file name to save your request to.
Click Next twice, and then click Finish to close the wizard.
Process your request through Certificate Server. To do this, follow these steps:
Browse to http://CAServerName/CertSrv, and select Request a certificate.
Note Do not use "localhost" as the server name. If you browse from the Certificate Server computer, use the computer name instead.
Click Next and select Advanced request.
Click Next and select Submit a certificate request using a base64 encoded PKCS #10 file or a renewal request using a base64 encoded PKCS #7 file. Click Next, and open the request file that you saved from the Web Certificate Wizard in Notepad. Paste the entire text of the file, including the BEGIN and END lines, into the Base64 Encoded Certificate Request text box.
Note Depending on the configuration of the Certificate Server service, you may see radio buttons on this page instead of Additional Attributes. If the "Submit a Certificate Request or Renewal Request" page includes these radio buttons, select the Web server option. The default setting, Admin, will cause the SSL Web service to fail.
Click Submit. You may be presented with a Certificate Pending dialog box. If you are prompted for download, skip to step 2i.
Close your browser. On the Certificate Server computer, open the Certification Authority MMC.
Expand the tree underneath the server name, and select the Pending Requests folder. Right-click the certificate that you just submitted (scroll to the right for more information to determine which certificate is yours if there are several pending), click All Tasks, and then click Issue. You may now close the Certification Authority MMC.
Open a new browser window, and browse to the URL that is listed in step a. Select Check on a pending certificate.
Click Next, and select the request that you made earlier.
Click Next, select DER encoded, and then click the Download CA certificate link. Save the certificate file to your Web server's local drive, and close your Web browser.
Now, finish processing the request within IIS to install the certificate to the server, and enable SSL.
Open the Internet Information Services MMC, right-click the Web site on which you want to enable SSL, and click Properties.
Click the Directory Security tab, then click Server Certificate.
Click Next, and select Process the pending request and install the certificate.
Click Next, and enter the path and file name of the certificate that you saved in the last section.
Click Next twice, and then click Finish to complete the wizard.
Click the Web Site tab, and make sure that the SSL Port text box is populated with the port you would like SSL to run on. The default (and recommended) port is 443.
Click OK to close the Web site Properties dialog box.
You can now use SSL on your server. Test the setup by connecting to the Web site's home page by using https instead of http. You have a valid connection if the page comes up and a small lock appears in the status bar in the lower right-hand corner of the browser.
Back to the top
REFERENCESFor more information about how to connect to IIS through SSL, click the followin...For more information about how to connect to IIS through SSL, click the following article number to view the article in the Microsoft Knowledge Base:
290625 (http://support.microsoft.com/kb/290625/ ) How to configure SSL in a Windows 2000 IIS 5.0 test environment by using Certificate Server 2.0
Back to the top
--------------------------------------------------------------------------------
APPLIES TO
Microsoft Internet Information Services 5.0
Microsoft Certificate Services 2.0
Back to the top
Keywords: kbhowto KB299525
Back to the top
Retired KB Content Disclaimer
This article was written about products for which Microsoft no longer offers support. Therefore, this article is offered "as is" and will no longer be updated.
Back to the top
Provide feedback on this information
Did this information solve your problem?
Yes
No
I don't know
Was this information relevant?
Yes
No
How much effort did you personally put forth to use this article?
Very low
Low
Moderate
High
Very high
What can we do to improve this information?
To protect your privacy, do not include contact information in your feedback.
Thank you! Your feedback is used to help us improve our support content. For more assistance options, please visit the Help and Support Home Page.
Other Resources
Other Support SitesSolution Centers
Microsoft Fix It Solutions
Windows Help and How-to
Office Online
Microsoft Partner Network
CommunityAnswers Forums
Technet Forums
Microsoft Developer Network (MSDN)
Get Help NowContact a Support Professional by Email, Online, or PhoneArticle TranslationsArabicCzechFrenchGermanItalianJapaneseKoreanPortuguese (Brazil)Portuguese (Portugal)Simplified ChineseSpanishTraditional ChineseTurkish
View related contentHow to implement SSL in IIS
Building Secure ASP.NET Applications: Authentication, Authorization ...
How To Set Up an HTTPS Service in IIS
How to configure Certificate Services and ISA Server to publish CRLs
Step 4: Enabling Secure Sockets Layer in IIS
Search related topicsHow to set up SSL using IIS 5.0 and cer...
Microsoft Certificate Server version 2....
How to back up a server certificate in ...
Microsoft Certificate Services 2.0
How to set up a website on Windows serv...
Page ToolsPrint this page
E-mail this page
Get Help Now
Contact a support professional by E-mail, Online, or Phone
Microsoft Support Feedback | Services Agreement
Contact Us | Terms of Use | Trademarks | Privacy Statement
©2010 Microsoft
| Reactions: |
Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication
How To: Call a Web Service Using SSL from ASP.NET 1.1
J.D. Meier, Alex Mackman, Michael Dunner, and Srinath Vasireddy
Microsoft Corporation
Published: November 2002
Last Revised: January 2006
Applies to:
•ASP.NET 1.1
•Internet Information Services (IIS) 5.0 and 5.1
•Microsoft® Windows Server 2000
See the "patterns & practices Security Guidance for Applications Index" for links to additional security resources.
See the Landing Page for a starting point and complete overview of Building Secure ASP.NET Applications.
Summary: Secure Sockets Layer (SSL) encryption can be used to guarantee the integrity and confidentiality of the messages passed to and from a Web service.
This How To shows you how to use SSL with Web services. (7 printed pages)
Contents
Summary of Steps Step 1. Install Server Certificates on the Web Server Step 2. Create a Simple Web Service Step 3. Configure the Web Service Virtual Directory to Require SSL Step 4. Test the Web Service Using a Browser Step 5. Install the Certificate Authority's Certificate on the Client Computer Step 6. Develop a Web Application to Call the Serviced Component
Additional Resources
You can configure a Web service to require Secure Sockets Layer (SSL) to protect sensitive data sent between the client and the service. SSL provides:
•Message integrity. This ensures that messages are not modified while in transit.
•Message confidentiality. This ensures that messages remain private while in transit.
This How To describes how to configure a Web service to require SSL and how to call the Web service from an ASP.NET client application by using the HTTPS protocol.
Summary of Steps
This article includes the following steps:
•Step 1. Install Server Certificates on the Web Server
•Step 2. Create a Simple Web Service
•Step 3. Configure the Web Service Virtual Directory to Require SSL
•Step 4. Test the Web Service Using a Browser
•Step 5. Install the Certificate Authority's Certificate on the Client Computer
•Step 6. Develop a Web Application to Call the Serviced Component
Step 1. Install Server Certificates on the Web Server
For information about installing Web server certificates on a Web server, see How To: Set Up SSL on a Web Server.
Step 2. Create a Simple Web Service
To create a simple Web service on the Web service host computer
1.Start Visual Studio .NET and create a new C# ASP.NET Web Service application called SecureMath.
2.Rename service1.asmx as math.asmx.
3.Open math.asmx.cs and rename the Service1 class as math.
4.Add the following Web method to the math class.
[WebMethod]
public long Add(long operand1, long operand2)
{
return (operand1 + operand2);
}
5.To create the Web service, click BuildSolution on the Build menu.
Step 3. Configure the Web Service Virtual Directory to Require SSL
Your Web service runs on Internet Information Services (IIS) and relies on IIS to provide SSL support.
This procedure assumes that you have a valid server certificate installed on your Web server. For more information about installing Web server certificates, see How To: Set Up SSL on a Web Server.
To use IIS to configure your Web service's virtual directory for SSL
1.On the Web service host computer, start IIS.
2.Navigate to the SecureMath virtual directory.
3.Right-click SecureMath, and then click Properties.
4.Click the Directory Security tab.
5.Under Secure communications, click Edit.
If Edit is unavailable, it is likely that a Web server certificate is not installed.
6.Select the Require secure channel (SSL) check box.
7.Click OK, and then OK again.
8.In the Inheritance Overrides dialog box, click Select All, and then click OK to close the SecureMath properties dialog box.
This applies the new security settings to all subdirectories in the virtual directory root.
Step 4. Test the Web Service Using a Browser
This procedure ensures that the Web server certificate is valid and has been issued by a Certification Authority (CA) that is trusted by the client computer.
To call the Web service using SSL from Internet Explorer
1.Start Internet Explorer on the client computer and browse (using HTTPS) to the Web service. For example:
https://WebServer/securemath/math.asmx
The Web service test page should be displayed by the browser.
2.If the Web service test page is displayed successfully, close Internet Explorer and go to Procedure 5, "Develop a Web Application to Call the Serviced Component."
3.If the Security Alert dialog box, as illustrated in Figure 1, is displayed, click View Certificate to see the identity of the issuing CA for the Web server certificate. You must install the CA's certificate on the client computer. This is described in Procedure 4, "Install the Certificate Authority's Certificate on the Client Computer."
4.Close Internet Explorer.
Figure 1. Security Alert dialog box
Step 5. Install the Certificate Authority's Certificate on the Client Computer
This procedure installs the issuing CA's certificate on the client computer as a trusted root certificate authority. The client computer must trust the issuing CA in order to accept the server certificate without displaying the Security Alert dialog box.
If you use Microsoft Certificate Services as a CA within your Windows domain
Perform this procedure only if your Web server certificate was issued by a Microsoft Certificate Services CA. Otherwise, if you have the CA's .cer file, go to Step 8.
1.Start Internet Explorer and browse to http:// hostname/certsrv, where hostname is the name of the computer where Microsoft Certificate Services that issued the server certificate is located.
2.Click Retrieve the CA certificate or certificate revocation list, and then click Next.
3.Click Install this CA certification path.
4.In the Root Certificate Store dialog box, click Yes.
5.Browse to Web service using HTTPS. For example:
https://WebServer/securemath/math.asmx
The Web service test page should now be correctly displayed by the browser, without a Security Alert dialog box.
You have now installed the CA's certificate in your personal trusted root certificate store. To be able to call the Web service successfully from an ASP.NET page, you must add the CA's certificate to the computer's trusted root store.
6.Repeat Steps 1 and 2, click Download CA certificate, and then save it to a file on your local computer.
7.Now perform the remaining steps, if you have the CA's .cer certificate file.
8.On the taskbar, click Start, and then click Run.
9.Type mmc, and then click OK.
10.On the Console menu, click Add/Remove Snap-in.
11.Click Add.
12.Select Certificates, and then click Add.
13.Select Computer account, and then click Next.
14.Select LocalComputer: (the computer this console is running on), and then click Finish.
15.Click Close, and then OK.
16.Expand Certificates (Local Computer) in the left pane of the MMC snap-in.
17.Expand Trusted Root Certification Authorities.
18.Right-click Certificates, point to All Tasks, and then click Import.
19.Click Next to move past the Welcome dialog box of the Certificate Import Wizard.
20.Enter the path and filename of the CA's .cer file.
21.Click Next.
22.Select Place all certificates in the following store, and then click Browse.
23.Select Show physical stores.
24.Expand Trusted Root Certification Authorities within the list, and then select Local Computer.
25.Click OK, click Next, and then click Finish.
26.Click OK to close the confirmation message box.
27.Refresh the view of the Certificates folder within the MMC snap-in and confirm that the CA's certificate is listed.
28.Close the MMC snap-in.
Step 6. Develop a Web Application to Call the Web Service
This procedure creates a simple ASP.NET Web application. You will use this ASP.NET Web application as the client application to call the Web service.
To create a simple ASP.NET Web application
1.On the Web service client computer, create a new C# ASP.NET Web application called SecureMathClient.
2.Add a Web reference (by using HTTPS) to the Web service.
1.Right-click the References node within Solution Explorer, and then click Add Web Reference.
2.In the Add Web Reference dialog box, enter the URL of your Web service. Make sure you use an HTTPS URL.
Note If you have already set a Web reference to a Web service without using HTTPS, you can manually edit the generated proxy class file and change the line of code that sets the Url property from an HTTP URL to an HTTPS URL.
3.Click Add Reference.
3.Open WebForm1.aspx.cs and add the following using statement beneath the existing using statements.
using SecureMathClient.WebReference1;
4.View WebForm1.aspx in Designer mode and create a form like the one illustrated in Figure 2 using the following IDs:
◦operand1
◦operand2
◦result
◦add
Figure 2. WebForm1.aspx form
5.Double-click the Add button to create a button-click event hander.
6.Add the following code to the event handler.
private void add_Click(object sender, System.EventArgs e)
{
math mathService = new math();
int addResult = (int) mathService.Add( Int32.Parse(operand1.Text),
Int32.Parse(operand2.Text));
result.Text = addResult.ToString();
}
7.On the Build menu, click BuildSolution.
8.Run the application. Enter two numbers to add, and then click the Add button.
The Web application will call the Web service using SSL.
Additional Resources
•How To: Set Up SSL on a Web Server
•How To: Call a Web Service Using Client Certificates from ASP.NET 1.1
J.D. Meier, Alex Mackman, Michael Dunner, and Srinath Vasireddy
Microsoft Corporation
Published: November 2002
Last Revised: January 2006
Applies to:
•ASP.NET 1.1
•Internet Information Services (IIS) 5.0 and 5.1
•Microsoft® Windows Server 2000
See the "patterns & practices Security Guidance for Applications Index" for links to additional security resources.
See the Landing Page for a starting point and complete overview of Building Secure ASP.NET Applications.
Summary: Secure Sockets Layer (SSL) encryption can be used to guarantee the integrity and confidentiality of the messages passed to and from a Web service.
This How To shows you how to use SSL with Web services. (7 printed pages)
Contents
Summary of Steps Step 1. Install Server Certificates on the Web Server Step 2. Create a Simple Web Service Step 3. Configure the Web Service Virtual Directory to Require SSL Step 4. Test the Web Service Using a Browser Step 5. Install the Certificate Authority's Certificate on the Client Computer Step 6. Develop a Web Application to Call the Serviced Component
Additional Resources
You can configure a Web service to require Secure Sockets Layer (SSL) to protect sensitive data sent between the client and the service. SSL provides:
•Message integrity. This ensures that messages are not modified while in transit.
•Message confidentiality. This ensures that messages remain private while in transit.
This How To describes how to configure a Web service to require SSL and how to call the Web service from an ASP.NET client application by using the HTTPS protocol.
Summary of Steps
This article includes the following steps:
•Step 1. Install Server Certificates on the Web Server
•Step 2. Create a Simple Web Service
•Step 3. Configure the Web Service Virtual Directory to Require SSL
•Step 4. Test the Web Service Using a Browser
•Step 5. Install the Certificate Authority's Certificate on the Client Computer
•Step 6. Develop a Web Application to Call the Serviced Component
Step 1. Install Server Certificates on the Web Server
For information about installing Web server certificates on a Web server, see How To: Set Up SSL on a Web Server.
Step 2. Create a Simple Web Service
To create a simple Web service on the Web service host computer
1.Start Visual Studio .NET and create a new C# ASP.NET Web Service application called SecureMath.
2.Rename service1.asmx as math.asmx.
3.Open math.asmx.cs and rename the Service1 class as math.
4.Add the following Web method to the math class.
[WebMethod]
public long Add(long operand1, long operand2)
{
return (operand1 + operand2);
}
5.To create the Web service, click BuildSolution on the Build menu.
Step 3. Configure the Web Service Virtual Directory to Require SSL
Your Web service runs on Internet Information Services (IIS) and relies on IIS to provide SSL support.
This procedure assumes that you have a valid server certificate installed on your Web server. For more information about installing Web server certificates, see How To: Set Up SSL on a Web Server.
To use IIS to configure your Web service's virtual directory for SSL
1.On the Web service host computer, start IIS.
2.Navigate to the SecureMath virtual directory.
3.Right-click SecureMath, and then click Properties.
4.Click the Directory Security tab.
5.Under Secure communications, click Edit.
If Edit is unavailable, it is likely that a Web server certificate is not installed.
6.Select the Require secure channel (SSL) check box.
7.Click OK, and then OK again.
8.In the Inheritance Overrides dialog box, click Select All, and then click OK to close the SecureMath properties dialog box.
This applies the new security settings to all subdirectories in the virtual directory root.
Step 4. Test the Web Service Using a Browser
This procedure ensures that the Web server certificate is valid and has been issued by a Certification Authority (CA) that is trusted by the client computer.
To call the Web service using SSL from Internet Explorer
1.Start Internet Explorer on the client computer and browse (using HTTPS) to the Web service. For example:
https://WebServer/securemath/math.asmx
The Web service test page should be displayed by the browser.
2.If the Web service test page is displayed successfully, close Internet Explorer and go to Procedure 5, "Develop a Web Application to Call the Serviced Component."
3.If the Security Alert dialog box, as illustrated in Figure 1, is displayed, click View Certificate to see the identity of the issuing CA for the Web server certificate. You must install the CA's certificate on the client computer. This is described in Procedure 4, "Install the Certificate Authority's Certificate on the Client Computer."
4.Close Internet Explorer.
Figure 1. Security Alert dialog box
Step 5. Install the Certificate Authority's Certificate on the Client Computer
This procedure installs the issuing CA's certificate on the client computer as a trusted root certificate authority. The client computer must trust the issuing CA in order to accept the server certificate without displaying the Security Alert dialog box.
If you use Microsoft Certificate Services as a CA within your Windows domain
Perform this procedure only if your Web server certificate was issued by a Microsoft Certificate Services CA. Otherwise, if you have the CA's .cer file, go to Step 8.
1.Start Internet Explorer and browse to http:// hostname/certsrv, where hostname is the name of the computer where Microsoft Certificate Services that issued the server certificate is located.
2.Click Retrieve the CA certificate or certificate revocation list, and then click Next.
3.Click Install this CA certification path.
4.In the Root Certificate Store dialog box, click Yes.
5.Browse to Web service using HTTPS. For example:
https://WebServer/securemath/math.asmx
The Web service test page should now be correctly displayed by the browser, without a Security Alert dialog box.
You have now installed the CA's certificate in your personal trusted root certificate store. To be able to call the Web service successfully from an ASP.NET page, you must add the CA's certificate to the computer's trusted root store.
6.Repeat Steps 1 and 2, click Download CA certificate, and then save it to a file on your local computer.
7.Now perform the remaining steps, if you have the CA's .cer certificate file.
8.On the taskbar, click Start, and then click Run.
9.Type mmc, and then click OK.
10.On the Console menu, click Add/Remove Snap-in.
11.Click Add.
12.Select Certificates, and then click Add.
13.Select Computer account, and then click Next.
14.Select LocalComputer: (the computer this console is running on), and then click Finish.
15.Click Close, and then OK.
16.Expand Certificates (Local Computer) in the left pane of the MMC snap-in.
17.Expand Trusted Root Certification Authorities.
18.Right-click Certificates, point to All Tasks, and then click Import.
19.Click Next to move past the Welcome dialog box of the Certificate Import Wizard.
20.Enter the path and filename of the CA's .cer file.
21.Click Next.
22.Select Place all certificates in the following store, and then click Browse.
23.Select Show physical stores.
24.Expand Trusted Root Certification Authorities within the list, and then select Local Computer.
25.Click OK, click Next, and then click Finish.
26.Click OK to close the confirmation message box.
27.Refresh the view of the Certificates folder within the MMC snap-in and confirm that the CA's certificate is listed.
28.Close the MMC snap-in.
Step 6. Develop a Web Application to Call the Web Service
This procedure creates a simple ASP.NET Web application. You will use this ASP.NET Web application as the client application to call the Web service.
To create a simple ASP.NET Web application
1.On the Web service client computer, create a new C# ASP.NET Web application called SecureMathClient.
2.Add a Web reference (by using HTTPS) to the Web service.
1.Right-click the References node within Solution Explorer, and then click Add Web Reference.
2.In the Add Web Reference dialog box, enter the URL of your Web service. Make sure you use an HTTPS URL.
Note If you have already set a Web reference to a Web service without using HTTPS, you can manually edit the generated proxy class file and change the line of code that sets the Url property from an HTTP URL to an HTTPS URL.
3.Click Add Reference.
3.Open WebForm1.aspx.cs and add the following using statement beneath the existing using statements.
using SecureMathClient.WebReference1;
4.View WebForm1.aspx in Designer mode and create a form like the one illustrated in Figure 2 using the following IDs:
◦operand1
◦operand2
◦result
◦add
Figure 2. WebForm1.aspx form
5.Double-click the Add button to create a button-click event hander.
6.Add the following code to the event handler.
private void add_Click(object sender, System.EventArgs e)
{
math mathService = new math();
int addResult = (int) mathService.Add( Int32.Parse(operand1.Text),
Int32.Parse(operand2.Text));
result.Text = addResult.ToString();
}
7.On the Build menu, click BuildSolution.
8.Run the application. Enter two numbers to add, and then click the Add button.
The Web application will call the Web service using SSL.
Additional Resources
•How To: Set Up SSL on a Web Server
•How To: Call a Web Service Using Client Certificates from ASP.NET 1.1
| Reactions: |
Wednesday, August 4, 2010
LINQ Framework Design Guidelines
Writing applications that interact with data sources, such as databases, XML documents, or Web Services such as Flickr or Amazon, is made easier in the .NET Framework 3.5 with the addition of a set of features collectively referred to as LINQ (Language-Integrated Query). In what follows, we start with a very brief overview of LINQ, followed by guidelines for designing APIs in relation to LINQ.
1. A Brief Overview of LINQ
Quite often, programming requires processing over sets of values. Some probably well known examples include: extracting the list of the most recently added books from a database of products; or finding the email address of a person in a directory service such as Active Directory; or transforming parts of an XML document to HTML to allow for web publishing; or something as frequent as looking up a value in a hash table.
LINQ allows for a uniform, language-integrated programming model with data, independent of the technology used to store that data.
In terms of concrete libraries, LINQ is embodied as:
· A specification in C# and VB of the notion of “extension methods”
· The Query Pattern, a specification of the set of methods a type must provide in order to be considered as a LINQ provider. The names of these methods can be found in System.Linq.Enumerable (found in System.Core.dll). Their signature follows a pattern that will be discussed later in this chapter.
· A definition of a new interface, IQueryable:IEnumerable
· New types representing generic delegates: Func<> and Action<>
· Lambda expressions, a language feature in VB and C# for defining anonymous delegates
· A type representing the notion of a delay-compiled delegate, the Expression<> family of types.
· An extension to the C# and VB syntax allowing for queries to be expressed in an alternative, SQL-like format. For example (C#):
//using extension methods:
IEnumerable names = set.Where(x=>x.Age>20).Select(x=>x.Name);
//using SQL-like syntax:
IEnumerable names = from x in set where x.Age>20
select x.Name;
The interplay between these features is the following: any IEnumerable<> can be queried upon using the LINQ extension methods, most of which require one or more lambda expressions as parameters; this leads to an in-memory, generic evaluation of the queries. For cases where the set of data is not in memory (e.g. in a database), and/or queries may be optimized, the set of data is presented as an IQueryable<>. If lambda expressions are given as parameters, they are transformed by the compiler to Expression<> objects. The implementation of IQueryable<> is responsible for processing said expressions. For example, the implementation of an IQueryable<> representing a database table would translate Expression<> objects to SQL queries.
2. Extension Methods, Func<>, Action<>, and Expression<>
Extension methods constitute a language feature that allows static methods to be invoked on instance variables. These methods must take at least one parameter, which represents the instance the method is to operate on. For example, in C#, this is done by using the this modifier on such a parameter, when defining the method:
public static bool IsPalindrome(this string s){
//implementation follows here
}
This example allows one to write, for example:
“some string”.IsPalindrome();
...which in this case would result in false being displayed on the console.
The class that defines such extension methods is referred to in this text as “sponsor” class, and it must be declared as static. To use extension methods, one must import the namespace defining their sponsor class.
Func<> objects represent a generic delegate. For example:
Func divide=(x,y)=>(double)x/(double)y;
Console.WriteLine(divide(2,3));
In this example, divide is a function that takes two integers and returns a double. The last parameter in the generic definition of a Func<> is always the return type. To represent void-returning functions, use Action<> instead. For example:
Action write=(aDouble)=>Console.WriteLine(aDouble);
write(divide(2,3));
Expression<> objects represent function definitions that can be compiled and subsequently invoked at runtime. Continuing with our example:
Expression> divideBody=(x,y)=>(double)x/(double)y;
Func divide2=divideBody.Compile();
write(divide2(2,3));
Notice how the syntax for constructing an Expression<> object is very similar to the one used to construct a Func<> object; in fact, the only difference is the static type declaration of the variable (Expression<> instead of Func<>).
1. A Brief Overview of LINQ
Quite often, programming requires processing over sets of values. Some probably well known examples include: extracting the list of the most recently added books from a database of products; or finding the email address of a person in a directory service such as Active Directory; or transforming parts of an XML document to HTML to allow for web publishing; or something as frequent as looking up a value in a hash table.
LINQ allows for a uniform, language-integrated programming model with data, independent of the technology used to store that data.
In terms of concrete libraries, LINQ is embodied as:
· A specification in C# and VB of the notion of “extension methods”
· The Query Pattern, a specification of the set of methods a type must provide in order to be considered as a LINQ provider. The names of these methods can be found in System.Linq.Enumerable (found in System.Core.dll). Their signature follows a pattern that will be discussed later in this chapter.
· A definition of a new interface, IQueryable
· New types representing generic delegates: Func<> and Action<>
· Lambda expressions, a language feature in VB and C# for defining anonymous delegates
· A type representing the notion of a delay-compiled delegate, the Expression<> family of types.
· An extension to the C# and VB syntax allowing for queries to be expressed in an alternative, SQL-like format. For example (C#):
//using extension methods:
IEnumerable
//using SQL-like syntax:
IEnumerable
select x.Name;
The interplay between these features is the following: any IEnumerable<> can be queried upon using the LINQ extension methods, most of which require one or more lambda expressions as parameters; this leads to an in-memory, generic evaluation of the queries. For cases where the set of data is not in memory (e.g. in a database), and/or queries may be optimized, the set of data is presented as an IQueryable<>. If lambda expressions are given as parameters, they are transformed by the compiler to Expression<> objects. The implementation of IQueryable<> is responsible for processing said expressions. For example, the implementation of an IQueryable<> representing a database table would translate Expression<> objects to SQL queries.
2. Extension Methods, Func<>, Action<>, and Expression<>
Extension methods constitute a language feature that allows static methods to be invoked on instance variables. These methods must take at least one parameter, which represents the instance the method is to operate on. For example, in C#, this is done by using the this modifier on such a parameter, when defining the method:
public static bool IsPalindrome(this string s){
//implementation follows here
}
This example allows one to write, for example:
“some string”.IsPalindrome();
...which in this case would result in false being displayed on the console.
The class that defines such extension methods is referred to in this text as “sponsor” class, and it must be declared as static. To use extension methods, one must import the namespace defining their sponsor class.
Func<> objects represent a generic delegate. For example:
Func
Console.WriteLine(divide(2,3));
In this example, divide is a function that takes two integers and returns a double. The last parameter in the generic definition of a Func<> is always the return type. To represent void-returning functions, use Action<> instead. For example:
Action
write(divide(2,3));
Expression<> objects represent function definitions that can be compiled and subsequently invoked at runtime. Continuing with our example:
Expression
Func
write(divide2(2,3));
Notice how the syntax for constructing an Expression<> object is very similar to the one used to construct a Func<> object; in fact, the only difference is the static type declaration of the variable (Expression<> instead of Func<>).
| Reactions: |
Tuesday, August 3, 2010
The "Nested WHERE-IN" SQL Anti-Pattern
There's a fascinating technique that I see many beginners use when writing SQL statements, and I call it the "Nested WHERE-IN" anti-pattern. It is, unfortunately, a common SQL technique used to avoid JOINS at all costs. For example, using Northwind, suppose we want to find all customers that have ordered ProductID 1. The Nested WHERE-IN technique results in code like this:
select *
from Customers
where CustomerID in
(select customerID
from Orders
where OrderID in
(select orderID
from [Order Details]
where ProductID = 1
)
)
That's just a simple example, but of course it gets nested more deeply (or branches out) as more conditions are added.
I think beginners gravitate towards this approach because:
1.No "tricky" joins are required
2.It is written more or less the way you would describe what you want: "return customers that have an Order that has ProductID 1 in it."
3.No "strange" duplication of results occur, which can happen with joins if you don't group things properly
In short, I think this technique surfaces because you can just start writing, without any planning or thinking, and the code sort of naturally comes out as you go. And, it does technically return the right results most of the time, so there doesn't seem to be a reason not to do things this way.
So, you might ask, how would you suggest that it should be written? As I often say, break it down into small, separate parts and put them all together in the end. Our first task is to write a SELECT that returns a distinct list of CustomerID's that have ordered productID 1:
select o.customerID
from orders o
inner join [order details] od on od.orderID = o.orderID
where od.productID = 1
group by o.customerID
With that, we know we can simply inner join from the customers table to this and our Customer table will be filtered with the exact results we need:
select c.*
from customers c
inner join
(
select o.customerID
from orders o
inner join [order details] od on od.orderID = o.orderID
where od.productID = 1
group by o.customerID
) x on c.CustomerID = x.CustomerID
Now, if we look at the execution plans of the two techniques, we will actually see that (in SQL 2000, anyway) they are exactly the same. So, what's the problem? Why shouldn't you use the "Nested WHERE-IN" anti-pattern?
Well, the main issue is maintainability, and how it affects not only the complexity of the SELECT, but performance as well.
Let's suppose we also need to return the total number of times that ProductID 1 has been ordered for each customer. The Nested WHERE-IN SELECT has no way to do this; our only option is to add a correlated subquery or an additional JOIN. Since we are avoiding JOINS in general with this approach, let's use a corrected sub-query:
select *, (select count(*)
from orders
where orderID in
(select orderID
from orders
where orders.customerID=customers.customerID)) as num
from Customers
where CustomerID in
(select customerID
from Orders
where OrderID in
(select orderID
from [Order Details]
where ProductID = 1
)
)
Notice the redundancy; we are basically expressing the same "join" to the orders tables in two different places. Adding more columns from the nested WHERE-IN clause will require more sub-queries or additional joins.
When using a standard JOIN, we simply add a count(*) expression to our derived table and return it:
select c.*, x.num
from customers c
inner join
(
select o.customerID, count(*) as num
from orders o
inner join [order details] od on od.orderID = o.orderID
where od.productID = 1
group by customerID
) x on c.CustomerID = x.CustomerID
Take a look at the execution plans now. Not only is the JOIN code shorter, it is twice as fast. In general, that's the way a SQL statement should be built -- joining SELECT statements together and return the columns or calculations that you need, not by deeply nesting WHERE-IN clauses or correlated sub-queries over and over.
The other problem with this technique is that it leads you to believe that every table in your database must have a single column primary key. This leads to bad database designs where tables that relate entities don't have proper composite primary keys, but just meaningless identities. This is because you cannot use WHERE IN to return entities that have more than one column define them.
Finally, you might also have issues with NULL values and performance problems in general as you nest these IN clauses one inside another, especially if you use the even more dreaded "Nested WHERE-NOT IN" anti-pattern. (A little more on that here.)
In short, try to avoid using Nested WHERE-IN clauses. Learn to use proper JOINS and consider thinking carefully and planning your SQL statements. Use derived tables to logically group things into pieces. I promise that if you take the time to learn the proper joining techniques, you will not regret it.
select *
from Customers
where CustomerID in
(select customerID
from Orders
where OrderID in
(select orderID
from [Order Details]
where ProductID = 1
)
)
That's just a simple example, but of course it gets nested more deeply (or branches out) as more conditions are added.
I think beginners gravitate towards this approach because:
1.No "tricky" joins are required
2.It is written more or less the way you would describe what you want: "return customers that have an Order that has ProductID 1 in it."
3.No "strange" duplication of results occur, which can happen with joins if you don't group things properly
In short, I think this technique surfaces because you can just start writing, without any planning or thinking, and the code sort of naturally comes out as you go. And, it does technically return the right results most of the time, so there doesn't seem to be a reason not to do things this way.
So, you might ask, how would you suggest that it should be written? As I often say, break it down into small, separate parts and put them all together in the end. Our first task is to write a SELECT that returns a distinct list of CustomerID's that have ordered productID 1:
select o.customerID
from orders o
inner join [order details] od on od.orderID = o.orderID
where od.productID = 1
group by o.customerID
With that, we know we can simply inner join from the customers table to this and our Customer table will be filtered with the exact results we need:
select c.*
from customers c
inner join
(
select o.customerID
from orders o
inner join [order details] od on od.orderID = o.orderID
where od.productID = 1
group by o.customerID
) x on c.CustomerID = x.CustomerID
Now, if we look at the execution plans of the two techniques, we will actually see that (in SQL 2000, anyway) they are exactly the same. So, what's the problem? Why shouldn't you use the "Nested WHERE-IN" anti-pattern?
Well, the main issue is maintainability, and how it affects not only the complexity of the SELECT, but performance as well.
Let's suppose we also need to return the total number of times that ProductID 1 has been ordered for each customer. The Nested WHERE-IN SELECT has no way to do this; our only option is to add a correlated subquery or an additional JOIN. Since we are avoiding JOINS in general with this approach, let's use a corrected sub-query:
select *, (select count(*)
from orders
where orderID in
(select orderID
from orders
where orders.customerID=customers.customerID)) as num
from Customers
where CustomerID in
(select customerID
from Orders
where OrderID in
(select orderID
from [Order Details]
where ProductID = 1
)
)
Notice the redundancy; we are basically expressing the same "join" to the orders tables in two different places. Adding more columns from the nested WHERE-IN clause will require more sub-queries or additional joins.
When using a standard JOIN, we simply add a count(*) expression to our derived table and return it:
select c.*, x.num
from customers c
inner join
(
select o.customerID, count(*) as num
from orders o
inner join [order details] od on od.orderID = o.orderID
where od.productID = 1
group by customerID
) x on c.CustomerID = x.CustomerID
Take a look at the execution plans now. Not only is the JOIN code shorter, it is twice as fast. In general, that's the way a SQL statement should be built -- joining SELECT statements together and return the columns or calculations that you need, not by deeply nesting WHERE-IN clauses or correlated sub-queries over and over.
The other problem with this technique is that it leads you to believe that every table in your database must have a single column primary key. This leads to bad database designs where tables that relate entities don't have proper composite primary keys, but just meaningless identities. This is because you cannot use WHERE IN to return entities that have more than one column define them.
Finally, you might also have issues with NULL values and performance problems in general as you nest these IN clauses one inside another, especially if you use the even more dreaded "Nested WHERE-NOT IN" anti-pattern. (A little more on that here.)
In short, try to avoid using Nested WHERE-IN clauses. Learn to use proper JOINS and consider thinking carefully and planning your SQL statements. Use derived tables to logically group things into pieces. I promise that if you take the time to learn the proper joining techniques, you will not regret it.
| Reactions: |
Sunday, August 1, 2010
How to Use More than One DataKeyNames in Asp.Net 2.0 GridView
DataKeyNames is a property to define Read-only primary key like fields in a GridView control. We can also add some more fields to this property separated by commas.
For example, if 'CusCode' is the primary key and you want 'CusType' as a readonly field, you can assign the GridView control's DataKeyNames property as CusCode,CusType.
To retreive the value from the GridView control in RowDataBound event or any other event of the GridView control, use the below syntax.
To take Field 1, use GridView1.DataKeys[e.Row.RowIndex][0].ToString()
To take Field 2, use GridView1.DataKeys[e.Row.RowIndex][1].ToString()
To take Field n, use GridView1.DataKeys[e.Row.RowIndex][n-1].ToString()
For example, if 'CusCode' is the primary key and you want 'CusType' as a readonly field, you can assign the GridView control's DataKeyNames property as CusCode,CusType.
To retreive the value from the GridView control in RowDataBound event or any other event of the GridView control, use the below syntax.
To take Field 1, use GridView1.DataKeys[e.Row.RowIndex][0].ToString()
To take Field 2, use GridView1.DataKeys[e.Row.RowIndex][1].ToString()
To take Field n, use GridView1.DataKeys[e.Row.RowIndex][n-1].ToString()
| Reactions: |
How To Pass Multiple QueryString or Parameter in Hyperlink NavigateUrl from GridView?
The information provided here will help you to frame more than one QueryString parameter in a HyperLink control placed inside GridView control and also shows you, how to pass multiple QueryString in the HyperLinkField of the GridView control.
1. Passing Multiple QueryStrings From HyperLink Inside GridView TemplateField Section
NavigateUrl='<%# String.Format("TestPage.aspx?param1={0}¶m2={1}¶m3={2}", Eval("Field1"), Eval("Field2"), Eval("Field2")) %>'>
2. Passing Multiple QueryString From HyperLinkField of GridView Control
source:
1. Passing Multiple QueryStrings From HyperLink Inside GridView TemplateField Section
2. Passing Multiple QueryString From HyperLinkField of GridView Control
source:
| Reactions: |
Friday, July 30, 2010
Critically examining the underlying architecture for a web application is an important step in defining the end product
Which Web Application Stack Is Best for Me?
Critically examining the underlying architecture for a web application is an important step in defining the end product
Critically examining the underlying architecture for a web application is an important step in defining the end product
| Reactions: |
Mailer Technology Sample
This will guide you how to do when doing classic email or latest technology.
| Reactions: |
Thursday, July 29, 2010
Data-Binding Expressions Overview
Data-binding syntax allows you to bind control property values to data and specify values for retrieving, updating, deleting, and inserting data
| Reactions: |
Designing Data Tier Components and Passing Data Through Tiers
This link wil help us how to build the Dal Componant.
| Reactions: |
Creating a Data Access Layer
my entire blog source is dedicated from internet or msdn source only.
courtsy:Msdn,Bing,
courtsy:Msdn,Bing,
| Reactions: |
Tuesday, July 27, 2010
send a mail from asp.net
using System.Net;
using System.Net.Mail;
protected void btnSubmit_Click(object sender, EventArgs e)
{
MailAddress from = new MailAddress(tbEmail.Text);
MailAddress to = new MailAddress("chowdare@target.com");
SmtpClient client = new SmtpClient("smtp-servername.target.com");
MailMessage mail = new MailMessage(from, to);
mail.Subject = "GSC Assistance : Forward to GSC Team";
mail.Body = "Company Name: " + tbCompanyName.Text + "\r\n" +
"Contact Name: " + tbName.Text + "\r\n" +
"Country : " + tbCountry.Text + "\r\n" +
"Telephone : " + tbTelephone.Text + "\r\n" + "\r\n" +
"Question : " + tbComments.Text;
try
{
client.Send(mail);
tbComments.Text = "";
tbCompanyName.Text = "";
tbCountry.Text = "";
tbEmail.Text = "";
tbName.Text = "";
tbTelephone.Text = "";
pnlSubmitted.Visible = true;
pnlAssistanceForm.Visible = false;
}
catch
{
errMsg.Visible = true;
errMsg.ForeColor = System.Drawing.Color.Red;
errMsg.Text = "Unable to Send Mail. Domain not found. Please check the Domain
";
}
}
using System.Net.Mail;
protected void btnSubmit_Click(object sender, EventArgs e)
{
MailAddress from = new MailAddress(tbEmail.Text);
MailAddress to = new MailAddress("chowdare@target.com");
SmtpClient client = new SmtpClient("smtp-servername.target.com");
MailMessage mail = new MailMessage(from, to);
mail.Subject = "GSC Assistance : Forward to GSC Team";
mail.Body = "Company Name: " + tbCompanyName.Text + "\r\n" +
"Contact Name: " + tbName.Text + "\r\n" +
"Country : " + tbCountry.Text + "\r\n" +
"Telephone : " + tbTelephone.Text + "\r\n" + "\r\n" +
"Question : " + tbComments.Text;
try
{
client.Send(mail);
tbComments.Text = "";
tbCompanyName.Text = "";
tbCountry.Text = "";
tbEmail.Text = "";
tbName.Text = "";
tbTelephone.Text = "";
pnlSubmitted.Visible = true;
pnlAssistanceForm.Visible = false;
}
catch
{
errMsg.Visible = true;
errMsg.ForeColor = System.Drawing.Color.Red;
errMsg.Text = "Unable to Send Mail. Domain not found. Please check the Domain
";
}
}
| Reactions: |
using the Transaction in Sqlserver
create procedure dbo.TS_EnqueueIncident_External
(
@userName varchar(32)
,@incidentId varchar(10)
,@historyId int out
,@queue uniqueidentifier
)
--
-- This procedure enqueues an incident
--
-- Jan, 2004 craig tullis
--
-- Change History
--
-- Date: Author: Description:
-- -------- -------- ---------------------------------
---------------------------------------------------------------------
as
begin
begin transaction
-- crete a new history item
DECLARE @HistoryType int
DECLARE @newHistoryId int
SET @HistoryType =dbo.HistoryTypeEnqueue()
EXEC @historyId = InsertSupportHistoryItem @incidentId, @userName, @HistoryType, 0, @newHistoryId
-- set the current queue id and persist the new queue entry to history
update support_incidents set queue_id = @queue where incident_id = @incidentId
insert support_incident_queue_changes
(
history_id
,new_queue_id
)
values
(
@historyId
,@queue
)
commit transaction
return @historyId
end
(
@userName varchar(32)
,@incidentId varchar(10)
,@historyId int out
,@queue uniqueidentifier
)
--
-- This procedure enqueues an incident
--
-- Jan, 2004 craig tullis
--
-- Change History
--
-- Date: Author: Description:
-- -------- -------- ---------------------------------
---------------------------------------------------------------------
as
begin
begin transaction
-- crete a new history item
DECLARE @HistoryType int
DECLARE @newHistoryId int
SET @HistoryType =dbo.HistoryTypeEnqueue()
EXEC @historyId = InsertSupportHistoryItem @incidentId, @userName, @HistoryType, 0, @newHistoryId
-- set the current queue id and persist the new queue entry to history
update support_incidents set queue_id = @queue where incident_id = @incidentId
insert support_incident_queue_changes
(
history_id
,new_queue_id
)
values
(
@historyId
,@queue
)
commit transaction
return @historyId
end
| Reactions: |
This how to validate An Email
at your html form
place a button
and at the code behind write the following code. in the
Form_Load Event()
btnSubmit.Attributes.Add("onclick", "return validate()");
| Reactions: |
SQL Server™ 2000 Reporting Services Deployment Guide
things to know about the ssrs.
that is better stuff for the deployment,
that is better stuff for the deployment,
| Reactions: |
Collections Best Practices
this is a good thing to learn about the collections.
after reading the collections, u immediatly go to " LinQ"
This is my suggestion.
Source:Msdn,Internet.
after reading the collections, u immediatly go to " LinQ"
This is my suggestion.
Source:Msdn,Internet.
| Reactions: |
Sunday, July 25, 2010
Things diffrence between asp.net 3.5 and 4.0
This article is a heads up to the cloud computing concept introduced in .NET 4.0
"Azure" is project name from Microsoft for Cloud Computing. They are going to introduce this from the upcoming version of .NET Framework 4.0. It might make a dramatic changes in the existing Web applications.
Through Cloud computing Microsoft targets for platform independency in their applications.
That is Each web can communicate to any other servers directly.
Advantages for ASP.NET applications:
Following are the advantages of ASP.NET applications by implementing Cloud computing.
1) Cost cutting - Both the small & large scall organizations can implement this.
2) More storage for Data.
3) Mobilitiy of Data - Data can be moved to any kind of servers(e.g Data can easily moved to Unix based machine from Windows).
4) More advantages on BCP(Disaster recoverty etc) plans
By the implementation of Cloud computing, the Web application will give the same level of performance even the traffic to the site is at the peak.
Disadvantages:
Following jobs will be very hectic by the implementation of Azure.
1) Implementation of session
2) Implementation of authentication
3) System Integration.
4) Migration of existing application.
Main Differences between ASP.NET 3.5 and ASP.NET 4.0
Main Differences between ASP.NET 3.5 and ASP.NET 4.0
As we all know, ASP.NET 3.5 has introduced with the following main new features
1) AJAX integration
2) LINQ
3) Automatic Properties
4) Lambda expressions
I hope it would be useful for everyone to know about the differences about asp.net 3.5 and its next version asp.net 4.0
Because of space consumption I’ll list only some of them here.
1) Client Data access
ASP.NET 3.5: There is no direct method to access data from client side. We can go for any of these methods
1) Pagemethods of script manager
2) ICallbackEventHandler interface
3) XMLHttphanlder component
ASP.NET 4.0: In this framework there is an inbuilt feature for this. Following are the methods to implement them.
• Client data controls
• Client templates
• Client data context
i.e we can access the data through client data view & data context objects from client side.
2) Setting Meta keyword and Meta description
Meta keywords and description are really useful for the search engine listings.
ASP.NET 3.5: It has a feature to add meta as following tag
ASP.NET 4.0: Here we can add the keywords and description in Page directives itself as shown below.
<%@ Page Language="C#" CodeFile="Default.aspx.cs"
Inherits="_Default"
Keywords="Keyword1,Key2,Key3,etc"
Description="description" %>
2) Enableviewstage property for each control
ASP.NET 3.5: this property has two values “True” or “false”
ASP.NET 4.0: ViewStateMode property takes an enumeration that has three values: Enabled, Disabled, and Inherit.
Here inherit is the default value for child controls of a control.
3) Setting Client IDs
Some times ClientID property creates head ach for the programmers.
ASP.NET 3.5: We have to use ClientID property to find out the id which is dynamically generated
ASP.NET 4.0: The new ClientIDMode property is introduced to minimize the issues of earlier versions of ASP.NET.
It has following values.
AutoID – Same as ASP.NET 3.5
Static – There won’t be any separate clientid generated at run time
Predictable-These are used particularly in datacontrols. Format is like clientIDrowsuffix with the clientid vlaue
Inherit- This value specifies that a control's ID generation is the same as its parent.
"Azure" is project name from Microsoft for Cloud Computing. They are going to introduce this from the upcoming version of .NET Framework 4.0. It might make a dramatic changes in the existing Web applications.
Through Cloud computing Microsoft targets for platform independency in their applications.
That is Each web can communicate to any other servers directly.
Advantages for ASP.NET applications:
Following are the advantages of ASP.NET applications by implementing Cloud computing.
1) Cost cutting - Both the small & large scall organizations can implement this.
2) More storage for Data.
3) Mobilitiy of Data - Data can be moved to any kind of servers(e.g Data can easily moved to Unix based machine from Windows).
4) More advantages on BCP(Disaster recoverty etc) plans
By the implementation of Cloud computing, the Web application will give the same level of performance even the traffic to the site is at the peak.
Disadvantages:
Following jobs will be very hectic by the implementation of Azure.
1) Implementation of session
2) Implementation of authentication
3) System Integration.
4) Migration of existing application.
Main Differences between ASP.NET 3.5 and ASP.NET 4.0
Main Differences between ASP.NET 3.5 and ASP.NET 4.0
As we all know, ASP.NET 3.5 has introduced with the following main new features
1) AJAX integration
2) LINQ
3) Automatic Properties
4) Lambda expressions
I hope it would be useful for everyone to know about the differences about asp.net 3.5 and its next version asp.net 4.0
Because of space consumption I’ll list only some of them here.
1) Client Data access
ASP.NET 3.5: There is no direct method to access data from client side. We can go for any of these methods
1) Pagemethods of script manager
2) ICallbackEventHandler interface
3) XMLHttphanlder component
ASP.NET 4.0: In this framework there is an inbuilt feature for this. Following are the methods to implement them.
• Client data controls
• Client templates
• Client data context
i.e we can access the data through client data view & data context objects from client side.
2) Setting Meta keyword and Meta description
Meta keywords and description are really useful for the search engine listings.
ASP.NET 3.5: It has a feature to add meta as following tag
ASP.NET 4.0: Here we can add the keywords and description in Page directives itself as shown below.
<%@ Page Language="C#" CodeFile="Default.aspx.cs"
Inherits="_Default"
Keywords="Keyword1,Key2,Key3,etc"
Description="description" %>
2) Enableviewstage property for each control
ASP.NET 3.5: this property has two values “True” or “false”
ASP.NET 4.0: ViewStateMode property takes an enumeration that has three values: Enabled, Disabled, and Inherit.
Here inherit is the default value for child controls of a control.
3) Setting Client IDs
Some times ClientID property creates head ach for the programmers.
ASP.NET 3.5: We have to use ClientID property to find out the id which is dynamically generated
ASP.NET 4.0: The new ClientIDMode property is introduced to minimize the issues of earlier versions of ASP.NET.
It has following values.
AutoID – Same as ASP.NET 3.5
Static – There won’t be any separate clientid generated at run time
Predictable-These are used particularly in datacontrols. Format is like clientIDrowsuffix with the clientid vlaue
Inherit- This value specifies that a control's ID generation is the same as its parent.
| Reactions: |
Subscribe to:
Posts (Atom)
