Search Results

Search found 5760 results on 231 pages for 'linq to xsd'.

Page 1/231 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Understanding LINQ to SQL (11) Performance

    - by Dixin
    [LINQ via C# series] LINQ to SQL has a lot of great features like strong typing query compilation deferred execution declarative paradigm etc., which are very productive. Of course, these cannot be free, and one price is the performance. O/R mapping overhead Because LINQ to SQL is based on O/R mapping, one obvious overhead is, data changing usually requires data retrieving:private static void UpdateProductUnitPrice(int id, decimal unitPrice) { using (NorthwindDataContext database = new NorthwindDataContext()) { Product product = database.Products.Single(item => item.ProductID == id); // SELECT... product.UnitPrice = unitPrice; // UPDATE... database.SubmitChanges(); } } Before updating an entity, that entity has to be retrieved by an extra SELECT query. This is slower than direct data update via ADO.NET:private static void UpdateProductUnitPrice(int id, decimal unitPrice) { using (SqlConnection connection = new SqlConnection( "Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True")) using (SqlCommand command = new SqlCommand( @"UPDATE [dbo].[Products] SET [UnitPrice] = @UnitPrice WHERE [ProductID] = @ProductID", connection)) { command.Parameters.Add("@ProductID", SqlDbType.Int).Value = id; command.Parameters.Add("@UnitPrice", SqlDbType.Money).Value = unitPrice; connection.Open(); command.Transaction = connection.BeginTransaction(); command.ExecuteNonQuery(); // UPDATE... command.Transaction.Commit(); } } The above imperative code specifies the “how to do” details with better performance. For the same reason, some articles from Internet insist that, when updating data via LINQ to SQL, the above declarative code should be replaced by:private static void UpdateProductUnitPrice(int id, decimal unitPrice) { using (NorthwindDataContext database = new NorthwindDataContext()) { database.ExecuteCommand( "UPDATE [dbo].[Products] SET [UnitPrice] = {0} WHERE [ProductID] = {1}", id, unitPrice); } } Or just create a stored procedure:CREATE PROCEDURE [dbo].[UpdateProductUnitPrice] ( @ProductID INT, @UnitPrice MONEY ) AS BEGIN BEGIN TRANSACTION UPDATE [dbo].[Products] SET [UnitPrice] = @UnitPrice WHERE [ProductID] = @ProductID COMMIT TRANSACTION END and map it as a method of NorthwindDataContext (explained in this post):private static void UpdateProductUnitPrice(int id, decimal unitPrice) { using (NorthwindDataContext database = new NorthwindDataContext()) { database.UpdateProductUnitPrice(id, unitPrice); } } As a normal trade off for O/R mapping, a decision has to be made between performance overhead and programming productivity according to the case. In a developer’s perspective, if O/R mapping is chosen, I consistently choose the declarative LINQ code, unless this kind of overhead is unacceptable. Data retrieving overhead After talking about the O/R mapping specific issue. Now look into the LINQ to SQL specific issues, for example, performance in the data retrieving process. The previous post has explained that the SQL translating and executing is complex. Actually, the LINQ to SQL pipeline is similar to the compiler pipeline. It consists of about 15 steps to translate an C# expression tree to SQL statement, which can be categorized as: Convert: Invoke SqlProvider.BuildQuery() to convert the tree of Expression nodes into a tree of SqlNode nodes; Bind: Used visitor pattern to figure out the meanings of names according to the mapping info, like a property for a column, etc.; Flatten: Figure out the hierarchy of the query; Rewrite: for SQL Server 2000, if needed Reduce: Remove the unnecessary information from the tree. Parameterize Format: Generate the SQL statement string; Parameterize: Figure out the parameters, for example, a reference to a local variable should be a parameter in SQL; Materialize: Executes the reader and convert the result back into typed objects. So for each data retrieving, even for data retrieving which looks simple: private static Product[] RetrieveProducts(int productId) { using (NorthwindDataContext database = new NorthwindDataContext()) { return database.Products.Where(product => product.ProductID == productId) .ToArray(); } } LINQ to SQL goes through above steps to translate and execute the query. Fortunately, there is a built-in way to cache the translated query. Compiled query When such a LINQ to SQL query is executed repeatedly, The CompiledQuery can be used to translate query for one time, and execute for multiple times:internal static class CompiledQueries { private static readonly Func<NorthwindDataContext, int, Product[]> _retrieveProducts = CompiledQuery.Compile((NorthwindDataContext database, int productId) => database.Products.Where(product => product.ProductID == productId).ToArray()); internal static Product[] RetrieveProducts( this NorthwindDataContext database, int productId) { return _retrieveProducts(database, productId); } } The new version of RetrieveProducts() gets better performance, because only when _retrieveProducts is first time invoked, it internally invokes SqlProvider.Compile() to translate the query expression. And it also uses lock to make sure translating once in multi-threading scenarios. Static SQL / stored procedures without translating Another way to avoid the translating overhead is to use static SQL or stored procedures, just as the above examples. Because this is a functional programming series, this article not dive into. For the details, Scott Guthrie already has some excellent articles: LINQ to SQL (Part 6: Retrieving Data Using Stored Procedures) LINQ to SQL (Part 7: Updating our Database using Stored Procedures) LINQ to SQL (Part 8: Executing Custom SQL Expressions) Data changing overhead By looking into the data updating process, it also needs a lot of work: Begins transaction Processes the changes (ChangeProcessor) Walks through the objects to identify the changes Determines the order of the changes Executes the changings LINQ queries may be needed to execute the changings, like the first example in this article, an object needs to be retrieved before changed, then the above whole process of data retrieving will be went through If there is user customization, it will be executed, for example, a table’s INSERT / UPDATE / DELETE can be customized in the O/R designer It is important to keep these overhead in mind. Bulk deleting / updating Another thing to be aware is the bulk deleting:private static void DeleteProducts(int categoryId) { using (NorthwindDataContext database = new NorthwindDataContext()) { database.Products.DeleteAllOnSubmit( database.Products.Where(product => product.CategoryID == categoryId)); database.SubmitChanges(); } } The expected SQL should be like:BEGIN TRANSACTION exec sp_executesql N'DELETE FROM [dbo].[Products] AS [t0] WHERE [t0].[CategoryID] = @p0',N'@p0 int',@p0=9 COMMIT TRANSACTION Hoverer, as fore mentioned, the actual SQL is to retrieving the entities, and then delete them one by one:-- Retrieves the entities to be deleted: exec sp_executesql N'SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued] FROM [dbo].[Products] AS [t0] WHERE [t0].[CategoryID] = @p0',N'@p0 int',@p0=9 -- Deletes the retrieved entities one by one: BEGIN TRANSACTION exec sp_executesql N'DELETE FROM [dbo].[Products] WHERE ([ProductID] = @p0) AND ([ProductName] = @p1) AND ([SupplierID] IS NULL) AND ([CategoryID] = @p2) AND ([QuantityPerUnit] IS NULL) AND ([UnitPrice] = @p3) AND ([UnitsInStock] = @p4) AND ([UnitsOnOrder] = @p5) AND ([ReorderLevel] = @p6) AND (NOT ([Discontinued] = 1))',N'@p0 int,@p1 nvarchar(4000),@p2 int,@p3 money,@p4 smallint,@p5 smallint,@p6 smallint',@p0=78,@p1=N'Optimus Prime',@p2=9,@p3=$0.0000,@p4=0,@p5=0,@p6=0 exec sp_executesql N'DELETE FROM [dbo].[Products] WHERE ([ProductID] = @p0) AND ([ProductName] = @p1) AND ([SupplierID] IS NULL) AND ([CategoryID] = @p2) AND ([QuantityPerUnit] IS NULL) AND ([UnitPrice] = @p3) AND ([UnitsInStock] = @p4) AND ([UnitsOnOrder] = @p5) AND ([ReorderLevel] = @p6) AND (NOT ([Discontinued] = 1))',N'@p0 int,@p1 nvarchar(4000),@p2 int,@p3 money,@p4 smallint,@p5 smallint,@p6 smallint',@p0=79,@p1=N'Bumble Bee',@p2=9,@p3=$0.0000,@p4=0,@p5=0,@p6=0 -- ... COMMIT TRANSACTION And the same to the bulk updating. This is really not effective and need to be aware. Here is already some solutions from the Internet, like this one. The idea is wrap the above SELECT statement into a INNER JOIN:exec sp_executesql N'DELETE [dbo].[Products] FROM [dbo].[Products] AS [j0] INNER JOIN ( SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued] FROM [dbo].[Products] AS [t0] WHERE [t0].[CategoryID] = @p0) AS [j1] ON ([j0].[ProductID] = [j1].[[Products])', -- The Primary Key N'@p0 int',@p0=9 Query plan overhead The last thing is about the SQL Server query plan. Before .NET 4.0, LINQ to SQL has an issue (not sure if it is a bug). LINQ to SQL internally uses ADO.NET, but it does not set the SqlParameter.Size for a variable-length argument, like argument of NVARCHAR type, etc. So for two queries with the same SQL but different argument length:using (NorthwindDataContext database = new NorthwindDataContext()) { database.Products.Where(product => product.ProductName == "A") .Select(product => product.ProductID).ToArray(); // The same SQL and argument type, different argument length. database.Products.Where(product => product.ProductName == "AA") .Select(product => product.ProductID).ToArray(); } Pay attention to the argument length in the translated SQL:exec sp_executesql N'SELECT [t0].[ProductID] FROM [dbo].[Products] AS [t0] WHERE [t0].[ProductName] = @p0',N'@p0 nvarchar(1)',@p0=N'A' exec sp_executesql N'SELECT [t0].[ProductID] FROM [dbo].[Products] AS [t0] WHERE [t0].[ProductName] = @p0',N'@p0 nvarchar(2)',@p0=N'AA' Here is the overhead: The first query’s query plan cache is not reused by the second one:SELECT sys.syscacheobjects.cacheobjtype, sys.dm_exec_cached_plans.usecounts, sys.syscacheobjects.[sql] FROM sys.syscacheobjects INNER JOIN sys.dm_exec_cached_plans ON sys.syscacheobjects.bucketid = sys.dm_exec_cached_plans.bucketid; They actually use different query plans. Again, pay attention to the argument length in the [sql] column (@p0 nvarchar(2) / @p0 nvarchar(1)). Fortunately, in .NET 4.0 this is fixed:internal static class SqlTypeSystem { private abstract class ProviderBase : TypeSystemProvider { protected int? GetLargestDeclarableSize(SqlType declaredType) { SqlDbType sqlDbType = declaredType.SqlDbType; if (sqlDbType <= SqlDbType.Image) { switch (sqlDbType) { case SqlDbType.Binary: case SqlDbType.Image: return 8000; } return null; } if (sqlDbType == SqlDbType.NVarChar) { return 4000; // Max length for NVARCHAR. } if (sqlDbType != SqlDbType.VarChar) { return null; } return 8000; } } } In this above example, the translated SQL becomes:exec sp_executesql N'SELECT [t0].[ProductID] FROM [dbo].[Products] AS [t0] WHERE [t0].[ProductName] = @p0',N'@p0 nvarchar(4000)',@p0=N'A' exec sp_executesql N'SELECT [t0].[ProductID] FROM [dbo].[Products] AS [t0] WHERE [t0].[ProductName] = @p0',N'@p0 nvarchar(4000)',@p0=N'AA' So that they reuses the same query plan cache: Now the [usecounts] column is 2.

    Read the article

  • Problem designing xsd schema - because of a variable element name

    - by ssaboum
    Hi everyone, i'm not the best at creating XSD schema as this is actually my first one, i would like to validate an xml that must look like this : <?xml version="1.0"?> <Data> <FIELD name='toto'> <META mono='false' dynamic='false'> <COLUMN1> <REFTABLE>table</REFTABLE> <REFCOLUMN>key_column</REFCOLUMN> <REFLABELCOLUMN>test_column</REFLABELCOLUMN> </COLUMN1> <COLUMN2> <REFTABLE>table</REFTABLE> <REFCOLUMN>key_column</REFCOLUMN> <REFLABELCOLUMN>test_column</REFLABELCOLUMN> </COLUMN2> </META> <VALUEs> <VALUE>...</VALUE> </VALUEs> </FIELD> My problem is that into the META block the tags "COLUMN1","COLUMN2" are always different, it may become COLUMNxxx. For now my schema is : <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="Data"> <xsd:complexType> <xsd:sequence> <xsd:element name="FIELD" type="Field" /> </xsd:sequence> <xsd:attribute name="id" type="xsd:int" use="required" /> </xsd:complexType> </xsd:element> <xsd:complexType name="dataSourceDef"> <xsd:sequence> <xsd:element name="DSD_REFTABLE" type="xsd:string" /> <xsd:element name="DSD_REFCOLUMN" type="xsd:string" /> <xsd:element name="DSD_REFLABELCOLUMN" type="xsd:string" /> </xsd:sequence> </xsd:complexType> <xsd:complexType name="MetaTag"> <xsd:sequence> <xsd:any processContents="lax" /> </xsd:sequence> <xsd:attribute name="mono" type="xsd:string" use="required" /> <xsd:attribute name="dynamic" type="xsd:string" use="required"/> </xsd:complexType> <xsd:complexType name="Field"> <xsd:sequence> <xsd:element name="META" type="MetaTag" minOccurs="1" /> <xsd:element name="VALUEs"> <xsd:complexType> <xsd:sequence> <xsd:any processContents="lax" /> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required"/> </xsd:complexType> </xsd:schema> And i just can't get it to work, i don't know how to handle the fact that a precise level of my nodes isn't clear, and the rest is. Would you help me please ? thx

    Read the article

  • Automatically extracting inline XSD from WSDL into XSD file(s)

    - by Steven Geens
    I am using a third party Web Service whose definition and implementation are beyond my control. This web service will change in the future. The Web Service should be used to generate an XML file which contains some of the same data (represented by the same XSD types) as the Web Service plus some extra information generated by the program. My approach: create my own XSD referring to the XSD definitions of the WSDL of the called web service (This XSD also includes XSD types for the extra information obviously.) use a Java XML databinding framework (like ADB or JiXB) to generate the databinding classes from my own XSD file from step 1 use a Java SOAP framework (like Axis2 or CXF) with the same databinding framework to generate the databinding classes from the WSDL (This would enable me to use the objects retrieved by the web service directly in the generation of the XML.) The XSD types I am going to use in my own XSD file, but are defined in the WSDL, are subject to change. Whenever they change, I would like to automatically process the XSD and WSDL databinding again. (If the change is significant enough, this might trigger some development effort.(But usually not.)) My problem: In step 1 I need an XSD referring to the same types as used by the Web Service. The WSDL is referring to another WSDL, which is referring to another WSDL etc. Eventually there is an WSDL with the needed inline XSD types. As far as I know there is no way to directly reference the inline XSD types of a WSDL from an XSD. The approach I would think most viable, is to include an extra step in the automatic processing (before the databinding) that extracts the inline XSD from the WSDL into other XSD file(s). These other XSD file(s) can then be referred to by my own XSD file. Things I'd like to avoid: Manually copy pasting the inline XSD into an XSD file (I am looking for an automatic process.) Any manual steps.(Like the determining the WSDL that contains the inline types manually.(The location of that WSDL does change as well.)) Using xsd:any in my own XSD. I would like my own XSD file to be correct. Using a non-Java technology(like .NET) Huge amounts of implementation (but hints on how you would implement such an extraction are welcome anyway) PS: I found some similar questions, but they all had responses like: WTH would you want to do that? That is the reason for my rather large background story.

    Read the article

  • An abundance of LINQ queries and expressions using both the query and method syntax.

    - by nikolaosk
    In this post I will be writing LINQ queries against an array of strings, an array of integers.Moreover I will be using LINQ to query an SQL Server database. I can use LINQ against arrays since the array of strings/integers implement the IENumerable interface. I thought it would be a good idea to use both the method syntax and the query syntax. There are other places on the net where you can find examples of LINQ queries but I decided to create a big post using as many LINQ examples as possible. We...(read more)

    Read the article

  • How to modify my Response.Document XSD for getting author name form Sharepoint

    - by Rohan Patil
    Hi, This is my XSD currently <?xml version="1.0" encoding="Windows-1252"?> <xsd:schema xmlns:tns="urn:Microsoft.Search.Response.Document" attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="urn:Microsoft.Search.Response.Document" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:import namespace="urn:Microsoft.Search.Response.Document.Document" schemaLocation="Microsoft.Search.Response.Document.Document.xsd" /> <xsd:annotation> <xsd:documentation> </xsd:documentation> <xsd:documentation> Defines a Query Respnose from a Windows SharePoint Services 3.0 Query Service. </xsd:documentation> </xsd:annotation> <!-- - - - - - - - - - - - - - - - - - - - - - - - - - --> <!-- Root Element: Document --> <!-- - - - - - - - - - - - - - - - - - - - - - - - - - --> <xsd:element name="Document"> <xsd:complexType> <xsd:sequence> <xsd:element name="Title" type="xsd:string" minOccurs="0" /> <xsd:element name="Action"> <xsd:complexType> <xsd:sequence> <xsd:element name="LinkUrl"> <xsd:complexType> <xsd:simpleContent> <xsd:extension base="xsd:string"> <xsd:attribute name="size" type="xsd:unsignedByte" use="optional" /> <xsd:attribute name="fileExt" type="xsd:string" use="required" /> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="Description" type="xsd:string" minOccurs="0" /> <xsd:element name="Date" type="xsd:dateTime" minOccurs="0" /> <xsd:element xmlns:q1="urn:Microsoft.Search.Response.Document.Document" ref="q1:Properties" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="relevance" type="xsd:unsignedByte" use="optional" /> </xsd:complexType> </xsd:element> </xsd:schema> I want to able to get the author name.. Please help..

    Read the article

  • What is Linq?

    - by Aamir Hasan
    The way data can be retrieved in .NET. LINQ provides a uniform way to retrieve data from any object that implements the IEnumerable<T> interface. With LINQ, arrays, collections, relational data, and XML are all potential data sources. Why LINQ?With LINQ, you can use the same syntax to retrieve data from any data source:var query = from e in employeeswhere e.id == 1select e.nameThe middle level represents the three main parts of the LINQ project: LINQ to Objects is an API that provides methods that represent a set of standard query operators (SQOs) to retrieve data from any object whose class implements the IEnumerable<T> interface. These queries are performed against in-memory data.LINQ to ADO.NET augments SQOs to work against relational data. It is composed of three parts.LINQ to SQL (formerly DLinq) is use to query relational databases such as Microsoft SQL Server. LINQ to DataSet supports queries by using ADO.NET data sets and data tables. LINQ to Entities is a Microsoft ORM solution, allowing developers to use Entities (an ADO.NET 3.0 feature) to declaratively specify the structure of business objects and use LINQ to query them. LINQ to XML (formerly XLinq) not only augments SQOs but also includes a host of XML-specific features for XML document creation and queries. What You Need to Use LINQLINQ is a combination of extensions to .NET languages and class libraries that support them. To use it, you’ll need the following: Obviously LINQ, which is available from the new Microsoft .NET Framework 3.5 that you can download at http://go.microsoft.com/?linkid=7755937.You can speed up your application development time with LINQ using Visual Studio 2008, which offers visual tools such as LINQ to SQL designer and the Intellisense  support with LINQ’s syntax.Optionally, you can download the Visual C# 2008 Expression Edition tool at www.microsoft.com/vstudio/express/download. It is the free edition of Visual Studio 2008 and offers a lot of LINQ support such as Intellisense and LINQ to SQL designer. To use LINQ to ADO.NET, you need SQL

    Read the article

  • Exception with Linq2SQL Query

    - by Hadi Eskandari
    I am running a query using Linq2SQL that comes down to following query: DateTime? expiration = GetExpirationDate(); IQueryable<Persons> persons = GetPersons(); IQueryable<Items> subquery = from i in db.Items where i.ExpirationDate >= expiration select i; return persons.Where(p = p.Items != null && p.Items.Any(item => subquery.Contains(item))); When I evaluate the result of the function, I get a NullReferenceException and here's the stack trace. Any idea what I'm doing wrong?! Basically I want to select all the persons and filter them by item expiration date. at System.Data.Linq.SqlClient.SqlFactory.Member(SqlExpression expr, MemberInfo member) at System.Data.Linq.SqlClient.QueryConverter.VisitMemberAccess(MemberExpression ma) at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node) at System.Data.Linq.SqlClient.QueryConverter.Visit(Expression node) at System.Data.Linq.SqlClient.QueryConverter.VisitExpression(Expression exp) at System.Data.Linq.SqlClient.QueryConverter.VisitBinary(BinaryExpression b) at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node) at System.Data.Linq.SqlClient.QueryConverter.Visit(Expression node) at System.Data.Linq.SqlClient.QueryConverter.VisitExpression(Expression exp) at System.Data.Linq.SqlClient.QueryConverter.VisitBinary(BinaryExpression b) at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node) at System.Data.Linq.SqlClient.QueryConverter.Visit(Expression node) at System.Data.Linq.SqlClient.QueryConverter.VisitExpression(Expression exp) at System.Data.Linq.SqlClient.QueryConverter.VisitWhere(Expression sequence, LambdaExpression predicate) at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc) at System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression mc) at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node) at System.Data.Linq.SqlClient.QueryConverter.Visit(Expression node) at System.Data.Linq.SqlClient.QueryConverter.VisitContains(Expression sequence, Expression value) at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc) at System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression mc) at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node) at System.Data.Linq.SqlClient.QueryConverter.Visit(Expression node) at System.Data.Linq.SqlClient.QueryConverter.VisitExpression(Expression exp) at System.Data.Linq.SqlClient.QueryConverter.VisitQuantifier(SqlSelect select, LambdaExpression lambda, Boolean isAny) at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc) at System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression mc) at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node) at System.Data.Linq.SqlClient.QueryConverter.Visit(Expression node) at System.Data.Linq.SqlClient.QueryConverter.VisitExpression(Expression exp) at System.Data.Linq.SqlClient.QueryConverter.VisitBinary(BinaryExpression b) at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node) at System.Data.Linq.SqlClient.QueryConverter.Visit(Expression node) at System.Data.Linq.SqlClient.QueryConverter.VisitExpression(Expression exp) at System.Data.Linq.SqlClient.QueryConverter.VisitWhere(Expression sequence, LambdaExpression predicate) at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc) at System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression mc) at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node) at System.Data.Linq.SqlClient.QueryConverter.ConvertOuter(Expression node) at System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression query, SqlNodeAnnotations annotations) at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) at System.Data.Linq.DataQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator() at System.Linq.SystemCore_EnumerableDebugView`1.get_Items()

    Read the article

  • Why won't this Schema validate this XML file? [Source of both included - quite small]

    - by Sergio Tapia
    The XML file: <Lista count="3"> <Pelicula nombre="Jurasic Park 3"> <Genero>Drama</ Genero> <Director sexo="M">Esteven Spielberg</Director> <Temporada> <Anho>2002</Anho> <Semestre>Verano<Semestre> </Temporada> </Pelicula> <Pelicula nombre="Maldiciones"> <Genero>Ficcion</ Genero> <Director sexo="M">Pedro Almodovar</Director> <Temporada> <Anho>2002</Anho> <Semestre>Verano<Semestre> </Temporada> </Pelicula> <Pelicula nombre="Amor en New York"> <Genero>Romance</Genero> <Director sexo="F">Katia Hertz</Director> <Temporada> <Anho>2002</Anho> <Semestre>Verano<Semestre> </Temporada> </Pelicula> </Lista count="3"> And here's the XML Schema file I made, it's not working. :\ <xsd:complexType name="Lista"> <xsd:attribute name="count" type="xsd:integer" /> <xsd:complexContent> <xsd:element name="Pelicula" type="xsd:string"> <xsd:attribute name="nombre" type="xsd:string" /> <xsd:complexType> <xsd:sequence> <xsd:element name="Genero" type="generoType"/> <xsd:element name="Director" type="directorType"> <xsd:attribute name="sexo" type="sexoType"/> </xsd:element> </xsd:element name="Temporada"> <xsd:complexType> <xsd:sequence> <xsd:element name="Anho" type="anhoType" /> <xsd:element name="Semestre" type="semestreType" /> </xsd:sequence> </xsd:complexType> <xsd:element> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:complexContent> </xsd:complexType> <xsd:simpleType name="sexoType"> <xsd:restriction base="xsd:string"> <xsd:enumeration value="F"/> <xsd:enumeration value="M"/> </xsd:restriction> </xsd:simpleType> <xsd:simpleType name="directorType"> <xsd:restriction base="xsd:string" /> </xsd:simpleType> <xsd:simpleType name="generoType"> <xsd:restriction base="xsd:string"> <xsd:enumeration value="Drama"/> <xsd:enumeration value="Accion"/> <xsd:enumeration value="Romance"/> <xsd:enumeration value="Ficcion"/> </xsd:restriction> </xsd:simpleType> <xsd:simpleType name="semestreType"> <xsd:restriction base="xsd:string"> <xsd:enumeration value="Verano"/> <xsd:enumeration value="Invierno"/> </xsd:restriction> </xsd:simpleType> <xsd:simpleType name="anhoType"> <xsd:restriction base="xsd:integer"> <xsd:minInclusive value="1970"/> <xsd:maxInclusive value="2020"/> </xsd:restriction> </xsd:simpleType>

    Read the article

  • Why won't this Schema validate this XML file?

    - by Sergio Tapia
    The XML file: <Lista count="3"> <Pelicula nombre="Jurasic Park 3"> <Genero>Drama</Genero> <Director sexo="M">Esteven Spielberg</Director> <Temporada> <Anho>2002</Anho> <Semestre>Verano</Semestre> </Temporada> </Pelicula> <Pelicula nombre="Maldiciones"> <Genero>Ficcion</Genero> <Director sexo="M">Pedro Almodovar</Director> <Temporada> <Anho>2002</Anho> <Semestre>Verano</Semestre> </Temporada> </Pelicula> <Pelicula nombre="Amor en New York"> <Genero>Romance</Genero> <Director sexo="F">Katia Hertz</Director> <Temporada> <Anho>2002</Anho> <Semestre>Verano</Semestre> </Temporada> </Pelicula> </Lista> And here's the XML Schema file I made, it's not working. :\ <xsd:complexType name="Lista"> <xsd:attribute name="count" type="xsd:integer" /> <xsd:complexContent> <xsd:element name="Pelicula" type="xsd:string"> <xsd:attribute name="nombre" type="xsd:string" /> <xsd:complexType> <xsd:sequence> <xsd:element name="Genero" type="generoType"/> <xsd:element name="Director" type="directorType"> <xsd:attribute name="sexo" type="sexoType"/> </xsd:element> </xsd:element name="Temporada"> <xsd:complexType> <xsd:sequence> <xsd:element name="Anho" type="anhoType" /> <xsd:element name="Semestre" type="semestreType" /> </xsd:sequence> </xsd:complexType> <xsd:element></xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:complexContent> </xsd:complexType> <xsd:simpleType name="sexoType"> <xsd:restriction base="xsd:string"> <xsd:enumeration value="F"/> <xsd:enumeration value="M"/> </xsd:restriction> </xsd:simpleType> <xsd:simpleType name="directorType"> <xsd:restriction base="xsd:string" /> </xsd:simpleType> <xsd:simpleType name="generoType"> <xsd:restriction base="xsd:string"> <xsd:enumeration value="Drama"/> <xsd:enumeration value="Accion"/> <xsd:enumeration value="Romance"/> <xsd:enumeration value="Ficcion"/> </xsd:restriction> </xsd:simpleType> <xsd:simpleType name="semestreType"> <xsd:restriction base="xsd:string"> <xsd:enumeration value="Verano"/> <xsd:enumeration value="Invierno"/> </xsd:restriction> </xsd:simpleType> <xsd:simpleType name="anhoType"> <xsd:restriction base="xsd:integer"> <xsd:minInclusive value="1970"/> <xsd:maxInclusive value="2020"/> </xsd:restriction> </xsd:simpleType>

    Read the article

  • How to create a dynamic Linq Join extension method

    - by Royd Brayshay
    There was a library of dynamic Linq extensions methods released as a sample with VS2008. I'd like to extend it with a Join method. The code below fails with a parameter miss match exception at run time. Can anyone find the problem? public static IQueryable Join(this IQueryable outer, IEnumerable inner, string outerSelector, string innerSelector, string resultsSelector, params object[] values) { if (inner == null) throw new ArgumentNullException("inner"); if (outerSelector == null) throw new ArgumentNullException("outerSelector"); if (innerSelector == null) throw new ArgumentNullException("innerSelector"); if (resultsSelector == null) throw new ArgumentNullException("resultsSelctor"); LambdaExpression outerSelectorLambda = DynamicExpression.ParseLambda(outer.ElementType, null, outerSelector, values); LambdaExpression innerSelectorLambda = DynamicExpression.ParseLambda(inner.AsQueryable().ElementType, null, innerSelector, values); ParameterExpression[] parameters = new ParameterExpression[] { Expression.Parameter(outer.ElementType, "outer"), Expression.Parameter(inner.AsQueryable().ElementType, "inner") }; LambdaExpression resultsSelectorLambda = DynamicExpression.ParseLambda(parameters, null, resultsSelector, values); return outer.Provider.CreateQuery( Expression.Call( typeof(Queryable), "Join", new Type[] { outer.ElementType, inner.AsQueryable().ElementType, outerSelectorLambda.Body.Type, innerSelectorLambda.Body.Type, resultsSelectorLambda.Body.Type }, outer.Expression, inner.AsQueryable().Expression, Expression.Quote(outerSelectorLambda), Expression.Quote(innerSelectorLambda), Expression.Quote(resultsSelectorLambda))); } I've now fixed it myself, here's the answer. Please vote it up or add a better one.

    Read the article

  • xsd.exe C# file to XSD file

    - by PSU_Kardi
    I have an XML file that I used to create an XSD File and from there generated the C# code. However, during development I had to make some changes to that C# file. Is there a way I can use the xsd.exe tool to convert that C# file back into an XSD file? I'm hoping to avoid having to go and manually edit the XSD File.

    Read the article

  • StackOverFlowException when generating C# code from xsd using xsd.exe (VS2010)

    - by Staffan
    Hello, I am trying to generate C# code from an XML schema with xsd.exe with Visual Studio RC1 (version 10.0.30128.1) but get the follwoing error: C:\Developmentxsd CR2008Schema.xsd /classes Microsoft (R) Xml Schemas/DataTypes support utility [Microsoft (R) .NET Framework, Version 4.0.30128.1] Copyright (C) Microsoft Corporation. All rights reser Process is terminated due to StackOverflowException. The xsd is http://www.businessobjects.com/products/xml/CR2008Schema.xsd Any help appreciated. Thanks, Staffan

    Read the article

  • Is LINQ to SQL deprecated?

    - by Mayo
    Back in late 2008 there was alot of debate about the future of LINQ to SQL. Many suggested that Microsoft's investments in the Entity Framework in .NET 4.0 were a sign that LINQ to SQL had no future. I figured I'd wait before making my own decision since folks were not in agreement. Fast-forward 18 months and I've got vendors providing solutions that rely on LINQ to SQL and I have personally given it a try and really enjoyed working with it. I figured it was here to stay. But I'm reading a new book (C# 4.0 How-To by Ben Watson) and in chapter 21 (LINQ), he suggests that it "has been more or less deprecated by Microsoft" and suggests using LINQ to Entity Framework. My question to you is whether or not LINQ to SQL is officially deprecated and/or if authoritative entities (Microsoft, Scott Gu, etc.) officially suggest using LINQ to Entities instead of LINQ to SQL.

    Read the article

  • Short-circuit evaluation and LINQ-to-NHibernate

    - by afsharm
    It seems that LINQ-to-NHibernate and LINQ-to-SQL does not support short-circuit evaluation in where clause of query. Am I right? Is there any workaround? May it be added to next versions of LINQ-to-NHibernate and LINQ-to-SQL? for more information plz see followings: http://stackoverflow.com/questions/772261/the-or-operator-in-linq-with-c http://stackoverflow.com/questions/2306302/why-ordinary-laws-in-evaluting-boolean-expression-does-not-fit-into-linq

    Read the article

  • xsd validation againts xsd generated class level validation

    - by Miral
    In my project I have very big XSD file which i use to validate some XML request and response to a 3rd party. For the above scenario I can have 2 approaches 1) Create XML and then validate against give XSD 2) Create classes from XSD with the help of XSD gen tool, add xtra bit of attirbutes and use them for validation. Validation in the second way will work somewhat in this manner, a) convert xml request/response into object with XML Serialization b) validate the object with custom attributes set on each property, i.e. Pass the object to a method which will validate the object by iterating through properties and its custom attributes set on the each property, and this will return a boolean value if the object validates and that determines whether the xml request is valid or not? Now the concern which approach is good in terms of performance and anything else???

    Read the article

  • Linq Tutorial

    - by SAMIR BHOGAYTA
    Microsoft LINQ Tutorials http://www.deitel.com/ResourceCenters/Programming/MicrosoftLINQ/Tutorials/tabid/2673/Default.aspx Introducing C# 3 – Part 4 LINQ http://www.programmersheaven.com/2/CSharp3-4 101 LINQ Samples http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx What is LinQ http://www.dotnetspider.com/forum/173039-what-linq-net.aspx Beginners Guides http://www.progtalk.com/viewarticle.aspx?articleid=68 http://www.programmersheaven.com/2/CSharp3-4 http://dotnetslackers.com/articles/csharp/introducinglinq1.aspx Using Linq http://weblogs.asp.net/scottgu/archive/2006/05/14/446412.aspx Step By Step Articles http://www.codeproject.com/KB/linq/linqtutorial.aspx http://www.codeproject.com/KB/linq/linqtutorial2.aspx http://www.codeproject.com/KB/linq/linqtutorial3.aspx

    Read the article

  • Multiple schema validation in Java

    - by user279554
    Hi, I am trying to do multiple schema validation in Java. I don't understand where I am doing wrong. Any help will be appreciated. abc.xsd <?xml version="1.0" encoding="UTF-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xn="project-xml-r4j_another.xsd"> <xsd:import namespace="project-xml-r4j_another.xsd"/> <xsd:element name="abc" type="abc"> </xsd:element> <xsd:complexType name="abc"> <xsd:sequence> <xsd:element name="test" type="test" minOccurs="0" maxOccurs="1"> </xsd:element> <!--<xsd:element name="proj" type="xn:proj"/>--> </xsd:sequence> <xsd:attribute name="id" type="xsd:ID" use="required"/> </xsd:complexType> <xsd:complexType name="test"> <xsd:attribute name="id" type="xsd:ID" use="required"></xsd:attribute> <xsd:attribute name="value" use="required"> <xsd:simpleType> <xsd:restriction base="xsd:string"> <xsd:maxLength value="100" /> </xsd:restriction> </xsd:simpleType> </xsd:attribute> </xsd:complexType> </xsd:schema> project-xml-r4j_another.xsd <?xml version="1.0" encoding="UTF-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="project-xml-r4j_another.xsd" xmlns="project-xml-r4j_another.xsd" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xsd:element name="proj" type="proj"> <xsd:annotation> <xsd:documentation> The project is the root tag of a project-xml. </xsd:documentation> </xsd:annotation> </xsd:element> <xsd:complexType name="proj"> <xsd:attribute name="id" type="xsd:ID" use="required"/> </xsd:complexType> </xsd:schema> Test case package test; import java.io.File; import java.io.IOException; import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.apache.log4j.Logger; import org.junit.Test; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import com.ericsson.ccrtool.core.project.projectxml.InvalidProjectXmlException; public class TestSchema { private static final Logger logger = Logger.getLogger(TestSchema.class); static final String W3C_XML_SCHEMA = XMLConstants.W3C_XML_SCHEMA_NS_URI; @Test public void test() { System.out.println("TestSchema.test()"); try { SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA); // create a grammar object. Source [] source = { new StreamSource(new File("C:\\jaydeep\\Ericsson\\R5B\\abc.xsd")), new StreamSource(new File("C:\\jaydeep\\Ericsson\\R5B\\project-xml-r4j.xsd"))}; Schema schemaGrammar = schemaFactory.newSchema(source); Validator schemaValidator = schemaGrammar.newValidator(); schemaValidator.setErrorHandler(new MessageHandler()); // validate xml instance against the grammar. schemaValidator.validate(new StreamSource("C:\\jaydeep\\Ericsson\\R5B\\project_tmmk17cells_xnaveen_project-xml.xml")); } catch (SAXException e) { throw new InvalidProjectXmlException("Project-xml validation failed, Exception: " + e.getMessage(), e); } catch (IOException e) { throw new InvalidProjectXmlException("Project-xml validation failed, Exception: " + e.getMessage(), e); } } class MessageHandler extends DefaultHandler { private String errMessage = ""; @Override public void warning(SAXParseException e) { logger.info("Warning Line " + e.getLineNumber() + ": " + e.getMessage()); } @Override public void error(SAXParseException e) { errMessage = new String("Error Line " + e.getLineNumber() + ": " + e.getMessage()); logger.info(errMessage); throw new InvalidProjectXmlException("Project-xml validation failed, Exception: " + errMessage); } @Override public void fatalError(SAXParseException e) { errMessage = new String("Error Line " + e.getLineNumber() + ": " + e.getMessage()); logger.info(errMessage); throw new InvalidProjectXmlException("Project-xml validation failed, Exception: " + errMessage); } } } Thanks, Jaydeep

    Read the article

  • Linq To SQL: Behaviour for table field which is NotNull and having Default value or binding

    - by kaushalparik27
    I found this something interesting while wandering over community which I would like to share. The post is whole about: DBML is not considering the table field's "Default value or Binding" setting which is a NotNull. I mean the field which can not be null but having default value set needs to be set IsDbGenerated = true in DBML file explicitly.Consider this situation: There is a simple tblEmployee table with below structure: The fields are simple. EmployeeID is a Primary Key with Identity Specification = True with Identity Seed = 1 to autogenerate numeric value for this field. EmployeeName and their EmailAddress to store in rest of 2 fields. And the last one is "DateAdded" with DateTime datatype which doesn't allow NULL but having Default Value/Binding with "GetDate()". That means if we don't pass any value to this field then SQL will insert current date in "DateAdded" field.So, I start with a new website, add a DBML file and dropped the said table to generate LINQ To SQL context class. Finally, I write a simple code snippet to insert data into the tblEmployee table; BUT, I am not passing any value to "DateAdded" field. Because I am considering SQL Server's "Default Value or Binding (GetDate())" setting to this field and understand that SQL will insert current date to this field.        using (TestDatabaseDataContext context = new TestDatabaseDataContext())        {            tblEmployee tblEmpObjet = new tblEmployee();            tblEmpObjet.EmployeeName = "KaushaL";            tblEmpObjet.EmployeeEmailAddress = "[email protected]";            context.tblEmployees.InsertOnSubmit(tblEmpObjet);            context.SubmitChanges();        }Here comes the twist when application give me below error:  This is something not expecting! From the error it clearly depicts that LINQ is passing NULL value to "DateAdded" Field while according to my understanding it should respect Sql Server's "Default value or Binding" setting for this field. A bit googling and I found very interesting related to this problem.When we set Primary Key to any field with "Identity Specification" Property set to true; DBML set one important property "IsDbGenerated=true" for this field. BUT, when we set "Default Value or Biding" property for some field; we need to explicitly tell the DBML/LINQ to let it know that this field is having default binding at DB side that needs to be respected if I don't pass any value. So, the solution is: You need to explicitly set "IsDbGenerated=true" for such field to tell the LINQ that the field is having default value or binding at Sql Server side so, please don't worry if i don't pass any value for it.You can select the field and set this property from property window in DBML Designer file or write the property in DBML.Designer.cs file directly. I have attached a working example with required table script with this post here. I hope this would be helpful for someone hunting for the same. Happy Discovery!

    Read the article

  • My "Ah-Ha!" Moment With LINQ

    - by CompiledMonkey
    I'm currently working on a set of web services that will be consumed by iPhone and Android devices. Given how often the web services will be called in a relatively short period of time, the data access for the web services has proven to be a very important aspect of the project. In choosing the technology stack for implementation, I opted for LINQ to SQL as it was something I had dabbled with in the past and wanted to learn more about in a real environment. The query optimization happening behind...(read more)

    Read the article

  • XSD NewDataSet Namespace?

    - by Ian
    I'm running XSD on an XML file and getting something strange. Depending on the depth of elements it produces a 'NewDataSet' element which will then is prefixed in Visual Studio to my auto-generated classes which is something I don't want. I've got quite a complex structure and am just trying to add a simple version element or attribute which is causing the problem. The simplest demo I could come up with is this. <A> <B>Text</B> </A> Running this through XSD says there is an element called 'NewDataSet' which may or may not appear and will prefix namespaces. <A> <B> <C>Text</C> </B> </A> This example works as expected and there is no magic 'NewDataSet' element in the generated XSD file.

    Read the article

  • xsd.exe creating invalid constraints in dataset from xsd file

    - by Dan Neely
    I have a sequence with an allowed minimum length of zero in my xsd. When I try and load an xml file which doesn't have any elements of the sequence into the DataSet that xsd.exe created I get an exception indicating that my file violated one of the DataSet's constraints. The xml file validates against the schema so I know it's valid. Is there anything I can do to make the tool generate a valid dataset? <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="Numbers" type="xs:double"/> </xs:sequence> Edit: if I change my schema to this the generated code works properly. It looks wrong to me though since it appears to be implying that I could have sequence items with nothing in them, which doesn't make any sense. <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="Numbers" type="xs:double" minOccurs="0"/> </xs:sequence>

    Read the article

  • Simple way to return anonymous types (to make MVC using LINQ possible)

    - by BlueRaja The Green Unicorn
    I'd like to implement MVC while using LINQ (specifically, LINQ-to-entities). The way I would do this is have the Controller generate (or call something which generates) the result-set using LINQ, then return that to the View to display the data. The problem is, if I do: return (from o in myTable select o); All the columns are read from the database, even the ones (potentially dozens) I don't want. And - more importantly - I can't do something like this: return (from o in myTable select new { o.column }); because there is no way to make anonymous types type-safe! I know for sure there is no nice, clean way of doing this in 3.5 (this is not clean...), but what about 4.0? Is there anything planned, or even proposed? Without something like duck-typing-for-LINQ, or type-safe anonymous return values (it seems to me the compiler should certainly be capable of that), it appears to be nearly impossible to cleanly separate the Controller from the View.

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >