Search Results

Search found 86 results on 4 pages for 'dataservice'.

Page 2/4 | < Previous Page | 1 2 3 4  | Next Page >

  • How to deal with class composition when components cannot be accessed from the outside?

    - by Chathuranga
    For example if I say I have three classes A, B, and C where B and C have a composition relation ship with A. That means the life of B and C is handled by A, and also B and C cannot access directly from the outside. For some reason my DataService class needs to return objects of B and C as It cant return a object of A as B and C cannot be initialized at the same time. (to be able to initializeC you have to initializeB first). So that I'm returning DataTables from DataService and then inside the class A those data tables are converted to B / C objects. If B and C objects cannot be initialized at the same time is it valid to say that B and C have a composition relationship with A? If its composition is it must to generate A with B and C inside? What is the proper way to handle this sort of a problem? EDIT: Following code explains the way I'm doing it now with DataTables. Example: class A { private List<B> B; private List <C> C; public A() { B= new List<B>(); C= new List<C>(); } public List<B> GetB( DataTable dt) { // Create a B list from dt return B; } } class Presenter { private void Show B() { _View.DataGrid = A.GetB(DataService.GetAListOfB()); } } The actual scenario is I have a class called WageInfo and classes Earning and Deduction having a composition relationship in the design. But for you to generate Deductions first you should Generate earnings and should be saved in a table. Then only you can generate deductions for the earnings to calculate balance wages. Also note that these contained classes have a one to many relationship with the containing class WageInfo. So actually WageInfo has a List<Earnings> and List<Deduction> My initial question was, is it ok if my DataService class returns Deductions / Earnings objects (actually lists) not a WageInfo? Still not clear?

    Read the article

  • Using Teleriks new LINQ implementation to create OData feeds

    This week Telerik released a new LINQ implementation that is simple to use and produces domain models very fast. Built on top of the enterprise grade OpenAccess ORM, you can connect to any database that OpenAccess can connect to such as: SQL Server, MySQL, Oracle, SQL Azure, VistaDB, etc. While this is a separate LINQ implementation from traditional OpenAccess Entites, you can use the visual designer without ever interacting with OpenAccess, however, you can always hook into the advanced ORM features like caching, fetch plan optimization, etc, if needed. Just to show off how easy our LINQ implementation is to use, I will walk you through building an OData feed using Data Services Update for .NET Framework 3.5 SP1. (Memo to Microsoft: P-L-E-A-S-E hire someone from Apple to name your products.) How easy is it? If you have a fast machine, are skilled with the mouse, and type fast, you can do this in about 60 seconds via three easy steps. (I promise in about 2-3 weeks that you can do this in less then 30 seconds. Stay tuned for that.)  Step 1 (15-20 seconds): Building your Domain Model In your web project in Visual Studio, right click on the project and select Add|New Item and select Telerik OpenAccess Domain Model as your item template. Give the file a meaningful name as well. Select your database type (SQL Server, SQL Azure, Oracle, MySQL, VistaDB, etc) and build the connection string. If you already have a Visual Studio connection string already saved, this step is trivial.  Then select your tables, enter a name for your model and click Finish. In this case I connected to Northwind and selected only Customers, Orders, and Order Details.  I named my model NorthwindEntities and will use that in my DataService. Step 2 (20-25 seconds): Adding and Configuring your Data Service In your web project in Visual Studio, right click on the project and select Add|New Item and select ADO .NET Data Service as your item template and name your service. In the code behind for your Data Service you have to make three small changes. Add the name of your Telerik Domain Model (entered in Step 1) as the DataService name (shown on line 6 below as NorthwindEntities) and uncomment line 11 and add a * to show all entities. Optionally if you want to take advantage of the DataService 3.5 updates, add line 13 (and change IDataServiceConfiguration to DataServiceConfiguration in line 9.) 1: using System.Data.Services; 2: using System.Data.Services.Common; 3:   4: namespace Telerik.RLINQ.Astoria.Web 5: { 6: public class NorthwindService : DataService<NorthwindEntities> 7: { 8: //change the IDataServiceConfigurationto DataServiceConfiguration 9: public static void InitializeService(DataServiceConfiguration config) 10: { 11: config.SetEntitySetAccessRule("*", EntitySetRights.All); 12: //take advantage of the "Astoria3.5 Update" features 13: config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; 14: } 15: } 16: } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   Step 3 (~30 seconds): Adding the DataServiceKeys You now have to tell your data service what are the primary keys of each entity. To do this you have to create a new code file and create a few partial classes. If you type fast, use copy and paste from your first entity,  and use a refactoring productivity tool, you can add these 6-8 lines of code or so in about 30 seconds. This is the most tedious step, but dont worry, Ive bribed some of the developers and our next update will eliminate this step completely. Just create a partial class for each entity you have mapped and add the attribute [DataServiceKey] on top of it along with the keys field name. If you have any complex properties, you will need to make them a primitive type, as I do in line 15. Create this as a separate file, dont manipulate the generated data access classes in case you want to regenerate them again later (even thought that would be much faster.) 1: using System.Data.Services.Common; 2:   3: namespace Telerik.RLINQ.Astoria.Web 4: { 5: [DataServiceKey("CustomerID")] 6: public partial class Customer 7: { 8: } 9:   10: [DataServiceKey("OrderID")] 11: public partial class Order 12: { 13: } 14:   15: [DataServiceKey(new string[] { "OrderID", "ProductID" })] 16: public partial class OrderDetail 17: { 18: } 19:   20: } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   Done! Time to run the service. Now, lets run the service! Select the svc file and right click and say View in Browser. You will see your OData service and can interact with it in the browser. Now that you have an OData service set up, you can consume it in one of the many ways that OData is consumed: using LINQ, the Silverlight OData client, Excel PowerPivot, or PhP, etc. Happy Data Servicing! Technorati Tags: Telerik,Astoria,Data Services 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

  • Adventures in Windows 8: Understanding and debugging design time data in Expression Blend

    - by Laurent Bugnion
    One of my favorite features in Expression Blend is the ability to attach a Visual Studio debugger to Blend. First let’s start by answering the question: why exactly do you want to do that? Note: If you are familiar with the creation and usage of design time data, feel free to scroll down to the paragraph titled “When design time data fails”. Creating design time data for your app When a designer works on an app, he needs to see something to design. For “static” UI such as buttons, backgrounds, etc, the user interface elements are going to show up in Blend just fine. If however the data is fetched dynamically from a service (web, database, etc) or created dynamically, most probably Blend is going to show just an empty element. The classical way to design at that stage is to run the application, navigate to the screen that is under construction (which can involve delays, need to log in, etc…), to measure what is on the screen (colors, margins, width and height, etc) using various tools, going back to Blend, editing the properties of the elements, running again, etc. Obviously this is not ideal. The solution is to create design time data. For more information about the creation of design time data by mocking services, you can refer to two talks of mine “Deep dive MVVM” and “MVVM Applied From Silverlight to Windows Phone to Windows 8”. The source code for these talks is here and here. Design time data in MVVM Light One of the main reasons why I developed MVVM Light is to facilitate the creation of design time data. To illustrate this, let’s create a new MVVM Light application in Visual Studio. Install MVVM Light from here: http://mvvmlight.codeplex.com (use the MSI in the Download section). After installing, make sure to read the Readme that opens up in your favorite browser, you will need one more step to install the Project Templates. Start Visual Studio 2012. Create a new MvvmLight (Win8) app. Run the application. You will see a string showing “Welcome to MVVM Light”. In the Solution explorer, right click on MainPage.xaml and select Open in Blend. Now you should see “Welcome to MVVM Light [Design]” What happens here is that Expression Blend runs different code at design time than the application runs at runtime. To do this, we use design-time detection (as explained in a previous article) and use that information to initialize a different data service at design time. To understand this better, open the ViewModelLocator.cs file in the ViewModel folder and see how the DesignDataService is used at design time, while the DataService is used at runtime. In a real-life applicationm, DataService would be used to connect to a web service, for instance. When design time data fails Sometimes however, the creation of design time data fails. It can be very difficult to understand exactly what is happening. Expression Blend is not giving a lot of information about what happened. Thankfully, we can use a trick: Attaching a debugger to Expression Blend and debug the design time code. In WPF and Silverlight (including Windows Phone 7), you could simply attach the debugger to Blend.exe (using the “Managed (v4.5, v4.0) code” option even for Silverlight!!) In Windows 8 however, things are just a bit different. This is because the designer that renders the actual representation of the Windows 8 app runs in its own process. Let’s illustrate that: Open the file DesignDataService in the Design folder. Modify the GetData method to look like this: public void GetData(Action<DataItem, Exception> callback) { throw new Exception(); // Use this to create design time data var item = new DataItem("Welcome to MVVM Light [design]"); callback(item, null); } Go to Blend and build the application. The build succeeds, but now the page is empty. The creation of the design time data failed, but we don’t get a warning message. We need to investigate what’s wrong. Close MainPage.xaml Go to Visual Studio and select the menu Debug, Attach to Process. Update: Make sure that you select “Managed (v4.5, v4.0) code” in the “Attach to” field. Find the process named XDesProc.exe. You should have at least two, one for the Visual Studio 2012 designer surface, and one for Expression Blend. Unfortunately in this screen it is not obvious which is which. Let’s find out in the Task Manager. Press Ctrl-Alt-Del and select Task Manager Go to the Details tab and sort the processes by name. Find the one that says “Blend for Microsoft Visual Studio 2012 XAML UI Designer” and write down the process ID. Go back to the Attach to Process dialog in Visual Studio. sort the processes by ID and attach the debugger to the correct instance of XDesProc.exe. Open the MainViewModel (in the ViewModel folder) Place a breakpoint on the first line of the MainViewModel constructor. Go to Blend and open the MainPage.xaml again. At this point, the debugger breaks in Visual Studio and you can execute your code step by step. Simply step inside the dataservice call, and find the exception that you had placed there. Visual Studio gives you additional information which helps you to solve the issue. More info and Conclusion I want to thank the amazing people on the Expression Blend team for being very fast in guiding me in that matter and encouraging me to blog about it. More information about the XDesProc.exe process can be found here. I had to work on a Windows 8 app for a few days without design time data because of an Exception thrown somewhere in the code, and it was really painful. With the debugger, finding the issue was a simple matter of stepping into the code until it threw the exception.   Laurent Bugnion (GalaSoft) Subscribe | Twitter | Facebook | Flickr | LinkedIn

    Read the article

  • Same data being returned by linq for 2 different executions of a stored procedure?

    - by Paul
    Hello I have a stored procedure that I am calling through Entity Framework. The stored procedure has 2 date parameters. I supply different argument in the 2 times I call the stored procedure. I have verified using SQL Profiler that the stored procedure is being called correctly and returning the correct results. When I call my method the second time with different arguments, even though the stored procedure is bringing back the correct results, the table created contains the same data as the first time I called it. dtStart = 01/08/2009 dtEnd = 31/08/2009 public List<dataRecord> GetData(DateTime dtStart, DateTime dtEnd) { var tbl = from t in db.SP(dtStart, dtEnd) select t; return tbl.ToList(); } GetData((new DateTime(2009, 8, 1), new DateTime(2009, 8, 31)) // tbl.field1 value = 45450 - CORRECT GetData(new DateTime(2009, 7, 1), new DateTime(2009, 7, 31)) // tbl.field1 value = 45450 - WRONG 27456 expected Is this a case of Entity Framework being clever and caching? I can't see why it would cache this though as it has executed the stored procedure twice. Do I have to do something to close tbl? using Visual Studio 2008 + Entity Framework. I also get the message "query cannot be enumerated more than once" a few times every now and then, am not sure if that is relevant? FULL CODE LISTING namespace ProfileDataService { public partial class DataService { public static List<MeterTotalConsumpRecord> GetTotalAllTimesConsumption(DateTime dtStart, DateTime dtEnd, EUtilityGroup ug, int nMeterSelectionType, int nCustomerID, int nUserID, string strSelection, bool bClosedLocations, bool bDisposedLocations) { dbChildDataContext db = DBManager.ChildDataConext(nCustomerID); var tbl = from t in db.GetTotalConsumptionByMeter(dtStart, dtEnd, (int) ug, nMeterSelectionType, nCustomerID, nUserID, strSelection, bClosedLocations, bDisposedLocations, 1) select t; return tbl.ToList(); } } } /// CALLER List<MeterTotalConsumpRecord> _P1Totals; List<MeterTotalConsumpRecord> _P2Totals; public void LoadData(int nUserID, int nCustomerID, ELocationSelectionMethod locationSelectionMethod, string strLocations, bool bIncludeClosedLocations, bool bIncludeDisposedLocations, DateTime dtStart, DateTime dtEnd, ReportsBusinessLogic.Lists.EPeriodType durMainPeriodType, ReportsBusinessLogic.Lists.EPeriodType durCompareToPeriodType, ReportsBusinessLogic.Lists.EIncreaseReportType rptType, bool bIncludeDecreases) { ///Code for setting properties using parameters.. _P2Totals = ProfileDataService.DataService.GetTotalAllTimesConsumption(_P2StartDate, _P2EndDate, EUtilityGroup.Electricity, 1, nCustomerID, nUserID, strLocations, bIncludeClosedLocations, bIncludeDisposedLocations); _P1Totals = ProfileDataService.DataService.GetTotalAllTimesConsumption(_StartDate, _EndDate, EUtilityGroup.Electricity, 1, nCustomerID, nUserID, strLocations, bIncludeClosedLocations, bIncludeDisposedLocations); PopulateLines() //This fills up a list of objects with information for my report ready for the totals to be added PopulateTotals(_P1Totals, 1); PopulateTotals(_P2Totals, 2); } void PopulateTotals(List<MeterTotalConsumpRecord> objTotals, int nPeriod) { MeterTotalConsumpRecord objMeterConsumption = null; foreach (IncreaseReportDataRecord objLine in _Lines) { objMeterConsumption = objTotals.Find(delegate(MeterTotalConsumpRecord t) { return t.MeterID == objLine.MeterID; }); if (objMeterConsumption != null) { if (nPeriod == 1) { objLine.P1Consumption = (double)objMeterConsumption.Consumption; } else { objLine.P2Consumption = (double)objMeterConsumption.Consumption; } objMeterConsumption = null; } } } }

    Read the article

  • Modify Address of asmx Method Call

    - by Adam
    When I'm making asmx web service calls from Silverlight, is there any way to have the (generated) SoapClient objects modify the address that they call the service on? Specifically, I'd like to tack on a QueryString value onto each call that the service makes. So if I have DataService.SilverlightServiceSoapClient C = new DataService.SilverlightServiceSoapClient(); Is there any way to do something like: C.Address += "?Foo=Bar"; Which would allow me to, from my WebMethod, say: HttpContext.Current.Request.QueryString["foo"]; Obviously I can modify my WebMethods to take this value in as a parameter, but I'd like to avoid doing that if possible.

    Read the article

  • Fix: WCF - The type provided as the Service attribute value in the ServiceHost directive could not

    I wanted to expose some raw data to users in my current ASP.NET 3.5 web site project. I created a subdirectory called datafeeds and added a WCF Data Service. I wired the dataservice up to the Entity Framework class and, on running the ItemDataService...(read more)...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

  • S#harp architecture mapping many to many and ado.net data services: A single resource was expected f

    - by Leg10n
    Hi, I'm developing an application that reads data from a SQL server database (migrated from a legacy DB) with nHibernate and s#arp architecture through ADO.NET Data services. I'm trying to map a many-to-many relationship. I have a Error class: public class Error { public virtual int ERROR_ID { get; set; } public virtual string ERROR_CODE { get; set; } public virtual string DESCRIPTION { get; set; } public virtual IList<ErrorGroup> GROUPS { get; protected set; } } And then I have the error group class: public class ErrorGroup { public virtual int ERROR_GROUP_ID {get; set;} public virtual string ERROR_GROUP_NAME { get; set; } public virtual string DESCRIPTION { get; set; } public virtual IList<Error> ERRORS { get; protected set; } } And the overrides: public class ErrorGroupOverride : IAutoMappingOverride<ErrorGroup> { public void Override(AutoMapping<ErrorGroup> mapping) { mapping.Table("ERROR_GROUP"); mapping.Id(x => x.ERROR_GROUP_ID, "ERROR_GROUP_ID"); mapping.IgnoreProperty(x => x.Id); mapping.HasManyToMany<Error>(x => x.Error) .Table("ERROR_GROUP_LINK") .ParentKeyColumn("ERROR_GROUP_ID") .ChildKeyColumn("ERROR_ID").Inverse().AsBag(); } } public class ErrorOverride : IAutoMappingOverride<Error> { public void Override(AutoMapping<Error> mapping) { mapping.Table("ERROR"); mapping.Id(x => x.ERROR_ID, "ERROR_ID"); mapping.IgnoreProperty(x => x.Id); mapping.HasManyToMany<ErrorGroup>(x => x.GROUPS) .Table("ERROR_GROUP_LINK") .ParentKeyColumn("ERROR_ID") .ChildKeyColumn("ERROR_GROUP_ID").AsBag(); } } When I view the Data service in the browser like: http://localhost:1905/DataService.svc/Errors it shows the list of errors with no problems, and using it like http://localhost:1905/DataService.svc/Errors(123) works too. The Problem When I want to see the Errors in a group or the groups form an error, like: "http://localhost:1905/DataService.svc/Errors(123)?$expand=GROUPS" I get the XML Document, but the browser says: The XML page cannot be displayed Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later. -------------------------------------------------------------------------------- Only one top level element is allowed in an XML document. Error processing resource 'http://localhost:1905/DataServic... <error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"> -^ I view the sourcecode, and I get the data. However it comes with an exception: <error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"> <code></code> <message xml:lang="en-US">An error occurred while processing this request.</message> <innererror xmlns="xmlns"> <message>A single resource was expected for the result, but multiple resources were found.</message> <type>System.InvalidOperationException</type> <stacktrace> at System.Data.Services.Serializers.Serializer.WriteRequest(IEnumerator queryResults, Boolean hasMoved)&#xD; at System.Data.Services.ResponseBodyWriter.Write(Stream stream)</stacktrace> </innererror> </error> A I missing something??? Where does this error come from?

    Read the article

  • If I use a facade class with generic methods to access the JPA API, how should I provide additional processing for specific types?

    - by Shaun
    Let's say I'm making a fairly simple web application using JAVA EE specs (I've heard this is possible). In this app, I only have about 10 domain/data objects, and these are represented by JPA Entities. Architecturally, I would consider the JPA API to perform the role of a DAO. Of course, I don't want to use the EntityManager directly in my UI (JSF) and I need to manage transactions, so I delegate these tasks to the so-called service layer. More specifically, I would like to be able to handle these tasks in a single DataService class (often also called CrudService) with generic methods. See this article by Adam Bien for an example interface: http://www.adam-bien.com/roller/abien/entry/generic_crud_service_aka_dao My project differs from that article in that I can't use EJBs, so my service classes are essentially just named beans and I handle transactions manually. Regardless, what I want is a single interface for simple CRUD operations on my data objects because having a different class for each data type would lead to a lot of duplicate and/or unnecessary code. Ideally, my views would be able to use a method such as public <T> List<T> findAll(Class<T> type) { ... } to retrieve data. Using JSF, it might look something like this: <h:dataTable value="#{dataService.findAll(data.class)}" var="d"> ... </h:dataTable> Similarly, after validating forms, my controller could submit the data with a method such as: public <T> void add(T entity) { ... } Granted, you'd probably actually want to return something useful to the caller. In any case, this works well if your data can be treated as homogenous in this manner. Alas, it breaks down when you need to perform additional processing on certain objects before passing them on to JPA. For example, let's say I'm dealing with Books and Authors which have a many-to-many relationship. Each Book has a set of IDs referring to its authors, and each Author has a set of IDs referring to their books. Normally, JPA can manage this kind of relationship for you, but in some cases it can't (for example, the google app engine JPA provider doesn't support this). Thus, when I persist a new book for example, I may need to update the corresponding author entities. My question, then, is if there's an elegant way to handle this or if I should reconsider the sanity of my whole design. Here's a couple ways I see of dealing with it: The instanceof operator. I could use this to target certain classes when special processing is needed. Perhaps maintainability suffers and it isn't beautiful code, but if there's only 10 or so domain objects it can't be all that bad... could it? Make a different service for each entity type (ie, BookService and AuthorService). All services would inherit from a generic DataService base class and override methods if special processing is needed. At this point, you could probably also just call them DAOs instead. As always, I appreciate the help. Let me know if any clarifications are needed, as I left out many smaller details.

    Read the article

  • Guice and JSF 2

    - by digitaljoel
    I'm trying to use Guice to inject properties of a JSF managed bean. This is all running on Google App Engine (which may or may not be important) I've followed the instructions here: http://code.google.com/docreader/#p=google-guice&s=google-guice&t=GoogleAppEngine One problem is in the first step. I can't subclass the Servlet module and setup my servlet mappings there because Faces is handled by the javax.faces.webapp.FacesServlet which subclasses Servlet, not HttpServlet. So, I tried leaving my servlet configuration in the web.xml file and simply instantiating a new ServletModel() along with my business module when creating the injector in the context listener described in the second step. Having done all that, along with the web.xml configuration, my managed bean isn't getting any properties injected. The method is as follows @ManagedBean @ViewScoped public class ViewTables implements Serializable { private DataService<Table> service; @Inject public void setService( DataService<Table> service ) { this.service = service; } public List<Table> getTables() { return service.getAll(); } } So, I'm wondering if there is a trick to get Guice injecting into a JSF managed bean? I obviously can't use the constructor injection because JSF needs a no-arg constructor to create the bean.

    Read the article

  • How do I authenticate an ADO.NET Data Service?

    - by lsb
    Hi! I've created an ADO.Net Data Service hosted in a Azure worker role. I want to pass credentials from a simple console client to the service then validate them using a QueryInterceptor. Unfortunately, the credentials don't seem to be making it over the wire. The following is a simplified version of the code I'm using, starting with the DataService on the server: using System; using System.Data.Services; using System.Linq.Expressions; using System.ServiceModel; using System.Web; namespace Oslo.Worker { [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)] public class AdminService : DataService<OsloEntities> { public static void InitializeService( IDataServiceConfiguration config) { config.SetEntitySetAccessRule("*", EntitySetRights.All); config.SetServiceOperationAccessRule("*", ServiceOperationRights.All); } [QueryInterceptor("Pairs")] public Expression<Func<Pair, bool>> OnQueryPairs() { // This doesn't work!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (HttpContext.Current.User.Identity.Name != "ADMIN") throw new Exception("Ooops!"); return p => true; } } } Here's the AdminService I'm using to instantiate the AdminService in my Azure worker role: using System; using System.Data.Services; namespace Oslo.Worker { public class AdminHost : DataServiceHost { public AdminHost(Uri baseAddress) : base(typeof(AdminService), new Uri[] { baseAddress }) { } } } And finally, here's the client code. using System; using System.Data.Services.Client; using System.Net; using Oslo.Shared; namespace Oslo.ClientTest { public class AdminContext : DataServiceContext { public AdminContext(Uri serviceRoot, string userName, string password) : base(serviceRoot) { Credentials = new NetworkCredential(userName, password); } public DataServiceQuery<Order> Orders { get { return base.CreateQuery<Pair>("Orders"); } } } } I should mention that the code works great with the signal exception that the credentials are not being passed over the wire. Any help in this regard would be greatly appreciated! Thanks....

    Read the article

  • ASP.NET and HTML5 Local Storage

    - by Stephen Walther
    My favorite feature of HTML5, hands-down, is HTML5 local storage (aka DOM storage). By taking advantage of HTML5 local storage, you can dramatically improve the performance of your data-driven ASP.NET applications by caching data in the browser persistently. Think of HTML5 local storage like browser cookies, but much better. Like cookies, local storage is persistent. When you add something to browser local storage, it remains there when the user returns to the website (possibly days or months later). Importantly, unlike the cookie storage limitation of 4KB, you can store up to 10 megabytes in HTML5 local storage. Because HTML5 local storage works with the latest versions of all modern browsers (IE, Firefox, Chrome, Safari), you can start taking advantage of this HTML5 feature in your applications right now. Why use HTML5 Local Storage? I use HTML5 Local Storage in the JavaScript Reference application: http://Superexpert.com/JavaScriptReference The JavaScript Reference application is an HTML5 app that provides an interactive reference for all of the syntax elements of JavaScript (You can read more about the application and download the source code for the application here). When you open the application for the first time, all of the entries are transferred from the server to the browser (all 300+ entries). All of the entries are stored in local storage. When you open the application in the future, only changes are transferred from the server to the browser. The benefit of this approach is that the application performs extremely fast. When you click the details link to view details on a particular entry, the entry details appear instantly because all of the entries are stored on the client machine. When you perform key-up searches, by typing in the filter textbox, matching entries are displayed very quickly because the entries are being filtered on the local machine. This approach can have a dramatic effect on the performance of any interactive data-driven web application. Interacting with data on the client is almost always faster than interacting with the same data on the server. Retrieving Data from the Server In the JavaScript Reference application, I use Microsoft WCF Data Services to expose data to the browser. WCF Data Services generates a REST interface for your data automatically. Here are the steps: Create your database tables in Microsoft SQL Server. For example, I created a database named ReferenceDB and a database table named Entities. Use the Entity Framework to generate your data model. For example, I used the Entity Framework to generate a class named ReferenceDBEntities and a class named Entities. Expose your data through WCF Data Services. I added a WCF Data Service to my project and modified the data service class to look like this:   using System.Data.Services; using System.Data.Services.Common; using System.Web; using JavaScriptReference.Models; namespace JavaScriptReference.Services { [System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)] public class EntryService : DataService<ReferenceDBEntities> { // This method is called only once to initialize service-wide policies. public static void InitializeService(DataServiceConfiguration config) { config.UseVerboseErrors = true; config.SetEntitySetAccessRule("*", EntitySetRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } // Define a change interceptor for the Products entity set. [ChangeInterceptor("Entries")] public void OnChangeEntries(Entry entry, UpdateOperations operations) { if (!HttpContext.Current.Request.IsAuthenticated) { throw new DataServiceException("Cannot update reference unless authenticated."); } } } }     The WCF data service is named EntryService. Notice that it derives from DataService<ReferenceEntitites>. Because it derives from DataService<ReferenceEntities>, the data service exposes the contents of the ReferenceEntitiesDB database. In the code above, I defined a ChangeInterceptor to prevent un-authenticated users from making changes to the database. Anyone can retrieve data through the service, but only authenticated users are allowed to make changes. After you expose data through a WCF Data Service, you can use jQuery to retrieve the data by performing an Ajax call. For example, I am using an Ajax call that looks something like this to retrieve the JavaScript entries from the EntryService.svc data service: $.ajax({ dataType: "json", url: “/Services/EntryService.svc/Entries”, success: function (result) { var data = callback(result["d"]); } });     Notice that you must unwrap the data using result[“d”]. After you unwrap the data, you have a JavaScript array of the entries. I’m transferring all 300+ entries from the server to the client when the application is opened for the first time. In other words, I transfer the entire database from the server to the client, once and only once, when the application is opened for the first time. The data is transferred using JSON. Here is a fragment: { "d" : [ { "__metadata": { "uri": "http://superexpert.com/javascriptreference/Services/EntryService.svc/Entries(1)", "type": "ReferenceDBModel.Entry" }, "Id": 1, "Name": "Global", "Browsers": "ff3_6,ie8,ie9,c8,sf5,es3,es5", "Syntax": "object", "ShortDescription": "Contains global variables and functions", "FullDescription": "<p>\nThe Global object is determined by the host environment. In web browsers, the Global object is the same as the windows object.\n</p>\n<p>\nYou can use the keyword <code>this</code> to refer to the Global object when in the global context (outside of any function).\n</p>\n<p>\nThe Global object holds all global variables and functions. For example, the following code demonstrates that the global <code>movieTitle</code> variable refers to the same thing as <code>window.movieTitle</code> and <code>this.movieTitle</code>.\n</p>\n<pre>\nvar movieTitle = \"Star Wars\";\nconsole.log(movieTitle === this.movieTitle); // true\nconsole.log(movieTitle === window.movieTitle); // true\n</pre>\n", "LastUpdated": "634298578273756641", "IsDeleted": false, "OwnerId": null }, { "__metadata": { "uri": "http://superexpert.com/javascriptreference/Services/EntryService.svc/Entries(2)", "type": "ReferenceDBModel.Entry" }, "Id": 2, "Name": "eval(string)", "Browsers": "ff3_6,ie8,ie9,c8,sf5,es3,es5", "Syntax": "function", "ShortDescription": "Evaluates and executes JavaScript code dynamically", "FullDescription": "<p>\nThe following code evaluates and executes the string \"3+5\" at runtime.\n</p>\n<pre>\nvar result = eval(\"3+5\");\nconsole.log(result); // returns 8\n</pre>\n<p>\nYou can rewrite the code above like this:\n</p>\n<pre>\nvar result;\neval(\"result = 3+5\");\nconsole.log(result);\n</pre>", "LastUpdated": "634298580913817644", "IsDeleted": false, "OwnerId": 1 } … ]} I worried about the amount of time that it would take to transfer the records. According to Google Chome, it takes about 5 seconds to retrieve all 300+ records on a broadband connection over the Internet. 5 seconds is a small price to pay to avoid performing any server fetches of the data in the future. And here are the estimated times using different types of connections using Fiddler: Notice that using a modem, it takes 33 seconds to download the database. 33 seconds is a significant chunk of time. So, I would not use the approach of transferring the entire database up front if you expect a significant portion of your website audience to connect to your website with a modem. Adding Data to HTML5 Local Storage After the JavaScript entries are retrieved from the server, the entries are stored in HTML5 local storage. Here’s the reference documentation for HTML5 storage for Internet Explorer: http://msdn.microsoft.com/en-us/library/cc197062(VS.85).aspx You access local storage by accessing the windows.localStorage object in JavaScript. This object contains key/value pairs. For example, you can use the following JavaScript code to add a new item to local storage: <script type="text/javascript"> window.localStorage.setItem("message", "Hello World!"); </script>   You can use the Google Chrome Storage tab in the Developer Tools (hit CTRL-SHIFT I in Chrome) to view items added to local storage: After you add an item to local storage, you can read it at any time in the future by using the window.localStorage.getItem() method: <script type="text/javascript"> window.localStorage.setItem("message", "Hello World!"); </script>   You only can add strings to local storage and not JavaScript objects such as arrays. Therefore, before adding a JavaScript object to local storage, you need to convert it into a JSON string. In the JavaScript Reference application, I use a wrapper around local storage that looks something like this: function Storage() { this.get = function (name) { return JSON.parse(window.localStorage.getItem(name)); }; this.set = function (name, value) { window.localStorage.setItem(name, JSON.stringify(value)); }; this.clear = function () { window.localStorage.clear(); }; }   If you use the wrapper above, then you can add arbitrary JavaScript objects to local storage like this: var store = new Storage(); // Add array to storage var products = [ {name:"Fish", price:2.33}, {name:"Bacon", price:1.33} ]; store.set("products", products); // Retrieve items from storage var products = store.get("products");   Modern browsers support the JSON object natively. If you need the script above to work with older browsers then you should download the JSON2.js library from: https://github.com/douglascrockford/JSON-js The JSON2 library will use the native JSON object if a browser already supports JSON. Merging Server Changes with Browser Local Storage When you first open the JavaScript Reference application, the entire database of JavaScript entries is transferred from the server to the browser. Two items are added to local storage: entries and entriesLastUpdated. The first item contains the entire entries database (a big JSON string of entries). The second item, a timestamp, represents the version of the entries. Whenever you open the JavaScript Reference in the future, the entriesLastUpdated timestamp is passed to the server. Only records that have been deleted, updated, or added since entriesLastUpdated are transferred to the browser. The OData query to get the latest updates looks like this: http://superexpert.com/javascriptreference/Services/EntryService.svc/Entries?$filter=(LastUpdated%20gt%20634301199890494792L) If you remove URL encoding, the query looks like this: http://superexpert.com/javascriptreference/Services/EntryService.svc/Entries?$filter=(LastUpdated gt 634301199890494792L) This query returns only those entries where the value of LastUpdated > 634301199890494792 (the version timestamp). The changes – new JavaScript entries, deleted entries, and updated entries – are merged with the existing entries in local storage. The JavaScript code for performing the merge is contained in the EntriesHelper.js file. The merge() method looks like this:   merge: function (oldEntries, newEntries) { // concat (this performs the add) oldEntries = oldEntries || []; var mergedEntries = oldEntries.concat(newEntries); // sort this.sortByIdThenLastUpdated(mergedEntries); // prune duplicates (this performs the update) mergedEntries = this.pruneDuplicates(mergedEntries); // delete mergedEntries = this.removeIsDeleted(mergedEntries); // Sort this.sortByName(mergedEntries); return mergedEntries; },   The contents of local storage are then updated with the merged entries. I spent several hours writing the merge() method (much longer than I expected). I found two resources to be extremely useful. First, I wrote extensive unit tests for the merge() method. I wrote the unit tests using server-side JavaScript. I describe this approach to writing unit tests in this blog entry. The unit tests are included in the JavaScript Reference source code. Second, I found the following blog entry to be super useful (thanks Nick!): http://nicksnettravels.builttoroam.com/post/2010/08/03/OData-Synchronization-with-WCF-Data-Services.aspx One big challenge that I encountered involved timestamps. I originally tried to store an actual UTC time as the value of the entriesLastUpdated item. I quickly discovered that trying to work with dates in JSON turned out to be a big can of worms that I did not want to open. Next, I tried to use a SQL timestamp column. However, I learned that OData cannot handle the timestamp data type when doing a filter query. Therefore, I ended up using a bigint column in SQL and manually creating the value when a record is updated. I overrode the SaveChanges() method to look something like this: public override int SaveChanges(SaveOptions options) { var changes = this.ObjectStateManager.GetObjectStateEntries( EntityState.Modified | EntityState.Added | EntityState.Deleted); foreach (var change in changes) { var entity = change.Entity as IEntityTracking; if (entity != null) { entity.LastUpdated = DateTime.Now.Ticks; } } return base.SaveChanges(options); }   Notice that I assign Date.Now.Ticks to the entity.LastUpdated property whenever an entry is modified, added, or deleted. Summary After building the JavaScript Reference application, I am convinced that HTML5 local storage can have a dramatic impact on the performance of any data-driven web application. If you are building a web application that involves extensive interaction with data then I recommend that you take advantage of this new feature included in the HTML5 standard.

    Read the article

  • Maven2 multi-module ejb 3.1 project - deployment error

    - by gerry
    The problem is taht I get the following error qhile deploying my project to Glassfish: java.lang.RuntimeException: Unable to load EJB module. DeploymentContext does not contain any EJB Check archive to ensure correct packaging But, let us start on how the project structure looks like in Maven2... I've build the following scenario: MultiModuleJavaEEProject - parent module - model --- packaged as jar - ejb1 ---- packaged as ebj - ejb2 ---- packaged as ebj - web ---- packaged as war So model, ejb1, ejb2 and web are children/modules of the parent MultiModuleJavaEEProject. _ejb1 depends on model. _ejb2 depends on ejb1. _web depends on ejb2. the pom's look like: _parent: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.dyndns.geraldhuber.testing</groupId> <artifactId>MultiModuleJavaEEProject</artifactId> <packaging>pom</packaging> <version>1.0</version> <name>MultiModuleJavaEEProject</name> <url>http://maven.apache.org</url> <modules> <module>model</module> <module>ejb1</module> <module>ejb2</module> <module>web</module> </modules> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-ejb-plugin</artifactId> <version>2.2</version> <configuration> <ejbVersion>3.1</ejbVersion> <jarName>${project.groupId}.${project.artifactId}-${project.version}</jarName> </configuration> </plugin> </plugins> </pluginManagement> </build> </project> _model: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>testing</groupId> <artifactId>MultiModuleJavaEEProject</artifactId> <version>1.0</version> </parent> <artifactId>model</artifactId> <packaging>jar</packaging> <version>1.0</version> <name>model</name> <url>http://maven.apache.org</url> </project> _ejb1: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>testing</groupId> <artifactId>MultiModuleJavaEEProject</artifactId> <version>1.0</version> </parent> <artifactId>ejb1</artifactId> <packaging>ejb</packaging> <version>1.0</version> <name>ejb1</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.ejb</artifactId> <version>3.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>testing</groupId> <artifactId>model</artifactId> <version>1.0</version> </dependency> </dependencies> </project> _ejb2: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>testing</groupId> <artifactId>MultiModuleJavaEEProject</artifactId> <version>1.0</version> </parent> <artifactId>ejb2</artifactId> <packaging>ejb</packaging> <version>1.0</version> <name>ejb2</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.ejb</artifactId> <version>3.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>testing</groupId> <artifactId>ejb1</artifactId> <version>1.0</version> </dependency> </dependencies> </project> _web: <?xml version="1.0" encoding="UTF-8"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>MultiModuleJavaEEProject</artifactId> <groupId>testing</groupId> <version>1.0</version> </parent> <groupId>testing</groupId> <artifactId>web</artifactId> <version>1.0</version> <packaging>war</packaging> <name>web Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.4</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.ejb</artifactId> <version>3.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>testing</groupId> <artifactId>ejb2</artifactId> <version>1.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.0</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> </manifest> </archive> </configuration> </plugin> </plugins> <finalName>web</finalName> </build> </project> And the model is just a simple Pojo: package testing.model; public class Data { private String data; public String getData() { return data; } public void setData(String data) { this.data = data; } } And the ejb1 contains only one STATELESS ejb. package testing.ejb1; import javax.ejb.Stateless; import testing.model.Data; @Stateless public class DataService { private Data data; public DataService(){ data = new Data(); data.setData("Hello World!"); } public String getDataText(){ return data.getData(); } } As well as the ejb2 is only a stateless ejb: package testing.ejb2; import javax.ejb.EJB; import javax.ejb.Stateless; import testing.ejb1.DataService; @Stateless public class Service { @EJB DataService service; public Service(){ } public String getText(){ return service.getDataText(); } } And the web module contains only a Servlet: package testing.web; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import testing.ejb2.Service; public class SimpleServlet extends HttpServlet { @EJB Service service; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println( "SimpleServlet Executed" ); out.println( "Text: "+service.getText() ); out.flush(); out.close(); } } And the web.xml file in the web module looks like: <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>simple</servlet-name> <servlet-class>testing.web.SimpleServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>simple</servlet-name> <url-pattern>/simple</url-pattern> </servlet-mapping> </web-app> So no further files are set up by me. There is no ejb-jar.xml in any ejb files, because I'm using EJB 3.1. So I think ejb-jar.xml descriptors are optional. I this right? But the problem is, the already mentioned error: java.lang.RuntimeException: Unable to load EJB module. DeploymentContext does not contain any EJB Check archive to ensure correct packaging Can anybody help?

    Read the article

  • Pre-filtering and shaping OData feeds using WCF Data Services and the Entity Framework - Part 2

    - by rajbk
    In the previous post, you saw how to create an OData feed and pre-filter the data. In this post, we will see how to shape the data. A sample project is attached at the bottom of this post. Pre-filtering and shaping OData feeds using WCF Data Services and the Entity Framework - Part 1 Shaping the feed The Product feed we created earlier returns too much information about our products. Let’s change this so that only the following properties are returned – ProductID, ProductName, QuantityPerUnit, UnitPrice, UnitsInStock. We also want to return only Products that are not discontinued.  Splitting the Entity To shape our data according to the requirements above, we are going to split our Product Entity into two and expose one through the feed. The exposed entity will contain only the properties listed above. We will use the other Entity in our Query Interceptor to pre-filter the data so that discontinued products are not returned. Go to the design surface for the Entity Model and make a copy of the Product entity. A “Product1” Entity gets created.   Rename Product1 to ProductDetail. Right click on the Product entity and select “Add Association” Make a one to one association between Product and ProductDetails.   Keep only the properties we wish to expose on the Product entity and delete all other properties on it (see diagram below). You delete a property on an Entity by right clicking on the property and selecting “delete”. Keep the ProductID on the ProductDetail. Delete any other property on the ProductDetail entity that is already present in the Product entity. Your design surface should look like below:    Mapping Entity to Database Tables Right click on “ProductDetail” and go to “Table Mapping”   Add a mapping to the “Products” table in the Mapping Details.   After mapping ProductDetail, you should see the following.   Add a referential constraint. Lets add a referential constraint which is similar to a referential integrity constraint in SQL. Double click on the Association between the Entities and add the constraint with “Principal” set to “Product”. Let us review what we did so far. We made a copy of the Product entity and called it ProductDetail We created a one to one association between these entities Excluding the ProductID, we made sure properties were not duplicated between these entities  We added a ProductDetail entity to Products table mapping (Entity to Database). We added a referential constraint between the entities. Lets build our project. We get the following error: ”'NortwindODataFeed.Product' does not contain a definition for 'Discontinued' and no extension method 'Discontinued' accepting a first argument of type 'NortwindODataFeed.Product' could be found …" The reason for this error is because our Product Entity no longer has a “Discontinued” property. We “moved” it to the ProductDetail entity since we want our Product Entity to contain only properties that will be exposed by our feed. Since we have a one to one association between the entities, we can easily rewrite our Query Interceptor like so: [QueryInterceptor("Products")] public Expression<Func<Product, bool>> OnReadProducts() { return o => o.ProductDetail.Discontinued == false; } Similarly, all “hidden” properties of the Product table are available to us internally (through the ProductDetail Entity) for any additional logic we wish to implement. Compile the project and view the feed. We see that the feed returns only the properties that were part of the requirement.   To see the data in JSON format, you have to create a request with the following request header Accept: application/json, text/javascript, */* (easy to do in jQuery) The result should look like this: { "d" : { "results": [ { "__metadata": { "uri": "http://localhost.:2576/DataService.svc/Products(1)", "type": "NorthwindModel.Product" }, "ProductID": 1, "ProductName": "Chai", "QuantityPerUnit": "10 boxes x 20 bags", "UnitPrice": "18.0000", "UnitsInStock": 39 }, { "__metadata": { "uri": "http://localhost.:2576/DataService.svc/Products(2)", "type": "NorthwindModel.Product" }, "ProductID": 2, "ProductName": "Chang", "QuantityPerUnit": "24 - 12 oz bottles", "UnitPrice": "19.0000", "UnitsInStock": 17 }, { ... ... If anyone has the $format operation working, please post a comment. It was not working for me at the time of writing this.  We have successfully pre-filtered our data to expose only products that have not been discontinued and shaped our data so that only certain properties of the Entity are exposed. Note that there are several other ways you could implement this like creating a QueryView, Stored Procedure or DefiningQuery. You have seen how easy it is to create an OData feed, shape the data and pre-filter it by hardly writing any code of your own. For more details on OData, Google it with your favorite search engine :-) Also check out the one of the most passionate persons I have ever met, Pablo Castro – the Architect of Aristoria WCF Data Services. Watch his MIX 2010 presentation titled “OData: There's a Feed for That” here. Download Sample Project for VS 2010 RTM NortwindODataFeed.zip

    Read the article

  • Fix: WCF - The type provided as the Service attribute value in the ServiceHost directive could not

    - by Ken Cox [MVP]
    I wanted to expose some raw data to users in my current ASP.NET 3.5 web site project. I created a subdirectory called ‘datafeeds’ and added a WCF Data Service. I wired the dataservice up to the Entity Framework class and, on running the ItemDataService.svc file, was greeted with: The type  <> provided as the Service attribute value in the ServiceHost directive could not be found So why couldn’t it find the class? It was right there in the… oops! Instead of putting the ItemDataService.vb...(read more)

    Read the article

  • subsonic.migrations and Oracle XE

    - by andrecarlucci
    Hello, Probably I'm doing something wrong but here it goes: I'm trying to create a database using subsonic.migrations in an OracleXE version 10.2.0.1.0. I have ODP v 10.2.0.2.20 installed. This is my app.config: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="SubSonicService" type="SubSonic.SubSonicSection, SubSonic" requirePermission="false"/> </configSections> <connectionStrings> <add name="test" connectionString="Data Source=XE; User Id=test; Password=test;"/> </connectionStrings> <SubSonicService defaultProvider="test"> <providers> <clear/> <add name="test" type="SubSonic.OracleDataProvider, SubSonic" connectionStringName="test" generatedNamespace="testdb"/> </providers> </SubSonicService> </configuration> And that's my first migration: public class Migration001_Init : Migration { public override void Up() { //Create the records table TableSchema.Table records = CreateTable("asdf"); records.AddColumn("RecordName"); } public override void Down() { DropTable("asdf"); } } When I run the sonic.exe, I get this exception: Setting ConfigPath: 'App.config' Building configuration from D:\Users\carlucci\Documents\Visual Studio 2008\Projects\Wum\Wum.Migration\App.config Adding connection to test ERROR: Trying to execute migrate Error Message: System.Data.OracleClient.OracleException: ORA-02253: especifica‡Æo de restri‡Æo nÆo permitida aqui at System.Data.OracleClient.OracleConnection.CheckError(OciErrorHandle errorHandle, Int32 rc) at System.Data.OracleClient.OracleCommand.Execute(OciStatementHandle statementHandle, CommandBehavior behavior, Boolean needRowid, OciRowidDescriptor& rowidDescriptor, ArrayList& resultParameterOrdinals) at System.Data.OracleClient.OracleCommand.ExecuteNonQueryInternal(Boolean needRowid, OciRowidDescriptor& rowidDescriptor) at System.Data.OracleClient.OracleCommand.ExecuteNonQuery() at SubSonic.OracleDataProvider.ExecuteQuery(QueryCommand qry) in D:\@SubSonic\SubSonic\SubSonic\DataProviders\OracleDataProvider.cs:line 350 at SubSonic.DataService.ExecuteQuery(QueryCommand cmd) in D:\@SubSonic\SubSonic\SubSonic\DataProviders\DataService.cs:line 544 at SubSonic.Migrations.Migrator.CreateSchemaInfo(String providerName) in D:\@SubSonic\SubSonic\SubSonic.Migrations\Migrator.cs:line 249 at SubSonic.Migrations.Migrator.GetCurrentVersion(String providerName) in D:\@SubSonic\SubSonic\SubSonic.Migrations\Migrator.cs:line 232 at SubSonic.Migrations.Migrator.Migrate(String providerName, String migrationDirectory, Nullable`1 toVersion) in D:\@SubSonic\SubSonic\SubSonic.Migrations\Migrator.cs:line 50 at SubSonic.SubCommander.Program.Migrate() in D:\@SubSonic\SubSonic\SubCommander\Program.cs:line 264 at SubSonic.SubCommander.Program.Main(String[] args) in D:\@SubSonic\SubSonic\SubCommander\Program.cs:line 90 Execution Time: 379ms What am I doing wrong? Thanks a lot for any help :) Andre Carlucci UPDATE: As pointed by Anton, the problem is the subsonic OracleSqlGenerator. It is trying to create the schema table using this sql: CREATE TABLE SubSonicSchemaInfo ( version int NOT NULL CONSTRAINT DF_SubSonicSchemaInfo_version DEFAULT (0) ) Which doesn't work on oracle. The correct sql would be: CREATE TABLE SubSonicSchemaInfo ( version int DEFAULT (0), constraint DF_SubSonicSchemaInfo_version primary key (version) ) The funny thing is that since this is the very first sql executed by subsonic migrations, NOBODY EVER TESTED it on oracle.

    Read the article

  • SubSonic 2.x now supports TVP's - SqlDbType.Structure / DataTables for SQL Server 2008

    - by ElHaix
    For those interested, I have now modified the SubSonic 2.x code to recognize and support DataTable parameter types. You can read more about SQL Server 2008 features here: http://download.microsoft.com/download/4/9/0/4906f81b-eb1a-49c3-bb05-ff3bcbb5d5ae/SQL%20SERVER%202008-RDBMS/T-SQL%20Enhancements%20with%20SQL%20Server%202008%20-%20Praveen%20Srivatsav.pdf What this enhancement will now allow you to do is to create a partial StoredProcedures.cs class, with a method that overrides the stored procedure wrapper method. A bit about good form: My DAL has no direct table access, and my DB only has execute permissions for that user to my sprocs. As such, SubSonic only generates the AllStructs and StoredProcedures classes. The SPROC: ALTER PROCEDURE [dbo].[testInsertToTestTVP] @UserDetails TestTVP READONLY, @Result INT OUT AS BEGIN SET NOCOUNT ON; SET @Result = -1 --SET IDENTITY_INSERT [dbo].[tbl_TestTVP] ON INSERT INTO [dbo].[tbl_TestTVP] ( [GroupInsertID], [FirstName], [LastName] ) SELECT [GroupInsertID], [FirstName], [LastName] FROM @UserDetails IF @@ROWCOUNT > 0 BEGIN SET @Result = 1 SELECT @Result RETURN @Result END --SET IDENTITY_INSERT [dbo].[tbl_TestTVP] OFF END The TVP: CREATE TYPE [dbo].[TestTVP] AS TABLE( [GroupInsertID] [varchar](50) NOT NULL, [FirstName] [varchar](50) NOT NULL, [LastName] [varchar](50) NOT NULL ) GO The the auto gen tool runs, it creates the following erroneous method: /// <summary> /// Creates an object wrapper for the testInsertToTestTVP Procedure /// </summary> public static StoredProcedure TestInsertToTestTVP(string UserDetails, int? Result) { SubSonic.StoredProcedure sp = new SubSonic.StoredProcedure("testInsertToTestTVP", DataService.GetInstance("MyDAL"), "dbo"); sp.Command.AddParameter("@UserDetails", UserDetails, DbType.AnsiString, null, null); sp.Command.AddOutputParameter("@Result", DbType.Int32, 0, 10); return sp; } It sets UserDetails as type string. As it's good form to have two folders for a SubSonic DAL - Custom and Generated, I created a StoredProcedures.cs partial class in Custom that looks like this: /// <summary> /// Creates an object wrapper for the testInsertToTestTVP Procedure /// </summary> public static StoredProcedure TestInsertToTestTVP(DataTable dt, int? Result) { DataSet ds = new DataSet(); SubSonic.StoredProcedure sp = new SubSonic.StoredProcedure("testInsertToTestTVP", DataService.GetInstance("MyDAL"), "dbo"); // TODO: Modify the SubSonic code base in sp.Command.AddParameter to accept // a parameter type of System.Data.SqlDbType.Structured, as it currently only accepts // System.Data.DbType. //sp.Command.AddParameter("@UserDetails", dt, System.Data.SqlDbType.Structured null, null); sp.Command.AddParameter("@UserDetails", dt, SqlDbType.Structured); sp.Command.AddOutputParameter("@Result", DbType.Int32, 0, 10); return sp; } As you can see, the method signature now contains a DataTable, and with my modification to the SubSonic framework, this now works perfectly. I'm wondering if the SubSonic guys can modify the auto-gen to recognize a TVP in a sproc signature, as to avoid having to re-write the warpper? Does SubSonic 3.x support Structured data types? Also, I'm sure many will be interested in using this code, so where can I upload the new code? Thanks.

    Read the article

  • "Error #1006: getAttributeByQName is not a function." Flex 2.0.1 hotfix 2

    - by Deveti Putnik
    Hi, guys! I am working on some old Flex project (Flex 2.0.1 hotfix 2) and I am rookie in Flex programming. So, I wrote code for accessing some ASP.NET web service: <?xml version="1.0" encoding="utf-8"?> [Bindable] public var users:ArrayOfUser; private function buttonClicked():void { mx.controls.Alert.show(dataService.wsdl); dataService.UserGetAll.send();/ } public function dataHandler(event:ResultEvent):void { Alert.show("alo"); var response:ResponseUsers = event.result as ResponseUsers; if (response.responseCode != ResponseCodes.SUCCESS) { mx.controls.Alert.show("Error: " + response.responseCode.toString()); return; } users = response.users; } ]]> <mx:Button label="Click me!" click="buttonClicked()"/> And this is what I get from debugger: WSDL loaded Invoking SOAP operation UserGetAll Encoding SOAP request envelope Encoding SOAP request body 'A97A2DC1-AEDA-C594-45D2-1BA2B0F3B223' producer sending message '10681130-43E7-3DA7-34DD-1BA2B85545E3' 'direct_http_channel' channel sending message: (mx.messaging.messages::SOAPMessage)#0 body = "<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <SOAP-ENV:Body> <tns:UserGetAll xmlns:tns="http://tempuri.org/"/> </SOAP-ENV:Body> </SOAP-ENV:Envelope>" clientId = "DirectHTTPChannel0" contentType = "text/xml; charset=utf-8" destination = "DefaultHTTP" headers = (Object)#1 httpHeaders = (Object)#2 SOAPAction = ""http://tempuri.org/UserGetAll"" messageId = "10681130-43E7-3DA7-34DD-1BA2B85545E3" method = "POST" recordHeaders = false timestamp = 0 timeToLive = 0 url = "http://192.168.0.201:8123/Service.asmx" 'A97A2DC1-AEDA-C594-45D2-1BA2B0F3B223' producer acknowledge of '10681130-43E7-3DA7-34DD-1BA2B85545E3'. Decoding SOAP response Encoded SOAP response <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><UserGetAllResponse xmlns="http://tempuri.org/"><UserGetAllResult><ResponseCode>Success</ResponseCode><Users><User><Id>1</Id><Name>test</Name><Key>testKey</Key><IsActive>true</IsActive><Name>Petar i Sofija</Name><Key>123789</Key><IsActive>true</IsActive></User></Users></UserGetAllResult></UserGetAllResponse></soap:Body></soap:Envelope> Decoding SOAP response envelope Decoding SOAP response body And finally I get this error "Error #1006: getAttributeByQName is not a function.". As you can see, I get correct response from web service, but dataHandler function is never got called. Can anyone please help me out? Thanks, Deveti Putnik

    Read the article

  • Make SubSonic use existing <connectionstring> instead of new data provider

    - by paolodm
    I am adding SubSonic to a legacy application. This application already defines a ConnectionString. Is there a way I can use this connectionstring instead of creating a new Data Provider entry? I know that one solution is programmatically setting this in the code (i.e. SubSonic.DataService.GetInstance("Name").SetDefaultConnectionString("ConnString") ). However, is there a more elegant solution?

    Read the article

  • Using jQuery and OData to Insert a Database Record

    - by Stephen Walther
    In my previous blog entry, I explored two ways of inserting a database record using jQuery. We added a new Movie to the Movie database table by using a generic handler and by using a WCF service. In this blog entry, I want to take a brief look at how you can insert a database record using OData. Introduction to OData The Open Data Protocol (OData) was developed by Microsoft to be an open standard for communicating data across the Internet. Because the protocol is compatible with standards such as REST and JSON, the protocol is particularly well suited for Ajax. OData has undergone several name changes. It was previously referred to as Astoria and ADO.NET Data Services. OData is used by Sharepoint Server 2010, Azure Storage Services, Excel 2010, SQL Server 2008, and project code name “Dallas.” Because OData is being adopted as the public interface of so many important Microsoft technologies, it is a good protocol to learn. You can learn more about OData by visiting the following websites: http://www.odata.org http://msdn.microsoft.com/en-us/data/bb931106.aspx When using the .NET framework, you can easily expose database data through the OData protocol by creating a WCF Data Service. In this blog entry, I will create a WCF Data Service that exposes the Movie database table. Create the Database and Data Model The MoviesDB database is a simple database that contains the following Movies table: You need to create a data model to represent the MoviesDB database. In this blog entry, I use the ADO.NET Entity Framework to create my data model. However, WCF Data Services and OData are not tied to any particular OR/M framework such as the ADO.NET Entity Framework. For details on creating the Entity Framework data model for the MoviesDB database, see the previous blog entry. Create a WCF Data Service You create a new WCF Service by selecting the menu option Project, Add New Item and selecting the WCF Data Service item template (see Figure 1). Name the new WCF Data Service MovieService.svc. Figure 1 – Adding a WCF Data Service Listing 1 contains the default code that you get when you create a new WCF Data Service. There are two things that you need to modify. Listing 1 – New WCF Data Service File using System; using System.Collections.Generic; using System.Data.Services; using System.Data.Services.Common; using System.Linq; using System.ServiceModel.Web; using System.Web; namespace WebApplication1 { public class MovieService : DataService< /* TODO: put your data source class name here */ > { // This method is called only once to initialize service-wide policies. public static void InitializeService(DataServiceConfiguration config) { // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc. // Examples: // config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead); // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } } } First, you need to replace the comment /* TODO: put your data source class name here */ with a class that represents the data that you want to expose from the service. In our case, we need to replace the comment with a reference to the MoviesDBEntities class generated by the Entity Framework. Next, you need to configure the security for the WCF Data Service. By default, you cannot query or modify the movie data. We need to update the Entity Set Access Rule to enable us to insert a new database record. The updated MovieService.svc is contained in Listing 2: Listing 2 – MovieService.svc using System.Data.Services; using System.Data.Services.Common; namespace WebApplication1 { public class MovieService : DataService<MoviesDBEntities> { public static void InitializeService(DataServiceConfiguration config) { config.SetEntitySetAccessRule("Movies", EntitySetRights.AllWrite); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } } } That’s all we have to do. We can now insert a new Movie into the Movies database table by posting a new Movie to the following URL: /MovieService.svc/Movies The request must be a POST request. The Movie must be represented as JSON. Using jQuery with OData The HTML page in Listing 3 illustrates how you can use jQuery to insert a new Movie into the Movies database table using the OData protocol. Listing 3 – Default.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>jQuery OData Insert</title> <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script> <script src="Scripts/json2.js" type="text/javascript"></script> </head> <body> <form> <label>Title:</label> <input id="title" /> <br /> <label>Director:</label> <input id="director" /> </form> <button id="btnAdd">Add Movie</button> <script type="text/javascript"> $("#btnAdd").click(function () { // Convert the form into an object var data = { Title: $("#title").val(), Director: $("#director").val() }; // JSONify the data var data = JSON.stringify(data); // Post it $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "MovieService.svc/Movies", data: data, dataType: "json", success: insertCallback }); }); function insertCallback(result) { // unwrap result var newMovie = result["d"]; // Show primary key alert("Movie added with primary key " + newMovie.Id); } </script> </body> </html> jQuery does not include a JSON serializer. Therefore, we need to include the JSON2 library to serialize the new Movie that we wish to create. The Movie is serialized by calling the JSON.stringify() method: var data = JSON.stringify(data); You can download the JSON2 library from the following website: http://www.json.org/js.html The jQuery ajax() method is called to insert the new Movie. Notice that both the contentType and dataType are set to use JSON. The jQuery ajax() method is used to perform a POST operation against the URL MovieService.svc/Movies. Because the POST payload contains a JSON representation of a new Movie, a new Movie is added to the database table of Movies. When the POST completes successfully, the insertCallback() method is called. The new Movie is passed to this method. The method simply displays the primary key of the new Movie: Summary The OData protocol (and its enabling technology named WCF Data Services) works very nicely with Ajax. By creating a WCF Data Service, you can quickly expose your database data to an Ajax application by taking advantage of open standards such as REST, JSON, and OData. In the next blog entry, I want to take a closer look at how the OData protocol supports different methods of querying data.

    Read the article

  • OData &ndash; The easiest service I can create: now with updates

    - by Jon Dalberg
    The other day I created a simple NastyWord service exposed via OData. It was read-only and used an in-memory backing store for the words. Today I’ll modify it to use a file instead of a list and I’ll accept new nasty words by implementing IUpdatable directly. The first thing to do is enable the service to accept new entries. This is done at configuration time by adding the “WriteAppend” access rule: 1: public class NastyWords : DataService<NastyWordsDataSource> 2: { 3: // This method is called only once to initialize service-wide policies. 4: public static void InitializeService(DataServiceConfiguration config) 5: { 6: config.SetEntitySetAccessRule("*", EntitySetRights.AllRead | EntitySetRights.WriteAppend); 7: config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; 8: } 9: }   Next I placed a file, NastyWords.txt, in the “App_Data” folder and added a few *choice* words to start. This required one simple change to our NastyWordDataSource.cs file: 1: public NastyWordsDataSource() 2: { 3: UpdateFromSource(); 4: } 5:   6: private void UpdateFromSource() 7: { 8: var words = File.ReadAllLines(pathToFile); 9: NastyWords = (from w in words 10: select new NastyWord { Word = w }).AsQueryable(); 11: }   Nothing too shocking here, just reading each line from the NastyWords.txt file and exposing them. Next, I implemented IUpdatable which comes with a boat-load of methods. We don’t need all of them for now since we are only concerned with allowing new values. Here are the methods we must implement, all the others throw a NotImplementedException: 1: public object CreateResource(string containerName, string fullTypeName) 2: { 3: var nastyWord = new NastyWord(); 4: pendingUpdates.Add(nastyWord); 5: return nastyWord; 6: } 7:   8: public object ResolveResource(object resource) 9: { 10: return resource; 11: } 12:   13: public void SaveChanges() 14: { 15: var intersect = (from w in pendingUpdates 16: select w.Word).Intersect(from n in NastyWords 17: select n.Word); 18:   19: if (intersect.Count() > 0) 20: throw new DataServiceException(500, "duplicate entry"); 21:   22: var lines = from w in pendingUpdates 23: select w.Word; 24:   25: File.AppendAllLines(pathToFile, 26: lines, 27: Encoding.UTF8); 28:   29: pendingUpdates.Clear(); 30:   31: UpdateFromSource(); 32: } 33:   34: public void SetValue(object targetResource, string propertyName, object propertyValue) 35: { 36: targetResource.GetType().GetProperty(propertyName).SetValue(targetResource, propertyValue, null); 37: }   I use a simple list to contain the pending updates and only commit them when the “SaveChanges” method is called. Here’s the order these methods are called in our service during an insert: CreateResource – here we just instantiate a new NastyWord and stick a reference to it in our pending updates list. SetValue – this is where the “Word” property of the NastyWord instance is set. SaveChanges – get the list of pending updates, barfing on duplicates, write them to the file and clear our pending list. ResolveResource – the newly created resource will be returned directly here since we aren’t dealing with “handles” to objects but the actual objects themselves. Not too bad, eh? I didn’t find this documented anywhere but a little bit of digging in the OData spec and use of Fiddler made it pretty easy to figure out. Here is some client code which would add a new nasty word: 1: static void Main(string[] args) 2: { 3: var svc = new ServiceReference1.NastyWordsDataSource(new Uri("http://localhost.:60921/NastyWords.svc")); 4: svc.AddToNastyWords(new ServiceReference1.NastyWord() { Word = "shat" }); 5:   6: svc.SaveChanges(); 7: }   Here’s all of the code so far for to implement the service: 1: using System; 2: using System.Collections.Generic; 3: using System.Data.Services; 4: using System.Data.Services.Common; 5: using System.Linq; 6: using System.ServiceModel.Web; 7: using System.Web; 8: using System.IO; 9: using System.Text; 10:   11: namespace ONasty 12: { 13: [DataServiceKey("Word")] 14: public class NastyWord 15: { 16: public string Word { get; set; } 17: } 18:   19: public class NastyWordsDataSource : IUpdatable 20: { 21: private List<NastyWord> pendingUpdates = new List<NastyWord>(); 22: private string pathToFile = @"path to your\App_Data\NastyWords.txt"; 23:   24: public NastyWordsDataSource() 25: { 26: UpdateFromSource(); 27: } 28:   29: private void UpdateFromSource() 30: { 31: var words = File.ReadAllLines(pathToFile); 32: NastyWords = (from w in words 33: select new NastyWord { Word = w }).AsQueryable(); 34: } 35:   36: public IQueryable<NastyWord> NastyWords { get; private set; } 37:   38: public void AddReferenceToCollection(object targetResource, string propertyName, object resourceToBeAdded) 39: { 40: throw new NotImplementedException(); 41: } 42:   43: public void ClearChanges() 44: { 45: pendingUpdates.Clear(); 46: } 47:   48: public object CreateResource(string containerName, string fullTypeName) 49: { 50: var nastyWord = new NastyWord(); 51: pendingUpdates.Add(nastyWord); 52: return nastyWord; 53: } 54:   55: public void DeleteResource(object targetResource) 56: { 57: throw new NotImplementedException(); 58: } 59:   60: public object GetResource(IQueryable query, string fullTypeName) 61: { 62: throw new NotImplementedException(); 63: } 64:   65: public object GetValue(object targetResource, string propertyName) 66: { 67: throw new NotImplementedException(); 68: } 69:   70: public void RemoveReferenceFromCollection(object targetResource, string propertyName, object resourceToBeRemoved) 71: { 72: throw new NotImplementedException(); 73: } 74:   75: public object ResetResource(object resource) 76: { 77: throw new NotImplementedException(); 78: } 79:   80: public object ResolveResource(object resource) 81: { 82: return resource; 83: } 84:   85: public void SaveChanges() 86: { 87: var intersect = (from w in pendingUpdates 88: select w.Word).Intersect(from n in NastyWords 89: select n.Word); 90:   91: if (intersect.Count() > 0) 92: throw new DataServiceException(500, "duplicate entry"); 93:   94: var lines = from w in pendingUpdates 95: select w.Word; 96:   97: File.AppendAllLines(pathToFile, 98: lines, 99: Encoding.UTF8); 100:   101: pendingUpdates.Clear(); 102:   103: UpdateFromSource(); 104: } 105:   106: public void SetReference(object targetResource, string propertyName, object propertyValue) 107: { 108: throw new NotImplementedException(); 109: } 110:   111: public void SetValue(object targetResource, string propertyName, object propertyValue) 112: { 113: targetResource.GetType().GetProperty(propertyName).SetValue(targetResource, propertyValue, null); 114: } 115: } 116:   117: public class NastyWords : DataService<NastyWordsDataSource> 118: { 119: // This method is called only once to initialize service-wide policies. 120: public static void InitializeService(DataServiceConfiguration config) 121: { 122: config.SetEntitySetAccessRule("*", EntitySetRights.AllRead | EntitySetRights.WriteAppend); 123: config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; 124: } 125: } 126: } Next time we’ll allow removing nasty words. Enjoy!

    Read the article

  • C# WCF Server retrieves 'List<T>' with 1 entry, but client doesn't receive it?! Please help Urgentl

    - by Neville
    Hi Everyone, I've been battling and trying to research this issue for over 2 days now with absolutely no luck. I am trying to retrieve a list of clients from the server (server using fluentNHibernate). The client object is as follow: [DataContract] //[KnownType(typeof(System.Collections.Generic.List<ContactPerson>))] //[KnownType(typeof(System.Collections.Generic.List<Address>))] //[KnownType(typeof(System.Collections.Generic.List<BatchRequest>))] //[KnownType(typeof(System.Collections.Generic.List<Discount>))] [KnownType(typeof(EClientType))] [KnownType(typeof(EComType))] public class Client { #region Properties [DataMember] public virtual int ClientID { get; set; } [DataMember] public virtual EClientType ClientType { get; set; } [DataMember] public virtual string RegisterID {get; set;} [DataMember] public virtual string HerdCode { get; set; } [DataMember] public virtual string CompanyName { get; set; } [DataMember] public virtual bool InvoicePerBatch { get; set; } [DataMember] public virtual EComType ResultsComType { get; set; } [DataMember] public virtual EComType InvoiceComType { get; set; } //[DataMember] //public virtual IList<ContactPerson> Contacts { get; set; } //[DataMember] //public virtual IList<Address> Addresses { get; set; } //[DataMember] //public virtual IList<BatchRequest> Batches { get; set; } //[DataMember] //public virtual IList<Discount> Discounts { get; set; } #endregion #region Overrides public override bool Equals(object obj) { var other = obj as Client; if (other == null) return false; return other.GetHashCode() == this.GetHashCode(); } public override int GetHashCode() { return ClientID.GetHashCode() | ClientType.GetHashCode() | RegisterID.GetHashCode() | HerdCode.GetHashCode() | CompanyName.GetHashCode() | InvoicePerBatch.GetHashCode() | ResultsComType.GetHashCode() | InvoiceComType.GetHashCode();// | Contacts.GetHashCode() | //Addresses.GetHashCode() | Batches.GetHashCode() | Discounts.GetHashCode(); } #endregion } As you can see, I have allready tried to remove the sub-lists, though even with this simplified version of the client I still run into the propblem. my fluent mapping is: public class ClientMap : ClassMap<Client> { public ClientMap() { Table("Clients"); Id(p => p.ClientID); Map(p => p.ClientType).CustomType<EClientType>(); ; Map(p => p.RegisterID); Map(p => p.HerdCode); Map(p => p.CompanyName); Map(p => p.InvoicePerBatch); Map(p => p.ResultsComType).CustomType<EComType>(); Map(p => p.InvoiceComType).CustomType<EComType>(); //HasMany<ContactPerson>(p => p.Contacts) // .KeyColumns.Add("ContactPersonID") // .Inverse() // .Cascade.All(); //HasMany<Address>(p => p.Addresses) // .KeyColumns.Add("AddressID") // .Inverse() // .Cascade.All(); //HasMany<BatchRequest>(p => p.Batches) // .KeyColumns.Add("BatchID") // .Inverse() // .Cascade.All(); //HasMany<Discount>(p => p.Discounts) // .KeyColumns.Add("DiscountID") // .Inverse() // .Cascade.All(); } The client method, seen below, connects to the server. The server retrieves the list, and everything looks right in the object, still, when it returns, the client doesn't receive anything (it receive a List object, but with nothing in it. Herewith the calling method: public List<s.Client> GetClientList() { try { s.DataServiceClient svcClient = new s.DataServiceClient(); svcClient.Open(); List<s.Client> clients = new List<s.Client>(); clients = svcClient.GetClientList().ToList<s.Client>(); svcClient.Close(); //when receiving focus from server, the clients object has a count of 0 return clients; } catch (Exception e) { MessageBox.Show(e.Message); } return null; } and the server method: public IList<Client> GetClientList() { var clients = new List<Client>(); try { using (var session = SessionHelper.OpenSession()) { clients = session.Linq<Client>().Where(p => p.ClientID > 0).ToList<Client>(); } } catch (Exception e) { EventLog.WriteEntry("eCOWS.Data", e.Message); } return clients; //returns a list with 1 client in it } the server method interface is: [UseNetDataContractSerializer] [OperationContract] IList<Client> GetClientList(); for final references, here is my client app.config entries: <system.serviceModel> <bindings> <netTcpBinding> <binding name="NetTcpBinding_IDataService" listenBacklog="10" maxConnections="10" transferMode="Buffered" transactionProtocol="OleTransactions" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" receiveTimeout="00:10:00" sendTimeout="00:10:00"> <readerQuotas maxDepth="51200000" maxStringContentLength="51200000" maxArrayLength="51200000" maxBytesPerRead="51200000" maxNameTableCharCount="51200000" /> <security mode="Transport"/> </binding> </netTcpBinding> </bindings> <client> <endpoint address="net.tcp://localhost:9000/eCOWS/DataService" binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IDataService" contract="eCowsDataService.IDataService" name="NetTcpBinding_IDataService" behaviorConfiguration="eCowsEndpointBehavior"> </endpoint> <endpoint address="MEX" binding="mexHttpBinding" contract="IMetadataExchange" /> </client> <behaviors> <endpointBehaviors> <behavior name="eCowsEndpointBehavior"> <dataContractSerializer maxItemsInObjectGraph="2147483647"/> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel> and my server app.config: <system.serviceModel> <bindings> <netTcpBinding> <binding name="netTcpBinding" maxConnections="10" listenBacklog="10" transferMode="Buffered" transactionProtocol="OleTransactions" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" sendTimeout="00:10:00" receiveTimeout="00:10:00"> <readerQuotas maxDepth="51200000" maxStringContentLength="51200000" maxArrayLength="51200000" maxBytesPerRead="51200000" maxNameTableCharCount="51200000" /> <security mode="Transport"/> </binding> </netTcpBinding> </bindings> <services> <service name="eCows.Data.Services.DataService" behaviorConfiguration="eCowsServiceBehavior"> <host> <baseAddresses> <add baseAddress="http://localhost:9001/eCOWS/" /> <add baseAddress="net.tcp://localhost:9000/eCOWS/" /> </baseAddresses> </host> <endpoint address="DataService" binding="netTcpBinding" contract="eCows.Data.Services.IDataService" behaviorConfiguration="eCowsEndpointBehaviour"> </endpoint> <endpoint address="MEX" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <endpointBehaviors> <behavior name="eCowsEndpointBehaviour"> <dataContractSerializer maxItemsInObjectGraph="2147483647" /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="eCowsServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceThrottling maxConcurrentCalls="10" maxConcurrentSessions="10"/> <serviceDebug includeExceptionDetailInFaults="False" /> </behavior> <behavior name="MexBehaviour"> <serviceMetadata /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> I use to run into "socket closed / network or timeout" errors, and the trace showed clearly that on the callback it was looking for a listening endpoint, but couldn't find one. Anyway, after adding the UseNetSerializer that error went away, yet now I'm just not getting anything. Oh PS. if I add all the commented out List items, I still retrieve an entry from the DB, but also still not receive anything on the client. if I remove the [UseNetDataContractSerializer] I get the following error(s) in the svclog : WARNING: Description Faulted System.ServiceModel.Channels.ServerSessionPreambleConnectionReader+ServerFramingDuplexSessionChannel WARNING: Description Faulted System.ServiceModel.Channels.ServiceChannel ERROR: Initializing[eCows.Data.Models.Client#3]-failed to lazily initialize a collection of role: eCows.Data.Models.Client.Addresses, no session or session was closed ... ERROR: Could not find default endpoint element that references contract 'ILogbookManager' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element. If I add a .Not.LazyLoad to the List mapping items, I'm back at not receiving errors, but also not receiving any client information.. Sigh! Please, if anyone can help with this I'd be extremely grateful. I'm probably just missing something small.. but... what is it :) hehe. Thanks in advance! Neville

    Read the article

  • Very Strange behavior in custom dataGrid

    - by Markus
    Hi everybody, I asked this question already in a former post, but nobody could answer this question correctly. So I try to post the problem again, to make sure it's not a bug. I have a dataGrid with a custom itemRenderer. Everytime I tab at least two times on the dataGrid, the cell below the one I taped gets selected. This doesn't happen if I uncomment the code in the method saveBackDataGridContent()! The second problem is that if the Line is shorter than the entered text, a horizontalScrollBar will get active, although I set setStyle("horizontalScrollPolicy", "off");... Who can solve that one? CustomRenderer.mxml: <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize="dataService.send()"> <mx:Script> <![CDATA[ import components.ChoiceRenderer; import mx.rpc.events.ResultEvent; import mx.events.DataGridEvent; private function resultHandler(event:ResultEvent):void { var doc:XML = event.result as XML; testGrid.dataProvider = doc.Records.BackSide; } private function saveBackDataGridContent(event:DataGridEvent):void{ testGrid.dataProvider[event.rowIndex].TextElement = event.currentTarget.itemEditorInstance.text; } ]]> </mx:Script> <mx:HTTPService id="dataService" result="resultHandler(event)" url = "data/example.xml" resultFormat="e4x"/> <mx:DataGrid id="testGrid" editable="true" itemEditEnd="saveBackDataGridContent(event)"> <mx:columns> <mx:DataGridColumn itemRenderer="components.ChoiceRenderer" width="230"/> </mx:columns> </mx:DataGrid> </mx:Application> ChoiceRenderer.as package components { import mx.containers.HBox; import mx.controls.CheckBox; import mx.controls.Label; public class ChoiceRenderer extends HBox { private var correctAnswer:CheckBox; private var choiceLabel:Label; public function ChoiceRenderer() { super(); setStyle("horizontalScrollPolicy", "off"); correctAnswer = new CheckBox; addChild(correctAnswer); choiceLabel = new Label; addChild(choiceLabel); } override public function set data(xmldata:Object):void{ if(xmldata.name() == "BackSide"){ super.data = xmldata.TextElement[0]; choiceLabel.text = xmldata.TextElement[0].toString(); } } } } example.xml <TopContainer> <Records> <BackSide> <TextElement>first</TextElement> </BackSide> <BackSide> <TextElement>second</TextElement> </BackSide> <BackSide> <TextElement>third</TextElement> </BackSide> <BackSide> <TextElement>fourth</TextElement> </BackSide> <BackSide> <TextElement>fifth</TextElement> </BackSide> <BackSide> <TextElement>sixth</TextElement> </BackSide> </Records> Thanks Markus

    Read the article

  • Oracle OpenWorld 2012?????WebLogic Server???3??????

    - by ???02
    ???????2012?9?30???10?4?(????)???4???????????????????????????Oracle OpenWorld 2012???????????????????????WebLogic Server????????????????????????????????????(Fusion Middleware?????????????????????????????)?????(???) ??????????????WebLogic Server?????? ??????Fusion Middleware??????????????????????????????????? ???????????OpenWorld??????WebLogic Server????????????????????????????(HTML5)???Oracle Database??????????3???????????????????????????? OpenWorld 2012?????????CEO????·??????????????·?????Oracle Cloud??????????SaaS?PaaS????IaaS???????????????? ??????????????????/?????????????????????????????????WebLogic Server????????????????????????????????????????·??????????????????????????????Oracle Exalogic Elastic Cloud?????????????????????????????????????????·???????????????????????? ???????????????·??????????·???????????????????????????????????????WebLogic Server?Oracle Enterprise Manager??????????????????????? ?????????????????????????????????·???????????????????????????????????????(???)????????????????????·???????????????????????????? ??????????·????????????????????????????????????????????????????????????????????Java EE????????????????????????·???????Oracle E-Business Suite????????????·???????????????????????????????????????????????????????????????????????? ??????????????????????????????????·????????????????????????????????????????????????????????????????????????????????????? ?WebLogic Server?Oracle Enterprise Manager?????????Exalogic?????????????????????????·????????????????????????????????????????????????????????????????????????????????????????????????????????OpenWorld?????????Exalogic???????????????????????/?????????????????????????????WebLogic Server?????????????????????????????????????(???) ?????????????????OpenWorld 2012???Java???????Oracle Developer Cloud Service???????????????·?????????????????????????·???????·??????????????????????????????·????·????????????????????????????Java??????????????????????????????????????????????????????????????????????????WebLogic Server????????????????? WebSockets?SSE???????Java EE???????? ????????Java??????????Java EE??????????????Java EE 7???????????????????????7???Java EE??????????????????·?????????????????????????????????????????????HTML5???????????????????????? ??????????Java EE??????????????WebLogic Server???????????12.1.2?????Java EE 7??????????Web???????????????????WebSockets???HTTP?????????????Server Sent Events(SSE)????????????????????????????OpenWorld 2012?????????WebSockets?SSE???????????????????????????Web???????????????????????????????????????????????????????????????? ???WebLogic Server?????????2013?????????????????Java EE 7??????????????????????Java?????????????????????????????????????WebLogic Server?????????????????????? ???WebLogic Server?????????????????Oracle TopLink DataService?????????????????????????????XML?JSON??????????????????????Java??????????????·????????????????????????????????????????????????????·????????????????????????? Oracle Database??????????? WebLogic Server???????????·??????????????????1???Oracle Database????????????????OpenWorld 2012?????????Oracle Database????????????????????? WebLogic Server????Oracle Real Application Clusters(RAC)?????????????????????????????????????Active GridLink for RAC??????????????????????????????????????????????????????????·?????????????Oracle RAC?????????????????·??????????????????????????????????????Oracle RAC????????????? OpenWorld 2012?????Active GridLink for RAC???????????????????????????????Application Continuity??????????????? ?????????????·???????????????Oracle RAC?????????????????????????????????????????????????????????????????Application Continuity?????JDBC???????????????????????????Oracle RAC??????????????????????????????????????????Oracle Coherence?????????????????????????????????·????????????????(???) ?????????????????·???????????????Java????????????WebLogic Server???????????????? ????????????????????????????????????????????/???????????????????WebLogic Server?????????????????????????? ??????·???????????????·????????????Java EE?????????????OpenWorld 2012????????WebLogic Server?????????????????????????????????????????????????????????????Java EE??????????????????????WebLogic Server????????????????????????????Java EE?????????????Java EE???????????????????????????(???) ????????·????????????????????????????????????Java EE????WebLogic Server?????????????????????????????????

    Read the article

  • WCF Data Service Exception

    - by Ravi
    Hi, I am working on C#.Net with ADO.NET Dataservice WCF Data Services. I try to update one record to relational table, when I reach context.SetLink() I am getting exception("The context is not currently tracking the entity"). I don't know how to solve this problem. My code is specified below. LogNote dbLogNote =logNote; LogSubSession dbLogSubSession = (from p in context.LogSubSession where p.UID == logNote.SubSessionId select p).First<LogSubSession>() as LogSubSession; context.AddToLogNote(dbLogNote); dbLogNote.LogSubSession = dbLogSubSession; context.SetLink(dbLogNote, "LogSubSession", dbLogSubSession); context.SaveChanges(); Here LogSubSession is a primary table and LogNote is a foreign table. I am updating data into foreign table based on primary key table. Thanks

    Read the article

  • How to perform insert and update with Ado.net dataservices (EF and Inheritance)

    - by Thurein
    Hi, I have an entity model, in which I have a table per type inheritance. There are 3 types, first, Contact, which I defined as abstract in my EF model and the rest are Company and person types which are derived from contact type. Is it possible to perform an insert using ado.net dataservice and asp.net ajax library? I was trying the following client code : dataContext.insertEntity(person, "Contacts"); I was getting this response from server : Error processing request stream. Type information must be specified for types that take part in inheritance. Thanks.

    Read the article

< Previous Page | 1 2 3 4  | Next Page >