Search Results

Search found 15930 results on 638 pages for 'analysis services'.

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

  • How to disable authentication schemes for WCF Data Services

    - by Schneider
    When I deployed my WCF Data Services to production hosting I started to get the following error (or similar depending on which auth schemes are active): IIS specified authentication schemes 'Basic, Anonymous', but the binding only supports specification of exactly one authentication scheme. Valid authentication schemes are Digest, Negotiate, NTLM, Basic, or Anonymous. Change the IIS settings so that only a single authentication scheme is used. Apparently WCF Data Services (WCF in general?) cannot handle having more than once authentication scheme active. OK so I am aware that I can disable all-but-one authentication scheme on the web application via IIS control panel .... via a support request!! Is there a way to specify a single authentication scheme on a per-service level in the web.config? I thought this might be as straight forward as making a change to <system.serviceModel> but... it turns out that WCF Data Services do not configure themselves in the web config. If you look at the DataService<> class it does not implement a [ServiceContract] hence you cannot refer to it in the <service><endpoint>...which I presume would be needed for changing its configuration via XML. P.S. Our host is using II6, but both solutions for IIS6 & IIS7 appreciated.

    Read the article

  • Integrating WIF with WCF Data Services

    - by cibrax
    A time ago I discussed how a custom REST Starter kit interceptor could be used to parse a SAML token in the Http Authorization header and wrap that into a ClaimsPrincipal that the WCF services could use. The thing is that code was initially created for Geneva framework, so it got deprecated quickly. I recently needed that piece of code for one of projects where I am currently working on so I decided to update it for WIF. As this interceptor can be injected in any host for WCF REST services, also represents an excellent solution for integrating claim-based security into WCF Data Services (previously known as ADO.NET Data Services). The interceptor basically expects a SAML token in the Authorization header. If a token is found, it is parsed and a new ClaimsPrincipal is initialized and injected in the WCF authorization context. public class SamlAuthenticationInterceptor : RequestInterceptor {   SecurityTokenHandlerCollection handlers;   public SamlAuthenticationInterceptor()     : base(false)   {     this.handlers = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers;   }   public override void ProcessRequest(ref RequestContext requestContext)   {     SecurityToken token = ExtractCredentials(requestContext.RequestMessage);     if (token != null)     {       ClaimsIdentityCollection claims = handlers.ValidateToken(token);       var principal = new ClaimsPrincipal(claims);       InitializeSecurityContext(requestContext.RequestMessage, principal);     }     else     {       DenyAccess(ref requestContext);     }   }   private void DenyAccess(ref RequestContext requestContext)   {     Message reply = Message.CreateMessage(MessageVersion.None, null);     HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty() { StatusCode = HttpStatusCode.Unauthorized };     responseProperty.Headers.Add("WWW-Authenticate",           String.Format("Basic realm=\"{0}\"", ""));     reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;     requestContext.Reply(reply);     requestContext = null;   }   private SecurityToken ExtractCredentials(Message requestMessage)   {     HttpRequestMessageProperty request = (HttpRequestMessageProperty)  requestMessage.Properties[HttpRequestMessageProperty.Name];     string authHeader = request.Headers["Authorization"];     if (authHeader != null && authHeader.Contains("<saml"))     {       XmlTextReader xmlReader = new XmlTextReader(new StringReader(authHeader));       var col = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();       SecurityToken token = col.ReadToken(xmlReader);                                        return token;     }     return null;   }   private void InitializeSecurityContext(Message request, IPrincipal principal)   {     List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>();     policies.Add(new PrincipalAuthorizationPolicy(principal));     ServiceSecurityContext securityContext = new ServiceSecurityContext(policies.AsReadOnly());     if (request.Properties.Security != null)     {       request.Properties.Security.ServiceSecurityContext = securityContext;     }     else     {       request.Properties.Security = new SecurityMessageProperty() { ServiceSecurityContext = securityContext };      }    }    class PrincipalAuthorizationPolicy : IAuthorizationPolicy    {      string id = Guid.NewGuid().ToString();      IPrincipal user;      public PrincipalAuthorizationPolicy(IPrincipal user)      {        this.user = user;      }      public ClaimSet Issuer      {        get { return ClaimSet.System; }      }      public string Id      {        get { return this.id; }      }      public bool Evaluate(EvaluationContext evaluationContext, ref object state)      {        evaluationContext.AddClaimSet(this, new DefaultClaimSet(System.IdentityModel.Claims.Claim.CreateNameClaim(user.Identity.Name)));        evaluationContext.Properties["Identities"] = new List<IIdentity>(new IIdentity[] { user.Identity });        evaluationContext.Properties["Principal"] = user;        return true;      }    } A WCF Data Service, as any other WCF Service, contains a service host where this interceptor can be injected. The following code illustrates how that can be done in the “svc” file. <%@ ServiceHost Language="C#" Debug="true" Service="ContactsDataService"                 Factory="AppServiceHostFactory" %> using System; using System.ServiceModel; using System.ServiceModel.Activation; using Microsoft.ServiceModel.Web; class AppServiceHostFactory : ServiceHostFactory {    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)   {     WebServiceHost2 result = new WebServiceHost2(serviceType, true, baseAddresses);     result.Interceptors.Add(new SamlAuthenticationInterceptor());                 return result;   } } WCF Data Services includes an specific WCF host of out the box (DataServiceHost). However, the service is not affected at all if you replace it with a custom one as I am doing in the code above (WebServiceHost2 is part of the REST Starter kit). Finally, the client application needs to pass the SAML token somehow to the data service. In case you are using any Http client library for consuming the data service, that’s easy to do, you only need to include the SAML token as part of the “Authorization” header. If you are using the auto-generated data service proxy, a little piece of code is needed to inject a SAML token into the DataServiceContext instance. That class provides an event “SendingRequest” that any client application can leverage to include custom code that modified the Http request before it is sent to the service. So, you can easily create an extension method for the DataServiceContext that negotiates the SAML token with an existing STS, and adds that token as part of the “Authorization” header. public static class DataServiceContextExtensions {        public static void ConfigureFederatedCredentials(this DataServiceContext context, string baseStsAddress, string realm)   {     string address = string.Format(STSAddressFormat, baseStsAddress, realm);                  string token = NegotiateSecurityToken(address);     context.SendingRequest += (source, args) =>     {       args.RequestHeaders.Add("Authorization", token);     };   } private string NegotiateSecurityToken(string address) { } } I left the NegociateSecurityToken method empty for this extension as it depends pretty much on how you are negotiating tokens from an existing STS. In case you want to end-to-end REST solution that involves an Http endpoint for the STS, you should definitely take a look at the Thinktecture starter STS project in codeplex.

    Read the article

  • Master Data Services Employees Sample Model

    - by Davide Mauri
    I’ve been playing with Master Data Services quite a lot in those last days and I’m also monitoring the web for all available resources on it. Today I’ve found this freshly released sample available on MSDN Code Gallery: SQL Server Master Data Services Employee Sample Model http://code.msdn.microsoft.com/SSMDSEmployeeSample This sample shows how Recursive Hierarchies can be modeled in order to represent a typical organizational chart scenario where a self-relationship exists on the Employee entity. Share this post: email it! | bookmark it! | digg it! | reddit! | kick it! | live it!

    Read the article

  • Develop JavaScript API to expose web services [closed]

    - by Apps
    We are planning to develop a JavaScript API to expose some of our J2EE based services. We are doing this keeping Google Maps API in mind. Can someone please suggested where we should start and the approaches that we need to follow to create a useful and extensible JavaScript API? These are the things that we are considering to achieve. It should be very simple for others to use our API. We feel Google Maps API is like that. We should be able to release the updates of the APIs without affecting the existing implementations. We should have enough security measures so that not all can use these services. Please suggest us if there are any books that can guide us through. Any suggestion will be greatly helpful for us. Please let me know if my question is not clear or you need any further information.

    Read the article

  • SQL Server 2008 Express + Reporting Services on Windows 7

    - by TimothyP
    I'm trying to install SQL Server Express 2008 and Reporting Services on a x64 Windows 7 Machine for development purposes. I've installed SQL Server 2008 Express with the Microsoft Web Platform Installer I had to manually enable the SQL Server Browser in the Sql Server Configuration Manager and tried to enable the SQL Server Agent but that simply doesn't work. Keeps throwing an RPC error: "The remote procedure call failed. [0x800706be]". The start mode is set to Disabled and I cannot change it. Even though I selected the SQL Server Express with advanced services in the web platform installer I could not find any reference to SQL Server Reporting Services so I used the SQL Server Installation Center x64 application to "upgrade" to SQL Server Express 2008 with advanced services... this installed many things but still I couldn't find any reference to SQL Server Reporting Services other than an application called: "Reporting Services Configuration Manager" This opens up a dialog called "Reporting Services Configuration Connection" which is asking for a server name (shows the name of my machine) and a Find button. When I click the find button I get: "Unable to connect to the Reporting Server WMI provider. Details: Invalid Namespace". I found some references on the web to solve this problem, but they refer to a directory: "%ProgamFiles%\Microsoft SQL Server\MSRS10.SQL2008\Reporting Services\" which does not exist anywhere on my system. (The directories for SQL Server are there, but there is no Reporting Services directory anywhere). What am I doing wrong here? Wasn't the web platform installer supposed to handle all this? Thnx for any advice. PS: Most google results refer to 2005 vs 2008 problems, but I never had 2005 installed on this system, it's a newly installed development machine.

    Read the article

  • Calling Web Services in classic ASP

    - by cabhilash
      Last day my colleague asked me the provide her a solution to call the Web service from classic ASP. (Yes Classic ASP. still people are using this :D ) We can call web service SOAP toolkit also. But invoking the service using the XMLHTTP object was more easier & fast. To create the Service I used the normal Web Service in .Net 2.0 with [Webmethod] public class WebService1 : System.Web.Services.WebService { [WebMethod] public string HelloWorld(string name){return name + " Pay my dues :) "; // a reminder to pay my consultation fee :D} } In Web.config add the following entry in System.web<webServices><protocols><add name="HttpGet"/><add name="HttpPost"/></protocols></webServices> Alternatively, you can enable these protocols for all Web services on the computer by editing the <protocols> section in Machine.config. The following example enables HTTP GET, HTTP POST, and also SOAP and HTTP POST from localhost: <protocols> <add name="HttpSoap"/> <add name="HttpPost"/> <add name="HttpGet"/> <add name="HttpPostLocalhost"/> <!-- Documentation enables the documentation/test pages --> <add name="Documentation"/> </protocols> By adding these entries I am enabling the HTTPGET & HTTPPOST (After .Net 1.1 by default HTTPGET & HTTPPOST is disabled because of security concerns)The .NET Framework 1.1 defines a new protocol that is named HttpPostLocalhost. By default, this new protocol is enabled. This protocol permits invoking Web services that use HTTP POST requests from applications on the same computer. This is true provided the POST URL uses http://localhost, not http://hostname. This permits Web service developers to use the HTML-based test form to invoke the Web service from the same computer where the Web service resides. Classic ASP Code to call Web service <%Option Explicit Dim objRequest, objXMLDoc, objXmlNode Dim strRet, strError, strNome Dim strName strName= "deepa" Set objRequest = Server.createobject("MSXML2.XMLHTTP") With objRequest .open "GET", "http://localhost:3106/WebService1.asmx/HelloWorld?name=" & strName, False .setRequestHeader "Content-Type", "text/xml" .setRequestHeader "SOAPAction", "http://localhost:3106/WebService1.asmx/HelloWorld" .send End With Set objXMLDoc = Server.createobject("MSXML2.DOMDocument") objXmlDoc.async = false Response.ContentType = "text/xml" Response.Write(objRequest.ResponseText) %> In Line 6 I created an MSXML XMLHTTP object. Line 9 Using the HTTPGET protocol I am openinig connection to WebService Line 10:11 – setting the Header for the service In line 15, I am getting the output from the webservice in XML Doc format & reading the responseText(line 18). In line 9 if you observe I am passing the parameter strName to the Webservice You can pass multiple parameters to the Web service by just like any other QueryString Parameters. In similar fashion you can invoke the Web service using HTTPPost. Only you have to ensure that the form contains all th required parameters for webmethod.  Happy coding !!!!!!!

    Read the article

  • WCF/ADO.NET Data Services - Could not load type 'System.Data.Services.Providers.IDataServiceUpdatePr

    Ad:: SharePoint 2007 Training in .NET 3.5 technologies (more information). This feed URL has been discontinued. Please update your reader's URL to : http://feeds.feedburner.com/winsmarts Read full article .... ...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Patterns & Practices: Composite Services CTP2 is Public

    - by HernanDL
    Finally the last CTP and pre-release version for the Composite Services is out. There were quite a lot of changes since CTP1. We added many new samples and many enhancements to the repository (DB) which is now called Inventory in sync with SOA Patterns. Here is a brief list of the main changes according to the included documentations.   Changes and additions in this release This CTP release contains reusable source code and samples to illustrate implementation for the following patterns and scenarios: Repair and Resubmit – this pattern is implemented in ESB Toolkit 2.0 as part of Exception Management Framework (EMF). This code drop provides code sample how to implement this pattern for Windows AppFabric workflow service, using Exceptions Web Service and workflow activities to create fault message, which will be created in EMF database.  Analytic Tracing – this code drop contains reusable code and samples for implementing ETW tracing: event collector service and database that store collected events. This capability may be used for scenarios that need flexibility on how collected events are decoded and processed via extensibility points you can configure and implement:  plugins and event decoders with leveraging ETW tracing capabilities provided by the event collector service.   Inventory Centralization – this code drop contains service catalog database, web services and samples to show how to implement Metadata Centralization, Schema Centralization and Policy Centralization patterns.  Service Virtualization – we included sample for implementing this pattern using WCF routing service( which is part of .NET framework) and service metadata centralization capabilities to define routing service metadata in service catalog. Termination Notification – we included sample for implementing this pattern using sample WCF service and policy centralization capabilities provided by this CTP release.   You will also find many new videos that will be uploaded to the home page any time soon. Stay tunned for new posts regarding implemetation details and advanced customizations for custom policy exporters/importers and monitoring.

    Read the article

  • Building a home cluster - hardware and cost analysis

    - by ldigas
    Does anyone know some links / books / anything you can think of, that describe the process of building a little home cluster (when I say home, it doesn't necessarily mean for keeping at home - just means it's relatively cheap and small) for experimental purposes, with a special emphasis on what hardware would be adequate today, and some kind of cost analysis ? Although, if someone here's done it, I'd appreciate all the experience you can share.

    Read the article

  • Excel Free Text Survey Question Analysis

    - by joec
    I have to analyse a survey. The survey consists of some yes/no questions, some numeric questions and some questions like the following (free text where respondents have entered multiple answers). Do you have any social networking accounts (Facebook, Twitter, Myspace etc) Y N If yes, which ones _____________________________ Respondents answer: Facebook and Twitter How do I put these types of answer into Excel to gain some sort of useful analysis? Thanks. PS. I know Excel is not great for surveys, but can't spend $1000 on SPSS or similar.

    Read the article

  • Speech recognition (web) services?

    - by Dave Peck
    I have a buffer of audio and I'd like to perform speech recognition/transcription on it. I have limited CPU and RAM locally so I want to perform recognition on a server. Are there any (web) services that allow me to do this? My searches so far have led nowhere...

    Read the article

  • New Executive Q&As on Oracle's Social Services Solution

    - by michael.seback
    According to Calvin Tu, Senior Director Product Management, for Oracle Public Sector, "Government organizations are experiencing unprecedented demand for social services--but many are hampered by..." Read more about the strategy. "They're going to love the ability to automate the prescreening process and eligibility determination, thanks to a natural-language rules engine that..." says John Garrison, Oracle Vice President For CRM Public Sector. Read the rest of the story.

    Read the article

  • Static analysis tool customization for any language

    - by Sam
    Hi, We are using a Tool in our project. This tool has its own language which is similar to Java. I am looking for a static analysis tool which can be applied to the new language. Are there any static analysis tools which can be customized to any languages? or Is there any document or any reference on how to develop the static analysis tool for our own languages? Thanks.

    Read the article

  • Static analysis framework for eclipse?

    - by autobiographer
    i just wanted to use eclipse tptp, a framework for static code analysis but the support for code analysis ended with tptp 4.5.0. 1. it seems that this version can not be integrated into the current eclipse galileo. am i right? 2. which language independant framework for eclipse would you use as an alternative for tptp static analysis which works with eclipse galileo?

    Read the article

  • Java EE Web Services study guides

    - by Marthin
    I´m going for the Java EE 6 Web Services Developer certificat but I´m having a hard time to find som solid study guides and mock exams. I already have the JPA and very soon EJB cert so i´m not new to this stuff but I´v looked at coderanch and other places but all information seems a bit outdated. So any tips for books, mock exams free or not, tutorials or other guides would be very much appreciated. EDIT: I will of course read all JSR´s needed.

    Read the article

  • Analysis and Design for Functional Programming

    - by edalorzo
    How do you deal with analysis and design phases when you plan to develop a system using a functional programming language like Haskell? My background is in imperative/object-oriented programming languages, and therefore, I am used to use case analysis and the use of UML to document the design of program. But the thing is that UML is inherently related to the object-oriented way of doing software. And I am intrigued about what would be the best way to develop documentation and define software designs for a system that is going to be developed using functional programming. Would you still use use case analysis or perhaps structured analysis and design instead? How do software architects define the high-level design of the system so that developers follow it? What do you show to you clients or to new developers when you are supposed to present a design of the solution? How do you document a picture of the whole thing without having first to write it all? Is there anything comparable to UML in the functional world?

    Read the article

  • Interview questions about ASP.NET Web services.

    - by Jalpesh P. Vadgama
    I have seen there are lots of myth’s about asp.net web services in fresher level asp.net developers. So I decided to write a blog post about asp.net web services interview questions. Because I think this is the best way to reach fresher asp.net developers. Followings are few questions about asp.net web services. 1) What is asp.net web services? Ans: Web services are used to support http requests that formatted using xml,http and SOAP syntax. They interact with through standards xml messages through Soap. They are used to support interoperability. It has .asmx extension and .NET framework contains http handlers for web services to support http requested directly. 2) What kind of data can be returned web services web methods? Ans: It supports all the primitive data types and custom data types that can be encoded and serialized by xml. You can find more information about that from the following link. http://msdn.microsoft.com/en-us/library/bb552900.aspx 3) Is web services are only written in asp.net? Ans: No, It can be written by Java and PHP languages also. 4) Explain web method attributes in web services Ans: Web method attributes are added to a public class method to indicate that this method is exposed as a part of XML web services. You can have multiple web methods in a class. But it should be having public attributes as it will be exposed as xml web service part. You can find more information about web method attributes from following link. http://msdn.microsoft.com/en-us/library/byxd99hx(v=vs.71).aspx 5) What is SOA? Ans: SOA stands for “Services Oriented Architecture”. It is kind of service oriented architecture used to support different kind of computing platforms and applications. Web services in asp.net are one of the technologies that supports that kind of architecture.  You can call asp.net web services from any computing platforms and applications. 6) What is SOAP,WDSL and UDDI? Ans: SOAP stands “Simple Object Access protocol”. Web services will be interact with SOAP messages written in XML. SOAP is sometimes referred as “data wrapper” or “data envelope”.Its contains different xml tag that creates a whole SOAP message.  WSDL stand for “Web services Description Language”.  It is an xml document which is written according to standard specified by W3c. It is a kind of manual or document that describes how we can use and consume web service. Web services development software processes the WSDL document and generates SOAP messages that are needed for specific web service. UDDI stand for “Universal Discovery, Description and Integration”. Its is used for web services registries. You can find addresses of web services from UDDI.

    Read the article

  • MDX: Problem filtering results in MDX query used in Reporting Services query

    - by wgpubs
    Why aren't my results being filtered by the members from my [Group Hierarchy] returned via the filter() statment below? SELECT NON EMPTY {[Measures].[Group Count], [Measures].[Overall Group Count] } ON COLUMNS, NON EMPTY { [Survey].[Surveys By Year].[Survey Year].ALLMEMBERS * [Response Status].[Response Status].[Response Status].ALLMEMBERS} DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS FROM ( SELECT ( { [Survey Type].[Survey Type Hierarchy].&[9] } ) ON COLUMNS FROM ( SELECT ( { [Response Status].[Response Status].[All] } ) ON COLUMNS FROM ( SELECT ( STRTOSET(@SurveySurveysByYear, CONSTRAINED) ) ON COLUMNS FROM ( SELECT(filter([Group].[Group Hierarchy].members, instr(@GroupGroupFullName,[Group].[Group Hierarchy].Properties( "Group Full Name" )))) on columns FROM [SysSurveyDW])))) CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS

    Read the article

  • Using Durable Services for saving wcf instances

    - by miker169
    I am currently creating a service which connects to a DAL and that can run a few stored procedures, one of the issues I am facing is that for certain times of the month, we can't update the database, (at the moment this is done manually. This is done via the user adding a note to their calendar) But I would like to automate this process, one of the possible solutions I can think of using is a durable service. When the date is lets say the 1st of the month, the Update/Insert/Delete instances can get saved to a database, and then ran after that date in a batch. Is this the intended use of durable services ? Is there a better route I could possibly take ?

    Read the article

  • Connecting to Magento Web Services with Java

    - by kerry
    I was in the unenviable position of needing to connect to Magento, a PHP ecommerce platform, web services using Java.  It was kind of difficult to get the classes generated from the WSDL so I figured I would throw the results up on my github account for any other poor sap in a similar position. First, pull down the project using git: git clone git://github.com/webdevwilson/magento-java.git and build it with maven: mvn install Here is a quick example of how to pull an order using the generated classes: MagentoServiceLocator serviceLocator = new MagentoServiceLocator(); String url = "http://domain.com/index.php/api/v2_soap"; Mage_Api_Model_Server_V2_HandlerPortType port = serviceLocator.getMage_Api_Model_Server_V2_HandlerPort(url); String sessionId = port.login("username", "key"); SalesOrderEntity salesOrder = port.salesOrderInfo(sessionId, orderId); I also have some wrapper code in there that makes it a little easier to call the API. Checkout the project at https://github.com/webdevwilson/magento-java There is another option. it’s called Magja and it is located at google code.

    Read the article

  • WCF data services - Limiting related objects returned based on critera

    - by Mike Morley
    I have an object graph consisting of a base employee object, and a set of related message objects. I am able to return the employee objects based on search criteria on the employee properties (eg team) etc. However, if I expand on the messages, I get the full collection of messages back. I would like to be able to either take the top n messages (i.e. restrict to 10 most recent) or ideally use a date range on the message objects to limit how many are brought back. So far I have not been able to figure out a way of doing this: I get an error if I attempt to filter on properties on the message (&$filter=employee/message/StartDate gives an error "No property 'StartDate' exists in type 'System.Data.Objects.DataClasses.EntityCollection`1). Attempting to use Top on the message related object doesn't work either. I have also tried using a WebGet extension that takes a string list of employee IDs. That works until the list gets too long, and then fails due to the URL getting too long (it might be possible to setup a paging mechanism on this approach)... Unfortunately the UI control I am using requires the data to be in a fairly specific hierarchical shape, so I can't easily come at this from starting on the message side and working backwards. Outside of making multiple calls does anyone know of a method to accomplish this with wcf data services? Thanks! M.

    Read the article

  • Implementing a generic repository for WCF data services

    - by cibrax
    The repository implementation I am going to discuss here is not exactly what someone would call repository in terms of DDD, but it is an abstraction layer that becomes handy at the moment of unit testing the code around this repository. In other words, you can easily create a mock to replace the real repository implementation. The WCF Data Services update for .NET 3.5 introduced a nice feature to support two way data bindings, which is very helpful for developing WPF or Silverlight based application but also for implementing the repository I am going to talk about. As part of this feature, the WCF Data Services Client library introduced a new collection DataServiceCollection<T> that implements INotifyPropertyChanged to notify the data context (DataServiceContext) about any change in the association links. This means that it is not longer necessary to manually set or remove the links in the data context when an item is added or removed from a collection. Before having this new collection, you basically used the following code to add a new item to a collection. Order order = new Order {   Name = "Foo" }; OrderItem item = new OrderItem {   Name = "bar",   UnitPrice = 10,   Qty = 1 }; var context = new OrderContext(); context.AddToOrders(order); context.AddToOrderItems(item); context.SetLink(item, "Order", order); context.SaveChanges(); Now, thanks to this new collection, everything is much simpler and similar to what you have in other ORMs like Entity Framework or L2S. Order order = new Order {   Name = "Foo" }; OrderItem item = new OrderItem {   Name = "bar",   UnitPrice = 10,   Qty = 1 }; order.Items.Add(item); var context = new OrderContext(); context.AddToOrders(order); context.SaveChanges(); In order to use this new feature, you first need to enable V2 in the data service, and then use some specific arguments in the datasvcutil tool (You can find more information about this new feature and how to use it in this post). DataSvcUtil /uri:"http://localhost:3655/MyDataService.svc/" /out:Reference.cs /dataservicecollection /version:2.0 Once you use those two arguments, the generated proxy classes will use DataServiceCollection<T> rather than a simple ObjectCollection<T>, which was the default collection in V1. There are some aspects that you need to know to use this feature correctly. 1. All the entities retrieved directly from the data context with a query track the changes and report those to the data context automatically. 2. A entity created with “new” does not track any change in the properties or associations. In order to enable change tracking in this entity, you need to do the following trick. public Order CreateOrder() {   var collection = new DataServiceCollection<Order>(this.context);   var order = new Order();   collection.Add(order);   return order; } You basically need to create a collection, and add the entity to that collection with the “Add” method to enable change tracking on that entity. 3. If you need to attach an existing entity (For example, if you created the entity with the “new” operator rather than retrieving it from the data context with a query) to a data context for tracking changes, you can use the “Load” method in the DataServiceCollection. var order = new Order {   Id = 1 }; var collection = new DataServiceCollection<Order>(this.context); collection.Load(order); In this case, the order with Id = 1 must exist on the data source exposed by the Data service. Otherwise, you will get an error because the entity did not exist. These cool extensions methods discussed by Stuart Leeks in this post to replace all the magic strings in the “Expand” operation with Expression Trees represent another feature I am going to use to implement this generic repository. Thanks to these extension methods, you could replace the following query with magic strings by a piece of code that only uses expressions. Magic strings, var customers = dataContext.Customers .Expand("Orders")         .Expand("Orders/Items") Expressions, var customers = dataContext.Customers .Expand(c => c.Orders.SubExpand(o => o.Items)) That query basically returns all the customers with their orders and order items. Ok, now that we have the automatic change tracking support and the expression support for explicitly loading entity associations, we are ready to create the repository. The interface for this repository looks like this,public interface IRepository { T Create<T>() where T : new(); void Update<T>(T entity); void Delete<T>(T entity); IQueryable<T> RetrieveAll<T>(params Expression<Func<T, object>>[] eagerProperties); IQueryable<T> Retrieve<T>(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] eagerProperties); void Attach<T>(T entity); void SaveChanges(); } The Retrieve and RetrieveAll methods are used to execute queries against the data service context. While both methods receive an array of expressions to load associations explicitly, only the Retrieve method receives a predicate representing the “where” clause. The following code represents the final implementation of this repository.public class DataServiceRepository: IRepository { ResourceRepositoryContext context; public DataServiceRepository() : this (new DataServiceContext()) { } public DataServiceRepository(DataServiceContext context) { this.context = context; } private static string ResolveEntitySet(Type type) { var entitySetAttribute = (EntitySetAttribute)type.GetCustomAttributes(typeof(EntitySetAttribute), true).FirstOrDefault(); if (entitySetAttribute != null) return entitySetAttribute.EntitySet; return null; } public T Create<T>() where T : new() { var collection = new DataServiceCollection<T>(this.context); var entity = new T(); collection.Add(entity); return entity; } public void Update<T>(T entity) { this.context.UpdateObject(entity); } public void Delete<T>(T entity) { this.context.DeleteObject(entity); } public void Attach<T>(T entity) { var collection = new DataServiceCollection<T>(this.context); collection.Load(entity); } public IQueryable<T> Retrieve<T>(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] eagerProperties) { var entitySet = ResolveEntitySet(typeof(T)); var query = context.CreateQuery<T>(entitySet); foreach (var e in eagerProperties) { query = query.Expand(e); } return query.Where(predicate); } public IQueryable<T> RetrieveAll<T>(params Expression<Func<T, object>>[] eagerProperties) { var entitySet = ResolveEntitySet(typeof(T)); var query = context.CreateQuery<T>(entitySet); foreach (var e in eagerProperties) { query = query.Expand(e); } return query; } public void SaveChanges() { this.context.SaveChanges(SaveChangesOptions.Batch); } } For instance, you can use the following code to retrieve customers with First name equal to “John”, and all their orders in a single call. repository.Retrieve<Customer>(    c => c.FirstName == “John”, //Where    c => c.Orders.SubExpand(o => o.Items)); In case, you want to have some pre-defined queries that you are going to use across several places, you can put them in an specific class. public static class CustomerQueries {   public static Expression<Func<Customer, bool>> LastNameEqualsTo(string lastName)   {     return c => c.LastName == lastName;   } } And then, use it with the repository. repository.Retrieve<Customer>(    CustomerQueries.LastNameEqualsTo("foo"),    c => c.Orders.SubExpand(o => o.Items));

    Read the article

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