6/16/2010I recently got stuck with one of the strange trouble with a developer. He reported that if he adds a workflow on a list created from sharepoint designer to run automatically when the item is added on list he can not use his code written in one of his asp.net user control to add item into that list. The issue happens is that workflow ends up with message "Failed on start"
First instance i suspected security trouble and tried running entire code with elevated permissions but no luck.
After looking at the log sharepoint was logging "The root activity type is invalid".
The solution found for this trouble is really simple. Adding following configuration in web.config of our asp.net solution resolved the problem.
<configSections>
<sectionGroup name="System.Workflow.ComponentModel.WorkflowCompiler" type="System.Workflow.ComponentModel.Compiler.WorkflowCompilerConfigurationSectionGroup, System.Workflow.ComponentModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="authorizedTypes" type="System.Workflow.ComponentModel.Compiler.AuthorizedTypesSectionHandler, System.Workflow.ComponentModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</sectionGroup>
</configSections>
<System.Workflow.ComponentModel.WorkflowCompiler>
<authorizedTypes>
<authorizedType Assembly="System.Workflow.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Workflow.*" TypeName="*" Authorized="True" />
<authorizedType Assembly="System.Workflow.ComponentModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Workflow.*" TypeName="*" Authorized="True" />
<authorizedType Assembly="System.Workflow.Runtime, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Workflow.*" TypeName="*" Authorized="True" />
<authorizedType Assembly="System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System*" TypeName="*" Authorized="True" />
<authorizedType Assembly="mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System*" TypeName="*" Authorized="True" />
<authorizedType Assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System*" TypeName="*" Authorized="True" />
<authorizedType Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint.Workflow" TypeName="SPWorkflowActivationProperties" Authorized="True" />
<authorizedType Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint.Workflow" TypeName="SPWorkflowTaskProperties" Authorized="True" />
<authorizedType Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint.Workflow" TypeName="SPWorkflowHistoryEventType" Authorized="True" />
<authorizedType Assembly="Microsoft.SharePoint.WorkflowActions, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint.WorkflowActions" TypeName="*" Authorized="True" />
</authorizedTypes>
</System.Workflow.ComponentModel.WorkflowCompiler>
6/9/2010
Problem: Open large xml files without loading the xml file (more than 2 GB)
Resolution: -
When we think of working with any XML file, we normally think of using XMLDocument (DOM) or DataSet.LoadXML(). Some programmers also use XPathDocument to load the xml file. When we use the above objects, we are loading the files into the system memory. The problem is that, if the size of the xml file is for e.g. 5 GB to 7 GB, we have to load the complete file in System’s Memory. This will cost us systems memory and will throw “System out of Memory Exception”.
The best approach to process such large files is to avoid loading the files into the memory. Microsoft has provided with XmlTextReader class. XmlTextReader helps us to process the xml file line by line. In this way we are not loading the complete xml file into the memory but processing the file line by line, node by node. The line provides indicates the type, whether it is a StartElement, EndElement, etc… WE can get the complete child nodes and its collection for the parent node using oXmlTextReader.ReadOuterXML().
Below is an example of how to use XMLTextReader class: -
XmlTextReader AgencyTextReader = new XmlTextReader(filename);
AgencyTextReader.WhitespaceHandling = WhitespaceHandling.None;
while (AgencyTextReader.Read())
{
if (AgencyTextReader.NodeType == XmlNodeType.Element &&
AgencyTextReader.LocalName == "award" &&
AgencyTextReader.IsStartElement() == true)
{
ProcessAwardNode(AgencyTextReader);
AgencyTextReader.Skip();
}
}
private void ProcessAwardNode(XmlTextReader AwardReader)
{
XmlDocument AwardXmlDoc = new XmlDocument();
AwardXmlDoc.LoadXml(AwardReader.ReadOuterXml());
// we can use xpath as below
agencyID =AwardXmlDoc.SelectSingleNode("award/agencyID").InnerText;
}
6/8/2010
Using Reflection we can evaluate an expression where value of the variables in the expression and even expression too are not known, in fact are generated dynamically at runtime. For e.g. I have an expression that can be sum of value of X and Y for one row and product of value of X and Y for the second row. So here my expression is also dynamic and values are also dynamic. I can use reflection to evaluate resultant for such processes.
Reflection basically is used when you don’t know what your code will return at the runtime (i.e. X + Y or X * Y) but it generates assemblies at runtime and also calls them at runtime and gives you the resultant.
First of all we need to add the reference to reflection in our declaration section.
using System.Reflection;
Now we create an object of c# code provider class, which has the method “CreateCompiler” to create compiler at runtime returning an object of “ICodeCompiler”.
Microsoft.CSharp.CSharpCodeProvider cp
= new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.ICodeCompiler ic = cp.CreateCompiler();
Now we will create an object of CompilerParameters, which provides us the functionality to add referenced assemblies at runtime.
System.CodeDom.Compiler.CompilerParameters cpar =
new System.CodeDom.Compiler.CompilerParameters();
cpar.GenerateInMemory = true;
cpar.GenerateExecutable = false;
cpar.ReferencedAssemblies.Add("system.dll");
Define the code to evaluate your expression in a string as shown below. The “strExpression” is the expression you can pass to this method which can be (X + Y) or (X * Y)
string src = "using System;" +
"class myclass" +
"{" +
"public myclass(){}" +
"public double eval(double X, double Y)" +
"{" +
"return " + textBox1.Text + ";" +
"}" +
"}";
Create an object of CompilterResults and call the method “CompileAssemblyFromSource” of ICodeCompiler which takes CompilerParameters and the string of your assembly (which is generated at runtime) as arguments.
System.CodeDom.Compiler.CompilerResults cr = ic.CompileAssemblyFromSource(cpar, src);
Now you can go through the loop of CompilerError object of CompilerResults to fetch errors, if any present in the resultant of the assembly you executed at runtime. Display the error in message box.
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
{
MessageBox.Show(ce.ErrorText);
return;
}
If there are no error in the CompilerResults object then we can fetch the Type of newly created assembly (which is created at runtime). Fetch the MethodInfo object using “GetMethod” method of Type object. We can fetch the resultant value by creating the instance of Type object using Invoke method.
if (cr.Errors.Count == 0 && cr.CompiledAssembly != null)
{
Type ObjType = cr.CompiledAssembly.GetType("myclass");
MethodInfo info = ObjType.GetMethod("eval");
object value = info.Invoke(Activator.CreateInstance(ObjType),
new object[] { Convert.ToDouble(txtX.Text),
Convert.ToDouble(txtY.Text) });
MessageBox.Show(value.ToString());
}
Thus to fetch a expression value at runtime where expression values and operators are dynamic can be achieved using reflection.
The only drawback of using reflection it degrades the performance by 400% compared to early binding. So we should use runtime assemblies only when we do not have the possibility of early binding in the process.
Introducing the ADO.NET Entity Framework
During the development with the database and ADO.NET, we use some traditional way. First we create the database tables and their relationships and then create the classes in the code for business layer. We write our business logic in these classes and performs different operations on the database though these classes. Most of the developers have to do the complex code to move the data between the application and the database. However, to write such type of the code develops must have the database knowledge. In this type of development we generally do not care about the database concepts in our code. Now the Microsoft has introduced the concept of Entity Framework Model where it deals with the database tables as en entity and allows us to write and maintain the code according to the database concepts. Using the entity relationship modeling, developers create the conceptual model of the data and write their code against this model. So we can say “ADO.NET Entity Framework Model allows you to deal with database concepts in your code." ADO.NET Entity framework intended to make the development easier and more effective for object-oriented application to work with data.

The Entity Framework architecture

The ADO.NET Entity Framework is a layered framework which abstracts the relational schema of a database and presents a conceptual model.
Data Source: The bottom layer is the data which can be stored in one or many databases.
Data Providers: The data will be accessed by a ADO.NET data provider. At this moment only SQL Server is supported but in the near future there will be data providers for Oracle, MySQL, DB2, Firebird, Sybase, VistaDB, SQLite.
Entity Data Model (EDM): The Entity Data Model consists of 3 parts : • Conceptual schema definition language (CSDL) : Declare and define entities, associations, inheritance, ... Entity classes are generated from this schema. • Store schema definition language (SSDL) : Metadata describing the storage container (=database) that persists data. • Mapping specification language (MSL) : Maps the entities in the CSDL file to tables described in the SSDL file.
Entity Client: EntityClient is an ADO.NET managed provider that supports accessing data described in an Entity Data Model. It is similar to SQLClient, OracleClient and others. It provides several components like EntityCommand, EntityConnection and EntityTransaction.
Object Services: This component enables you to query, insert, update, and delete data, expressed as strongly-typed CLR objects that are instances of entity types. Object Services supports both Entity SQL and LINQ to Entities queries.
Entity SQL (ESQL): Entity SQL is a derivative of Transact-SQL, designed to query and manipulate entities defined in the Entity Data Model. It supports inheritance and associations. Both Object Services components and Entity Client components can execute Entity SQL statements.
LINQ to Entities: This is a strong-typed query language for querying against entities defined in the Entity Data Model.
DATABASE MODELING LAYERS
Common design pattern for data modeling is the division of the data model into three parts: a conceptual model, a logical model, and a physical model
1.Physical Data Model: This model describes how data are represented in the physical resources such as memory, wire or disk. The vocabulary of concepts discussed at this layer includes record formats, file partitions and groups, heaps, and indexes. The physical model is typically invisible to the application –applications
2.Logical/Relational Data Model: The concepts discussed at the logical level include tables, rows, and primary key-foreign key constraints, and normalization.
3.Conceptual Model: The conceptual model captures the core information entities from the problem domain and their relationships. conceptual model is the Entity-Relationship Model. UML is a more recent example of a conceptual model

Why Entity Framework is used/ADO.NET Entity Data Model
Entity Framework maps relational tables, columns, and foreign key constraints in logical models to entities and relationships in conceptual models. The Entity Data Model tools generate extensible data classes based on the conceptual model. These classes are partial classes that can be extended with additional members that the developer adds. The classes that are generated for a particular conceptual model derive from base classes that provide Object Services for materializing entities as objects and for tracking and saving changes. Developers can use these classes to work with the entities and relationships as objects related by navigation properties.
Object Services: Object Services is a component of the Entity Framework that enables you to query, insert, update, and delete data, expressed as strongly typed CLR objects that are instances of entity types. Object Services supports both Language-Integrated Query (LINQ) and Entity SQL queries against types that are defined in an Entity Data Model (EDM). Entity framework enables application to access and change the data that is represented as entities and relationship in the conceptual model. Object Services uses the EDM to translate object queries against entity types that are represented in the conceptual model into data source-specific queries. Query results are materialized into objects that Object Services manages. The Entity Framework provides the following ways to query an EDM and return objects:
• LINQ to Entities - provides Language-Integrated Query (LINQ) support for querying entity types that are defined in a conceptual model.
• Entity SQL - a storage-independent dialect of SQL that works directly with entities in the conceptual model and that supports EDM features such as inheritance and relationships. Entity SQL is used both with object queries and queries that are executed by using the EntityClient provider. For more information, see Entity SQL Overview.
• Query builder methods - enables you to construct Entity SQL queries using LINQ-style query methods. For more information, see Query Builder Methods (Entity Framework).
The Entity Framework includes the EntityClient(The EntityClient provider is a data provider used by Entity Framework applications to access data described in an Entity Data Model (EDM)) data provider. This provider manages connections, translates entity queries into data source-specific queries, and returns a data reader that Object Services uses to materialize entity data into objects. When object materialization is not required, the EntityClient provider can also be used like a standard ADO.NET data provider by enabling applications to execute Entity SQL queries and consume the returned read-only data reader. The following mythology is used generally

f you use the Entity Framework concept then the result would be
Thus we can say the ADO.NET Entity Framework provide the abstraction layer between the logical data model and application domain. When you will generate the logical tables to entity data diagram, it combines multiple data tables to one entity.
NET 3.5 SP1 includes the new ADO.NET Entity Framework, which allows developers to define a higher-level Entity Data Model over their relational data, and then program in terms of this model. Concepts like inheritance, complex types and relationships can be modeled using it.
Scheme file (EDMX)
If can also see the EDMS file as XML. To see the xml file open the solution explorer, right click on .EDMS file, select Open With XML Editor.

Now you can see here 3 sections 1. Conceptual Model (CSDL) 2. Storage Model (SSDL) 3. Mapping (MSL)
<?xml version="1.0" encoding="utf-8"?> <edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx"> <edmx:Runtime> <!-- CSDL content --> <edmx:ConceptualModels> <Schema Namespace="NorthwindModel" Alias="Self" xmlns="http://schemas.microsoft.com/ado/2006/04/edm"> <EntityContainer Name="NorthwindEntities"> <EntitySet Name="Employees" EntityType="NorthwindModel.Employee" /> <AssociationSet Name="FK_Orders_Employees" Association="NorthwindModel.FK_Orders_Employees"> <End Role="Employees" EntitySet="Employees" /> <End Role="Orders" EntitySet="Orders" /> </AssociationSet> </EntityContainer> <EntityType Name="Employee"> <Documentation><Summary>Employee entity which corresponds with the Northwind.Employees table</Summary></Documentation> <Key> <PropertyRef Name="EmployeeID" /> </Key> <Property Name="EmployeeID" Type="Int32" Nullable="false" /> <Property Name="LastName" Type="String" Nullable="false" MaxLength="20" /> <Property Name="FirstName" Type="String" Nullable="false" MaxLength="10" /> <NavigationProperty Name="Orders" Relationship="NorthwindModel.FK_Orders_Employees" FromRole="Employees" ToRole="Orders" /> </EntityType> </Schema> </edmx:ConceptualModels>
<!-- SSDL content --> <edmx:StorageModels> <Schema Namespace="NorthwindModel.Store" Alias="Self" ProviderManifestToken="09.00.1399" xmlns="http://schemas.microsoft.com/ado/2006/04/edm/ssdl"> <EntityContainer Name="dbo"> <EntitySet Name="Employees" EntityType="NorthwindModel.Store.Employees" /> <AssociationSet Name="FK_Orders_Employees" Association="NorthwindModel.Store.FK_Orders_Employees"> <End Role="Employees" EntitySet="Employees" /> <End Role="Orders" EntitySet="Orders" /> </AssociationSet> </Schema> </edmx:StorageModels>
<!-- C-S mapping content --> <edmx:Mappings> <Mapping Space="C-S" xmlns="urn:schemas-microsoft-com:windows:storage:mapping:CS"> <EntityContainerMapping StorageEntityContainer="dbo" CdmEntityContainer="NorthwindEntities"> <EntitySetMapping Name="Employees"> <EntityTypeMapping TypeName="IsTypeOf(NorthwindModel.Employee)"> <MappingFragment StoreEntitySet="Employees"> <ScalarProperty Name="EmployeeID" ColumnName="EmployeeID" /> <ScalarProperty Name="LastName" ColumnName="LastName" /> <ScalarProperty Name="FirstName" ColumnName="FirstName" /> </MappingFragment> </EntityTypeMapping> </EntitySetMapping> <AssociationSetMapping Name="FK_Orders_Employees" TypeName="NorthwindModel.FK_Orders_Employees" StoreEntitySet="Orders"> <EndProperty Name="Employees"> <ScalarProperty Name="EmployeeID" ColumnName="EmployeeID" /> </EndProperty> <EndProperty Name="Orders"> <ScalarProperty Name="OrderID" ColumnName="OrderID" /> </EndProperty> <Condition ColumnName="EmployeeID" IsNull="false" /> </AssociationSetMapping> </EntityContainerMapping> </Mapping> </edmx:Mappings> </edmx:Runtime> </edmx:Edmx>
When you build your project, MSBuild will extract the CSDL/SSDL/MSL content from the EDMX file and places these 3 seperate XML files in your project output directory.
Model View
The Model Browser window can be used to visualize the conceptual model and storage model in a well-organized tree hierarchy.

• Conceptual Model o Entity Types : Employee o Associations : FK_Orders_Employees o Entity Container 1. Entity Sets : Employees 2. Association Sets 3. Function Imports
• Storage Model o Tables / Views : Employees o Stored Procedures o Constraints
Generating an Entity Data Model in Your Visual Studio Project
The very first step you have to generate the Entity Data Model for your database. Here I am using the asp.net web application to create the sample of the Entity Data Mode. Right click on sample project -> Add -> New Item -> ADO.NET Entity Data Model
Changed the model name to EntityDataModel.edmx
Select the Generate from database and click on Next
Select your database connection or create New Connection. And click on Next button
You can select objects (Tables, Vies, Stored Procedures) from this window. Then click on the Finish button. Blow is the graphical representation of the Entity Data Mode (EDM) that is generated by the wizard.

Here I have created a .aspx page to fetch all the categories from the database with the Entity Framework Model and showing the products in the gridview by the selected category. The .aspx page is
<table width="100%"> <tr> <td align="right" > Category : </td> <td> <asp:DropDownList ID="drpCategory" runat=server AutoPostBack=true onselectedindexchanged="drpCategory_SelectedIndexChanged" ></asp:DropDownList> </td> </tr> <tr> <td colspan="2" align="center" style="padding-top:10px" > <asp:GridView ID="dgridProducs" Width="90%" runat=server ></asp:GridView> </td> </tr> </table>
Code:
NORTHWNDEntities obNORTHWNDEntities = new NORTHWNDEntities();
protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; FillCategories(); }
private void FillCategories() { try { drpCategory.DataSource = obNORTHWNDEntities.Categories; drpCategory.DataTextField = "CategoryName"; drpCategory.DataValueField = "CategoryID"; drpCategory.DataBind(); } catch { throw; } }
protected void drpCategory_SelectedIndexChanged(object sender, EventArgs e) { int categoryID =Convert.ToInt32(drpCategory.SelectedValue);
IQueryable<Products> products = from c in obNORTHWNDEntities.Products where c.Categories.CategoryID == categoryID select c;
dgridProducs.DataSource = products; dgridProducs.DataBind(); } }
Here obNORTHWNDEntities represent the NORTHWNDEntities context. To fill all the categories into the DrowDownList the FillCategories() is used. To fetch all the product of the selected categories, called the SelectedIndexChanged of the dropdownlist.

How to: Add, Modify, and Delete Objects (Entity Framework)
Here I have created an Employee page where you can add, modify and delete a new employee from the database through the Entity Framework.
To show all the employees the FillEmployees() has been called on the page load event.
private void FillEmployees() { dgridEmployee.DataSource = obNORTHWNDEntities.Employees; dgridEmployee.DataBind(); }
To add the new employee AddNewEmployee() has been used.
private void AddNewEmployee() { Employees obEmployee = new Employees();
obEmployee.EmployeeID = -1;
obEmployee.FirstName = txtFirstName.Text.Trim();
obEmployee.LastName = txtLastName.Text.Trim();
obEmployee.City = txtCity.Text.Trim();
obEmployee.Country = txtCountry.Text.Trim();
obNORTHWNDEntities.AddToEmployees(obEmployee);
obNORTHWNDEntities.SaveChanges();
}
Since this the new employee that’s why the employeeID has been assigned to -1. After assigning all the values to the new employee object it has to be added to the obNORTHWNDEntities context through the AddToEmployees() method. To save the employee to the database SaveChanges() is called.
For modifying the employee, the EditEmployee() functions has been called. private void EditEmployee() {
Employees obEmployee = new Employees();
int employeeId = Convert.ToInt32(hdnEmployeeId.Value);
//IQueryable<Employees> employees = from c in obNORTHWNDEntities.Employees // where c.EmployeeID == employeeId // select c;
//List<Employees> obCollection = employees.ToList<Employees>();
//obEmployee = obCollection[0];
//IQueryable<Employees> emp = obNORTHWNDEntities.Employees.Where("it.EmployeeID=" + employeeId);
//obEmployee = emp.First();
obEmployee = obNORTHWNDEntities.Employees.Where("it.EmployeeID=" + employeeId).First();
obEmployee.FirstName = txtFirstName.Text.Trim();
obEmployee.LastName = txtLastName.Text.Trim();
obEmployee.City = txtCity.Text.Trim();
obEmployee.Country = txtCountry.Text.Trim();
hdnEmployeeId.Value = string.Empty;
obNORTHWNDEntities.SaveChanges(); }
First of all the modified employees information is fatched. obEmployee = obNORTHWNDEntities.Employees.Where("it.EmployeeID=" + employeeId).First();
you can also use the following code to fetch the employee information
//IQueryable<Employees> employees = from c in obNORTHWNDEntities.Employees // where c.EmployeeID == employeeId // select c;
//List<Employees> obCollection = employees.ToList<Employees>();
//obEmployee = obCollection[0];
After assinging the modified values you need to call the obNORTHWNDEntities.SaveChanges().
Use stored procedure with ADO.NET Entity Framework
1. Create the stored procedure to fetch all the orders of a customer
Create PROCEDURE [dbo].[GetOrderByCustomer] @CustomerID nchar(5) AS SELECT * FROM Orders WHERE CustomerID = @CustomerID ORDER BY OrderID
2. Now you have to import this stored procedure to your EDM. There are two ways: first you have to regenerate the EDM and import is via the designer, or in second way you can edit the xml file directly. Here we are using the first method.
a. Right click on the Entity Designer View and click on the Update Model from Database.

b. Choose the newly created stored procedure what you want to include.
3. Go to the Model Browser and search the newly imported stored procedure 4. Right click on that stored procedure and then click on Create Function Import.
5. A new Add Function Import window will be opened. Here select the Entities to Orders. Since this function returns the order list.
To fetch all the orders of a customer the above stored procedure is used in the c# code. private void FillOrder() { using (NORTHWNDEntities obNORTHWNDEntities = new NORTHWNDEntities()) { ObjectResult<Orders> objectResultOrder = obNORTHWNDEntities.GetOrderByCustomer("ALFKI");
dgridOrder.DataSource = objectResultOrder; dgridOrder.DataBind();
} }
Mapping the stored procedure
1. Create the stored procedure to insert the new employee
CREATE PROCEDURE InsertEmployee
@FirstName nvarchar(20) ,@LastName nvarchar(20)
AS BEGIN
INSERT INTO EMPLOYEES ( FirstName ,LastName
) VALUES ( @FirstName ,@LastName )
SELECT MAX(EmployeeID) as NewEmployeeID FROM Employees
END GO
2. Right click on the Employee entity on the EDM and click on Stored Procedure Mapping.
Once you click on that, you will see the Mapping Details window
Here you can map your insert, update and delete stored procedure. Now you have insertEmployee stored procedure to map this procedure click on the <Select Insert Function> then select the InsertEmployee stored procedure from the dropdownlist box.

Difference between LINQ to SQL and Entity Framework
LINQ to SQL is an object-relational mapping (ORM) framework that allows the direct 1-1 mapping of a Microsoft SQL Server database to .NET classes, and query of the resulting objects using LINQ. More specifically, LINQ to SQL has been developed to target a rapid development scenario against Microsoft SQL Server where the database closely resembles the application object model and the primary concern is increased developer productivity. LINQ2SQL was first released with C# 3.0 and .Net Framework 3.5.
• LINQ to SQL supports a wide breadth of abstractions • LINQ to SQL support domain Model • Linq to SQL is only for SQL • LINQ to SQL is simple to use • LINQ to SQL is used for rapid development. • LINQ to SQL class uses the mapping only for the single table • LINQ to SQL generate only dbml file
LINQ to Entities (ADO.Net Entity Framework) is an ORM (Object Relational Mapper) API which allows for a broad definition of object domain models and their relationships to many different ADO.Net data providers. As such, you can mix and match a number of different database vendors, application servers or protocols to design an aggregated mash-up of objects which are constructed from a variety of tables, sources, services, etc. ADO.Net Framework was released with the .Net Framework 3.5 SP1.
• Entity framework supports a high level of abstraction. • Entity framework support conceptual data mode. • Entity Framework will have ability to target different database engines in addition to Microsoft SQL Server. • Entity framework is complex to use. • Entity framework is slower development but has more capabilities. • Entity framework map a single class to multipal tables • Entity framework generate the three xml files csdl, msl and ssdl.
Reference: http://blogs.msdn.com/adonet/archive/2007/05/30/entitysql.aspx http://msdn.microsoft.com/en-us/library/bb399567.aspx
Covariance and Contra variance in Delegates
There has always been confusion for me to understand the concept of Covariance and Contra variance. And today when I scaled down to this definition and example to understand them, it has become really easy to understand it. So here I am sharing with you all.
Covariance: In earlier versions of Visual C#, a delegate method must be exactly matched to a delegate signature. To create a successful match, the parameter type and the return type of the delegate method must be identical to the parameter type and the return type of the delegate signature.
When we talk about covariance in .net, we say it permits a method to have a more derived return type than what is defined in the delegate. In Visual C# 2005, you may notice that more than one match can be established when you work in an inheritance context. In this scenario, delegate behavior may change.
using System;
delegate object D();
class A {
public object M() {return "object";}
}
class B:A {
public string M() {return "string";}
}
public class MyClass {
public static void Main() {
B b = new B();
D d = new D(b.M);
Console.WriteLine(d());
}
}
When you compile and run this code sample in the Microsoft .NET Framework 2.0, you receive a result of "String". In the .NET Framework 2.0, both the M method in the base class and the M method in the derived class can be matched to the delegate signature. However, overload resolution rules decide that the one method in the most specific class wins the match. In this example, the method that is in class B wins the match.
Covariant type parameters enable you to make assignments that look much like ordinary polymorphism. Polymorphism enables you to assign an instance of derived class to a variable of type base class. Similarly, because the type parameter of the IEnumerable<T> interface is covariant, you can assign an instance of IEnumerable<derived class> to a variable of type IEnumerable<base class>, as shown in the following code.
IEnumerable<Dogs> d = new List<Dogs>();
IEnumerable<Mammals> m = d;
This gave an error “Cannot implicitly convert type” in Framework 2.0. But it is compiles without error in Framework 4.0. The List<T> class implements the IEnumerable<T> interface, so List<derived class> implements IEnumerable<derived class>. The covariant type parameter does the rest.
Contra variance: When a delegate method signature has one or more parameters of types that are derived from the types of the method parameters, that method is said to be contra variant. As the delegate method signature parameters are more specific than the method parameters, they can be implicitly converted when passed to the handler method. Contra variance therefore makes it easier to create more general delegate methods that can be used with a larger number of classes class Animal {} class Dog : Animal {} class DelgateDemo { public delegate void getAction(Dog dog); public static void Run(Animal cat) {} public static void Eat(Dog petdog) {} static void Main(string[] args) {
getAction g1 = new getAction(Run); getAction g2 = new getAction(Eat); }
} Now have you ever imagine that IComparer<object> and IComparer<string> are one and the same. It is possible in Framework4.0 because the interface IComparer<T> has become IComparer<in T>. The “in” indicates that the parameters are restricted to occur only in input positions. Let’s go for an example to explain the contra variance in Framework4.0.
public class Animal
{
public int Weight { get; set; }
public string Name { get; set; }
public Animal()
{ }
public Animal(string InputName, int InputWeight)
{
Name = InputName;
Weight = InputWeight;
}
}
public class Elephant : Animal
{
public Elephant(string InputName, int InputWeight) : base(InputName, InputWeight)
{ }
}
To weigh animals, we will create WeightComparer which will implement IComparer interface; which in turn will enable us to use the Sort() method on list object.
public class WeightComparer : IComparer<Animal>
{
public int Compare(Animal x, Animal y)
{
if (x.Weight > y.Weight) return 1;
if (x.Weight == y.Weight) return 0;
return -1;
}
}
Now we will check by adding making a list of animals and sorting it and making a list of elephants and sorting it using the Sort() method of IComparer.
static void Main(string[] args)
{
WeightComparer objAnimalComparer = new WeightComparer();
List<Animal> Animals = new List<Animal>();
Animals.Add(new Animal("elephant", 500));
Animals.Add(new Animal("tiger", 100));
Animals.Add(new Animal("rat", 5));
Animals.Sort(objAnimalComparer);
List<Elephant> Elephants = new List<Elephant>();
Elephants.Add(new Elephant("Nellie", 100));
Elephants.Add(new Elephant("Dumbo", 200));
Elephants.Add(new Elephant("Baba", 50));
Elephants.Sort(objAnimalComparer);
Elephants.ForEach(e => Console.WriteLine(e.Name + " " + e.Weight.ToString()));
}
In the above code prior to .Net 4.0 Elephants list could not have been sorted it gives error “Cannot convert from 'WeightComparer' to 'System.Collections.Generic.IComparer<Elephant>”.
Above samples have cleared the concepts of covariance and contra variance; also have explained the enhancement in these concepts in .Net Framework 4.0.
You know that sandbox solution in SharePoint 2010 has certain limitation like
· It doesn’t allow using web services.
· You can’t access SharePoint web controls
· It won’t allow executing code that runs under elevated privileges etc…
So, basically sandbox solution provides restricted environment to execute your code for specific SharePoint site.
What if you want to execute a web service inside a sandbox solution? The solution is to write a full trust proxy. Let’s solidify this requirement by creating a web part that gets the data from a web part. I’m going to write a simple sandbox solution that displays xml string returned from Lists.GetList(“your list name”) method.
There are three parts of this code.
· Create a proxy: This will execute your sharepoint web service and return xml
· Register full trust proxy.
· Write a web part
Create a proxy
1. Add a class library project to your solution say “RVProxy”.
2. Add a class file inside it say “ServiceHelper.cs”.
3. Copy and paste below code to your ServiceHelper.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.UserCode;
using System.Xml;
[assembly: System.Security.AllowPartiallyTrustedCallersAttribute()]
namespace RVProxy
{
public class ServiceHelper:SPProxyOperation
{
public override object Execute(SPProxyOperationArgs args)
{
if (args != null)
{
ListArgs lstArg = args as ListArgs;
string listName = lstArg.ListName;
RVListOperation.Lists lst = new RVListOperation.Lists();
lst.PreAuthenticate = true;
lst.Credentials = System.Net.CredentialCache.DefaultCredentials;
XmlNode node = lst.GetList(listName);
return node.InnerXml;
}
else
{
return null;
}
}
}
[Serializable]
public class ListArgs:SPProxyOperationArgs
{
public ListArgs(string listName)
{
this.ListName = listName;
}
public string ListName
{
get;
set;
}
}
}
In the above code, note that assembly has been tagged with attribute [assembly: System.Security.AllowPartiallyTrustedCallersAttribute()]. This tells the compiler to execute the assembly in partially trusted environment.
Class ServiceHelper inherits SPProxyOperation class. Implement its Execute() method. This method contains all the code that runs under trusted mode.
Class ListArgs serves as an input argument sent to the proxy. Don’t forget to decorate this class with attribute [Serializable]
Now your proxy is ready. You need to register this as full trust proxy.
Register full trust proxy
1. Put the “RVProxy” dll into the GAC.
2. Register this dll as full trust proxy. You can either register this using powershell script or using SharePoint object model. I’ll explain the second one here
a. Create a windows application
b. Use below code to register, unregister or view registered assemblies:
Register
private void RegisterFullTrustProxty(string assemblyName, string typeName)
{
label1.Text = "";
lblRegisteredProxy.Text = "";
SPUserCodeService service = SPUserCodeService.Local;
if (service != null)
{
SPProxyOperationType getEventLogItemCreationOperation = new SPProxyOperationType(assemblyName, typeName);
service.ProxyOperationTypes.Add(getEventLogItemCreationOperation);
service.Update();
label1.Text = "Updated successfully!";
}
else
{
label1.Text = "Update failed!";
}
}
For e.g RegisterFullTrustProxty("RVProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0d35956c4346f2f1"
, "RVProxy.ServiceHelper"
);
Unregister
private void UnregisterFullTrustProxty(string assemblyName, string typeName)
{
label1.Text = "";
lblRegisteredProxy.Text = "";
SPUserCodeService service = SPUserCodeService.Local;
if (service != null)
{
SPProxyOperationType getEventLogItemCreationOperation = new SPProxyOperationType(assemblyName, typeName);
service.ProxyOperationTypes.Remove(getEventLogItemCreationOperation);
service.Update();
label1.Text = "Removed succesfully!";
}
else
{
label1.Text = "Remove failed!";
}
}
View all registered assemblies
private void ViewAllRegisteredProxy()
{
label1.Text = "";
lblRegisteredProxy.Text = "";
SPUserCodeService service = SPUserCodeService.Local;
if (service != null)
{
int count = service.ProxyOperationTypes.Count;
lblRegisteredProxy.Text = "Proxy count: " + count.ToString() + Environment.NewLine ;
foreach (SPProxyOperationType item in service.ProxyOperationTypes)
{
lblRegisteredProxy.Text += "AssemblyName: " + item.AssemblyName + Environment.NewLine + "TypeName: " + item.TypeName + Environment.NewLine;
}
}
}
Write the web part
You have created the proxy as well as registered as a full trust proxy. Now it’s time to utilize this proxy in your web part code. I’m pasting here a sample code that utilizes the above proxy:
[ToolboxItemAttribute(false)]
public class DemoPart : WebPart
{
Label lbl = new Label();
Button btnTest = new Button()
{
Text = "Get List"
};
public DemoPart()
{
btnTest.Click += new EventHandler(btnTest_Click);
}
void btnTest_Click(object sender, EventArgs e)
{
string assemblyName = "RVProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0d35956c4346f2f1";
string typeName = "RVProxy.ServiceHelper";
string listInfo = SPUtility.ExecuteRegisteredProxyOperation(assemblyName, typeName, new ListArgs("Tasks")).ToString();
lbl.Text += listInfo;
}
protected override void CreateChildControls()
{
lbl.Text = "Hi Ranvijay, here is your web part under sandbox solution.<br /><br />";
Controls.Add(lbl);
Controls.Add(btnTest);
}
Note: The proxy runs under SPUserCodeService.exe service. So, every time you make changes to your proxy and redeploy the dll to GAC, you will need to restart the “SPUserCodeV4”. To stop use "net stop SPUserCodeV4" and to start use "net start SPUserCodeV4" 6/3/2010You may see error like Unhandled Exception: System.IO.FileNotFoundException: The Web application at http://sp2010:12523 could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.while debugging the code as shown below: WorkaroundWhen you create a new application, it defaults to x86. However sharepoint 2010 is a 64 bit application. To resolve the issue, View your project properties, go to the Build tab and change the platform target to x64. Run your application again and everything should work as expected now. 11/6/2009
Recently I needed to open windows calculator from web page. Different browser has different approach to allow this. Below I have mentioned how to implement this for Internet Explorer 6.0/7.0/8.0 and Mozilla Firefox 3.0/3.5.
Internet Explorer:
In IE you need to create the ActiveX control to open the application. You need to write the following HTML code to do this.
<html>
<head>
</head>
<body>
<input type="button" id ="buttonOpenCalculator" value="Open Calculator" />
<script type="text/javascript">
function OpenCalculator()
{
var commandShell = new ActiveXObject("WScript.Shell");
commandShell.Run("calc");
commandShell.Quit;
}
document.getElementById("buttonOpenCalculator").attachEvent('onclick', OpenCalculator);
</script>
</body>
</html>
Here when you click the button “Open Calculater” calculator will be opened.
Note: In order to open calculator you need change browser settings as below.
· Go to Tools > Internet Options > Security Tab > Local Intranet.
· Click Custom Level in Security level for this zone.
· Set “Initialize and script ActiveX controls not marked as safe” to prompt in ActiveX Controls and Plug-Ins zone.
Mozilla Firefox:
To open the application in web page from Mozilla you need to create an extension (.xpi).
In extension you need to write the following code in JS file.
//This is the function that will create a process for an application
eventListener = function(event) {
// get system32 path for user;
var userSystemFilePath = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("SysD", Components.interfaces.nsIFile);
var stringApplicationPath = userSystemFilePath.path + "\\calc.exe";// "c:\\windows\\system32\\calc.exe";
event.target.setAttribute("IsAddOnInstalled", "true");
var stringParameter = "";
try
{
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var objectFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
objectFile.initWithPath(stringApplicationPath);
if (objectFile.exists())
{
// create an nsIProcess
var objectProcess = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
objectProcess.init(objectFile);
// Run the process.
// If first param is true, calling process will be blocked until
// called process terminates.
// Second and third params are used to pass command-line arguments
// to the process.
var arguments = null;
var argumentLenth = 0;
if (stringParameter)
{
arguments = [stringParameter];
argumentLenth = 1;
}
objectProcess.run(false, arguments, argumentLenth);
}
}
catch (error)
{
alert(error );
}
}
document.addEventListener("sendEvent", eventListener, false, true);
In the web page you need to write the following code
<html>
<head>
</head>
<body>
<input type="button" id ="buttonOpenCalculator" value="Open Calculator" />
<script type="text/javascript">
var element = document.createElement("ExtensionDataElement");
element.setAttribute("IsAddOnInstalled", 'false');
document.documentElement.appendChild(element);
function OpenCalculator()
{
var event = document.createEvent("Events");
event.initEvent("sendEvent", true, false);
element.dispatchEvent(event);
if (element.getAttribute("IsAddOnInstalled") == 'false')
{
window.open("download url of xpi","calculator","","");
}
}
document.getElementById("buttonOpenCalculator").addEventListener('click', OpenCalculator, false);
</script>
</body>
</html>
If you run the code and click the button for first time you will be prompted to install xpi file. Firefox needs to be restarted after installing the extension. Clicking the button now will open the calculator. 11/5/2009
Problem: Printing in silverlight.
Answer: One of the important missing features in Silverlight has been printing support. If you have ever tried to print a web page containing Silverlight content, what you saw on the printed page may be skewed or even missing altogether!
In one of the projects we are working, we need to print information from silverlight application for a user. We have resolved this problem using HTML Bridge.
First of all, Place one div element in your .aspx or .html page which holds your silverlight object as shown below. Look at printDiv tag. It will hold printing content of silverlight application.
“<div id="silverlightControlHost">
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2"
width="100%" height="100%">
<param name="source" value="ClientBin/XXXXX.xap" />
<param name="onError" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="3.0.40624.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration: none">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight"
style="border-style: none" />
</a>
</object>
<iframe id="_sl_historyFrame" style="visibility: hidden; height: 0px; width: 0px;
border: 0px"></iframe>
</div>
<div id="printDiv" style="display: none; height: 0; width: 0; z-index: -1; position: absolute">
</div>
Add this JavaScript function as below in same aspx or html page. These will pop up a print dialog to print dynamically generated content in printDiv element.
// Function to print itinarary layout
function CallPrint() {
var prtContent = document.getElementById("printDiv");
var WinPrint = window.open('', '', 'left=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
prtContent.innerHTML = "";
}
Now question is how we can add elements and set values from silverlight in this div tag. Here Is the solution. For HtmlElement and HtmlPage object please add statement
using System.Windows.Browser;
//get printDiv element of html or aspx page as HTMLElement
HtmlElement printDiv = HtmlPage.Document.GetElementById("printDiv");
//setting printDiv's innerHTML property to empty string
printDiv.SetProperty("innerHTML", string.Empty);
//creating table and tbody instance
HtmlElement table = HtmlPage.Document.CreateElement("table");
HtmlElement tbody = HtmlPage.Document.CreateElement("tbody");
//setting table width and Vertical align properties
table.SetStyleAttribute("width", "70%");
table.SetStyleAttribute("verticalAlign", "top");
//creating TripName(Header of page) label in top
HtmlElement trTrip = HtmlPage.Document.CreateElement("tr");
HtmlElement tdTrip = HtmlPage.Document.CreateElement("td");
tdTrip.SetStyleAttribute("width", "20%");
tdTrip.SetStyleAttribute("verticalAlign", "top");
// add input element and set it’s properties and value
HtmlElement tripinput = HtmlPage.Document.CreateElement("input");
tripinput.SetAttribute("value", _dashboard.lblControlName.Text);
tripinput.SetStyleAttribute("width", "100%");
tripinput.SetAttribute("type", "text");
tripinput.SetAttribute("readonly", "readonly");
tripinput.SetStyleAttribute("border", "0");
tdTrip.AppendChild(tripinput);
trTrip.AppendChild(tdTrip);
tbody.AppendChild(trTrip);
//adding tbody tablebody to table
table.AppendChild(tbody);
//adding table to printDiv Div
printDiv.AppendChild(table);
//call to javascript Function which will fire print command to print Printdiv contents
HtmlPage.Window.CreateInstance("CallPrint", null);
That’s it.
Thanks,
Posted By: Darshana Rana & Jigar patel 7/22/2009
Sql server 2005: OUTPUT Clause
What: OUTPUT Clause is used to return the rows affected by Insert, Update or Delete Statement on Sql table
Why: to perform an action on the rows which are affected by any of the table manipulation statements i.e. Insert, Update and Delete.
Example: suppose, we have a requirement to maintain a log file after any operation on a table. Here operation refers Insert, Update and Delete operation.
The role of an Output Clause comes here, Instead of using a trigger we could use the OUTPUT clause.
How: For the example here uses a 2 tables:
1. tblExternalFile: a parents Table
2. tblExternalFileBackup : a Backup Table
Structures of these 2 tables are bellow:
1. tblExternalFile
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblExternalFile](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FileXml] [xml] NULL,
CONSTRAINT [PK_tblExternalFile] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (
PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
) ON [PRIMARY]
2. tblExternalFileBackup
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblExternalFileBackup](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FileXml] [xml] NULL,
CONSTRAINT [PK_tblExternalFileBackup] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
Here both tables have same numbers of column,
OUTPUT clause with Insert:
Here is a code that will automatically insert a new record in - tblExternalFileBackup table,whenever an insert operation fires on – tblExternalFile table.
GO
-- Create Temp Table variable
DECLARE @MyTableVar table( Id int,
FileXml xml,
ModifiedDate smallDateTime);
-- Insert Operation Fires on tblExternalFile
INSERT tblExternalFile([FileXml])
OUTPUT INSERTED.Id,INSERTED.FileXml,GetDate()
INTO @MyTableVar
VALUES (N'<DatabaseData xmlns=""><MappingMeta>123</MappingMeta></DatabaseData>');
-- Insert a newly Added Record to tblExternalFileBackup
INSERT INTO tblExternalFileBackup(FileXml)
SELECT FileXml FROM @MyTableVar
--Display the result set of the table variable.
SELECT * FROM tblExternalFileBackup;
GO
OUTPUT clause with Delete:
DELETE FROM tblExternalFile
OUTPUT DELETED.*
WHERE ID=17
All Deleted rows will be displayed whose Id is 17.
OUTPUT clause with Update:
-- Create Temp Table variable
DECLARE @MyTableVar table( Id int,
OldFileXml xml,
NewFileXml xml,
ModifiedDate smallDateTime);
-- Update Operation
UPDATE tblExternalFile
SET FileXml = '<Employee xmlns=""><ID>007</ID></Employee>'
OUTPUT INSERTED.Id,
DELETED.FileXml,
INSERTED.FileXml,
GETDATE()
INTO @MyTableVar
WHERE iD=17;
-- Insert a newly Added/ Updated Record to tblExternalFileBackup
INSERT INTO tblExternalFileBackup(FileXml)
SELECT FileXml FROM @MyTableVar
SELECT * FROM tblExternalFileBackup
@MyTableVar is a table Variable we use it to store the Updated records of a Table. Here an Id Number ‘17’ will be updated with the New Xml String and new row will be added in tblExternalFileBackup table.
Alternative of OUTPUT Clause:
You can write a trigger on table to manage a log on a table. The benefits/ Limitation of triggers over OUTPUT clause are not in the scope of this blog.
Ref. Site: http://msdn.microsoft.com/en-us/library/ms177564(SQL.90).aspx
Thanks,
Vivek Shah
|
|
|
|