Search Results

Search found 228 results on 10 pages for 'datacontract'.

Page 8/10 | < Previous Page | 4 5 6 7 8 9 10  | Next Page >

  • svcutil, WSDL, and the generated interfaces not being sufficient for implementation

    - by chtmd
    I have a WSDL file defining a service that I have to implement in WCF. I had read that I could generate the proxy using svcutil from the WSDL file, and that I could then use the generated interfaces to implement the service. Unfortunately, I can't quite seem to find a way to have the interfaces contain the correct attributes to expose the contracts. All operations have the "OperationContractAttribute" attribute, but it appears as though for the service to be exposed, I require the "OperationContract" for each one. Same thing with "ServiceContractAttribute" and "ServiceContract", and I imagine DataContract, but I haven't gotten that far. I could manually make these changes, but I would much prefer a technique where the existing code could be easily used, or better code could be generated for my uses. Is there some way that this can be done? Thanks. EDIT: Command used: svcutil ObjectManagerService.wsdl /n:*,Sample /o:ObjectManagerServiceProxy.cs /nologo Code sample: public interface ObjectManagerSyncPortType { // CODEGEN: Generating message contract since the operation createObject is neither RPC nor document wrapped. [System.ServiceModel.OperationContractAttribute(Action="http://www.sample.com/createObject", ReplyAction="*")] [System.ServiceModel.XmlSerializerFormatAttribute()] Sample.createObjectResponse1 createObject(Sample.createObjectRequest1 request); As best as I can tell/see the WSDL file is entirely self-contained and requires no additional XSD files.

    Read the article

  • How can I return json from my WCF rest service (.NET 4), using Json.Net, without it being a string,

    - by Samuel Meacham
    The DataContractJsonSerializer is unable to handle many scenarios that Json.Net handles just fine when properly configured (specifically, cycles). A service method can either return a specific object type (in this case a DTO), in which case the DataContractJsonSerializer will be used, or I can have the method return a string, and do the serialization myself with Json.Net. The problem is that when I return a json string as opposed to an object, the json that is sent to the client is wrapped in quotes. Using DataContractJsonSerializer, returning a specific object type, the response is: {"Message":"Hello World"} Using Json.Net to return a json string, the response is: "{\"Message\":\"Hello World\"}" I do not want to have to eval() or JSON.parse() the result on the client, which is what I would have to do if the json comes back as a string, wrapped in quotes. I realize that the behavior is correct; it's just not what I want/need. I need the raw json; the behavior when the service method's return type is an object, not a string. So, how can I have my method return an object type, but not use the DataContractJsonSerializer? How can I tell it to use the Json.Net serializer instead? Or, is there someway to directly write to the response stream? So I can just return the raw json myself? Without the wrapping quotes? Here is my contrived example, for reference: [DataContract] public class SimpleMessage { [DataMember] public string Message { get; set; } } [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] public class PersonService { // uses DataContractJsonSerializer // returns {"Message":"Hello World"} [WebGet(UriTemplate = "helloObject")] public SimpleMessage SayHelloObject() { return new SimpleMessage("Hello World"); } // uses Json.Net serialization, to return a json string // returns "{\"Message\":\"Hello World\"}" [WebGet(UriTemplate = "helloString")] public string SayHelloString() { SimpleMessage message = new SimpleMessage() { Message = "Hello World" }; string json = JsonConvert.Serialize(message); return json; } // I need a mix of the two. Return an object type, but use the Json.Net serializer. }

    Read the article

  • MS AJAX Library 4.0 Sys.create.dataView

    - by azamsharp
    One again Microsoft poor documentation has left me confused. I am trying to use the new features of the .NET 4.0 framework. I am using the following code to populate the Title and Director but it keeps getting blank. <script language="javascript" type="text/javascript"> Sys.require([Sys.components.dataView, Sys.components.dataContext,Sys.scripts.WebServices], function () { Sys.create.dataView("#moviesView", { dataProvider: "MovieService.svc", fetchOperation: "GetMovies", autoFetch: true }); }); </script> And here it the HTML code: <ul id="moviesView"> <li> {{Title}} - {{Director}} </li> </ul> IS THIS THE LATEST URL TO Start.js file. Here is the Ajax-Enabled WCF Service: [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class MovieService { [OperationContract] public Movie GetMovies() { return new Movie() { Title = "SS", Director = "SSSSS" }; } } [DataContract] public class Movie { [DataMember] public string Title { get; set; } [DataMember] public string Director { get; set; } }

    Read the article

  • XmlSerializer equivalent of IExtensibleDataObject

    - by demoncodemonkey
    With DataContracts you can derive from IExtensibleDataObject to allow round-tripping to work without losing any unknown additional data from your XML file. I can't use DataContract because I need to control the formatting of the output XML. But I also need to be able to read a future version of the XML file in the old version of the app, without losing any of the data from the XML file. e.g. XML v1: <Person> <Name>Fred</Name> </Person> XML v2: <Person> <Name>Fred</Name> <Age>42</Age> </Person> If reading an XML v2 file from v1 of my app, deserializing and serializing it again turns it into an XML v1 file. i.e. the "Age" field is erased. Is there anything similar to IExtensibleDataObject that I can use with XmlSerializer to avoid the Age field disappearing?

    Read the article

  • xsd.exe - schema to class - for use with WCF

    - by NealWalters
    I have created a schema as an agreed upon interface between our company and an external company. I am now creating a WCF C# web service to handle the interface. I ran the XSD utility and it created a C# class. The schema was built in BizTalk, and references other schemas, so all-in-all there are over 15 classes being generated. I put [DataContract} attribute in front of each of the classes. Do I have to put the [DataMember] attribute on every single property? When I generate a test client program, the proxy does not have any code for any of these 15 classes. We used to use this technique when using .asmx services, but not sure if it will work the same with WCF. If we change the schema, we would want to regenerate the WCF class, and then we would haev to each time redecorate it with all the [DataMember] attributes? Is there an newer tool similar to XSD.exe that will work better with WCF? Thanks, Neal Walters SOLUTION (buried in one of Saunders answer/comments): Add the XmlSerializerFormat to the Interface definition: [OperationContract] [XmlSerializerFormat] // ADD THIS LINE Transaction SubmitTransaction(Transaction transactionIn); Two notes: 1) After I did this, I saw a lot more .xsds in the my proxy (Service Reference) test client program, but I didn't see the new classes in my intellisense. 2) For some reason, until I did a build on the project, I didn't get all the classes in the intellisense (not sure why).

    Read the article

  • Should business objects be able to create their own DTOs?

    - by Sam
    Suppose I have the following class: class Camera { public Camera( double exposure, double brightness, double contrast, RegionOfInterest regionOfInterest) { this.exposure = exposure; this.brightness = brightness; this.contrast = contrast; this.regionOfInterest = regionOfInterest; } public void ConfigureAcquisitionFifo(IAcquisitionFifo acquisitionFifo) { // do stuff to the acquisition FIFO } readonly double exposure; readonly double brightness; readonly double contrast; readonly RegionOfInterest regionOfInterest; } ... and a DTO to transport the camera info across a service boundary (WCF), say, for viewing in a WinForms/WPF/Web app: using System.Runtime.Serialization; [DataContract] public class CameraData { [DataMember] public double Exposure { get; set; } [DataMember] public double Brightness { get; set; } [DataMember] public double Contrast { get; set; } [DataMember] public RegionOfInterestData RegionOfInterest { get; set; } } Now I can add a method to Camera to expose its data: class Camera { // blah blah public CameraData ToData() { var regionOfInterestData = regionOfInterest.ToData(); return new CameraData() { Exposure = exposure, Brightness = brightness, Contrast = contrast, RegionOfInterestData = regionOfInterestData }; } } or, I can create a method that requires a special IReporter to be passed in for the Camera to expose its data to. This removes the dependency on the Contracts layer (Camera no longer has to know about CameraData): class Camera { // beep beep I'm a jeep public void ExposeToReporter(IReporter reporter) { reporter.GetCameraInfo(exposure, brightness, contrast, regionOfInterest); } } So which should I do? I prefer the second, but it requires the IReporter to have a CameraData field (which gets changed by GetCameraInfo()), which feels weird. Also, if there is any even better solution, please share with me! I'm still an object-oriented newb.

    Read the article

  • How to pass multiple parameter in DomainService - WCF

    - by S.Amani
    Hi, Let's say I have a window which should submit 3 model in client side (Silverlight Client Application). My problem is each time I submit the form, data on the server side which I passed them from client are empty. I've used nested class which contains my models, instead of passing multiple object as parameter, but it didn't work again. My Personnel Data Transfer Object Code is something like this : [DataContract] public class PersonnelDTO : EntityObject { [Key] [DataMember] public int PersonnelId { get; set; } [Include] [DataMember] [Association("Personnel_ID", "PersonnelId", "Personnel_ID")] public Personnel Personnel { get; set; } [Include] [DataMember] [Association("Personnel_Info_ID", "PersonnelId", "Personnel_Info_ID")] public Personnel_Info PersonnelInfo { get; set; } } I fill up this model to pass data from client to server (DomainService). and also my domain service code is : [Invoke] public void AddPersonnel(PersonnelDTO personnelDTO) { // Model are EMPTY in DTO ObjectContext.AddToPersonnels(personnelDTO.Personnel); ObjectContext.AddToPersonnel_Info(personnelDTO.PersonnelInfo); ObjectContext.SaveChanges(); } I don't know if there is a way to pass multiple parameter in WCF Service method include Generic List. Any advice will be graceful. Thanks.

    Read the article

  • WCF object parameter loses values

    - by Josh
    I'm passing an object to a WCF service and wasn't getting anything back. I checked the variable as it gets passed to the method that actually does the work and noticed that none of the values are set on the object at that point. Here's the object: [DataContract] public class Section { [DataMember] public long SectionID { get; set; } [DataMember] public string Title { get; set; } [DataMember] public string Text { get; set; } [DataMember] public int Order { get; set; } } Here's the service code for the method: [OperationContract] public List<Section> LoadAllSections(Section s) { return SectionRepository.Instance().LoadAll(s); } The code that actually calls this method is this and is located in a Silverlight XAML file: SectionServiceClient proxy = new SectionServiceClient(); proxy.LoadAllSectionsCompleted += new EventHandler<LoadAllSectionsCompletedEventArgs>(proxy_LoadAllSectionsCompleted); Section s = new Section(); s.SectionID = 4; proxy.LoadAllSectionsAsync(s); When the code finally gets into the method LoadAllSections(Section s), the parameter's SectionID is not set. I stepped through the code and when it goes into the generated code that returns an IAsyncResult object, the object's properties are set. But when it actually calls the method, LoadAllSections, the parameter received is completely blank. Is there something I have to set to make the proeprty stick between method calls?

    Read the article

  • My First F# program

    - by sudaly
    Hi I just finish writing my first F# program. Functionality wise the code works the way I wanted, but not sure if the code is efficient. I would much appreciate if someone could review the code for me and point out the areas where the code can be improved. Thanks Sudaly open System open System.IO open System.IO.Pipes open System.Text open System.Collections.Generic open System.Runtime.Serialization [<DataContract>] type Quote = { [<field: DataMember(Name="securityIdentifier") >] RicCode:string [<field: DataMember(Name="madeOn") >] MadeOn:DateTime [<field: DataMember(Name="closePrice") >] Price:float } let m_cache = new Dictionary<string, Quote>() let ParseQuoteString (quoteString:string) = let data = Encoding.Unicode.GetBytes(quoteString) let stream = new MemoryStream() stream.Write(data, 0, data.Length); stream.Position <- 0L let ser = Json.DataContractJsonSerializer(typeof<Quote array>) let results:Quote array = ser.ReadObject(stream) :?> Quote array results let RefreshCache quoteList = m_cache.Clear() quoteList |> Array.iter(fun result->m_cache.Add(result.RicCode, result)) let EstablishConnection() = let pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4) let mutable sr = null printfn "[F#] NamedPipeServerStream thread created, Wait for a client to connect" pipeServer.WaitForConnection() printfn "[F#] Client connected." try // Stream for the request. sr <- new StreamReader(pipeServer) with | _ as e -> printfn "[F#]ERROR: %s" e.Message sr while true do let sr = EstablishConnection() // Read request from the stream. printfn "[F#] Ready to Receive data" sr.ReadLine() |> ParseQuoteString |> RefreshCache printfn "[F#]Quot Size, %d" m_cache.Count let quot = m_cache.["MSFT.OQ"] printfn "[F#]RIC: %s" quot.RicCode printfn "[F#]MadeOn: %s" (String.Format("{0:T}",quot.MadeOn)) printfn "[F#]Price: %f" quot.Price

    Read the article

  • IComparable not included when serializing in WCF

    - by djerry
    Hey guys, I have a list i'm filling at server side. It's a list of "User", which implements IComparable. Now when WCF is serializing the data, i guess it's not including the CompareTo method. This is my Object class : [DataContract] public class User : IComparable { private string e164, cn, h323; private int id; private DateTime lastActive; [DataMember] public DateTime LastActive { get { return lastActive; } set { laatstActief = value; } } [DataMember] public int Id { get { return id; } set { id = value; } } [DataMember] public string H323 { get { return h323; } set { h323 = value; } } [DataMember] public string Cn { get { return cn; } set { cn = value; } } [DataMember] public string E164 { get { return e164; } set { e164 = value; } } public User() { } public User(string e164, string cn, string h323, DateTime lastActive) { this.E164 = e164; this.Cn = cn; this.H323 = h323; this.LastActive= lastActive; } [DataMember] public string ToStringExtra { get { if (h323 != "/" && h323 != "") return h323 + " (" + e164 + ")"; return e164; } set { ;} } public override string ToString() { if (Cn.Equals("Trunk Line") || Cn.Equals("")) if (h323.Equals("")) return E164; else return h323; return Cn; } public int CompareTo(object obj) { User user = (User)obj; return user.LastActive.CompareTo(this.LastActive); } } Is it possible to get the CompareTo method to reach the client? Putting [DataMember] isn't the solution as i tried it ( i know...). Thanks in advance.

    Read the article

  • Why won't VS2010 RC use my existing types when I add a service reference?

    - by Johan Driessen
    I have a huge problem getting services references in VS2010 RC to use existing assemblies. Even though I have a class library with all the data contracts (classes marked with DataContract and properties with DataMember) that is shared between the service project and the consuming project (which is a class library), when I add a service reference, the data contracts are regenerated withing the service reference instead of using the existing types. When I was using VS2010 beta 2, this worked fine, and I have existing service references using the very same data contracts. But if I add a new service reference, or even update an old one, it won't use the existing types anymore. I have made a mini-test-solution, with one service, one data contract type and one console app as a consumer (all in the same solution), and there it seems to work, but that's no great comfort to me. Is there any way to see why it can't use the existing types? Edit to clearify. It works to generate the proxy classes with svcutil.exe, and point to the data contracts dll, like this: svcutil.exe http://localhost/MyService.svc /reference:[Path To DataContracts]\DataContracts.dll /n:*,MyProject.MyServiceReference /ct:System.Collections.Generic.List`1 The question is, what possible reason could there be for Visual Studio to generate its own datacontracts instead of using the existing ones even though the "reuse" checkbox is checked and the datacontracts assembly is referenced.

    Read the article

  • Serializing Exceptions WCF + Silverlight

    - by Bram
    I have a WCF service I use to submit bugs for my project. Snippet of the data class: Private _exception As Exception <DataMember()> _ Public Property Exception As Exception Get Return _exception End Get Set(ByVal value As Exception) _exception = value End Set End Property I have a Silverlight app that uses the WCF service to send any bugs home if and when they occur. This is the error I'm testing with: Dim i As Integer = 5 i = i / 0 The problem is SL is banging on with this message: System.ServiceModel.CommunicationException was unhandled by user code Message=There was an error while trying to serialize parameter :bug. The InnerException message was 'Type 'System.OverflowException' with data contract name 'OverflowException:http://schemas.datacontract.org/2004/07/System' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details. Is there some trick to get a generic .NET Exception (any InnerException) to serialize properly? I'm not doing anything funky with the exception - it's just a plain 'ol exception Thanks for any help.

    Read the article

  • JSON Twitter List in C#.net

    - by James
    Hi, My code is below. I am not able to extract the 'name' and 'query' lists from the JSON via a DataContracted Class (below) I have spent a long time trying to work this one out, and could really do with some help... My Json string: {"as_of":1266853488,"trends":{"2010-02-22 15:44:48":[{"name":"#nowplaying","query":"#nowplaying"},{"name":"#musicmonday","query":"#musicmonday"},{"name":"#WeGoTogetherLike","query":"#WeGoTogetherLike"},{"name":"#imcurious","query":"#imcurious"},{"name":"#mm","query":"#mm"},{"name":"#HumanoidCityTour","query":"#HumanoidCityTour"},{"name":"#awesomeindianthings","query":"#awesomeindianthings"},{"name":"#officeformac","query":"#officeformac"},{"name":"Justin Bieber","query":"\"Justin Bieber\""},{"name":"National Margarita","query":"\"National Margarita\""}]}} My code: WebClient wc = new WebClient(); wc.Credentials = new NetworkCredential(this.Auth.UserName, this.Auth.Password); string res = wc.DownloadString(new Uri(link)); //the download string gives me the above JSON string - no problems Trends trends = new Trends(); Trends obj = Deserialise<Trends>(res); private T Deserialise<T>(string json) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json))) { DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType()); obj = (T)serialiser.ReadObject(ms); ms.Close(); return obj; } } [DataContract] public class Trends { [DataMember(Name = "as_of")] public string AsOf { get; set; } //The As_OF value is returned - But how do I get the //multidimensional array of Names and Queries from the JSON here? }

    Read the article

  • Is my objective possible using WCF (and is it the right way to do things?)

    - by David
    I'm writing some software that modifies a Windows Server's configuration (things like MS-DNS, IIS, parts of the filesystem). My design has a server process that builds an in-memory object graph of the server configuration state and a client which requests this object graph. The server would then serialize the graph, send it to the client (presumably using WCF), the server then makes changes to this graph and sends it back to the server. The server receives the graph and proceeds to make modifications to the server. However I've learned that object-graph serialisation in WCF isn't as simple as I first thought. My objects have a hierarchy and many have parametrised-constructors and immutable properties/fields. There are also numerous collections, arrays, and dictionaries. My understanding of WCF serialisation is that it requires use of either the XmlSerializer or DataContractSerializer, but DCS places restrictions on the design of my object-graph (immutable data seems right-out, it also requires parameter-less constructors). I understand XmlSerializer lets me use my own classes provided they implement ISerializable and have the de-serializer constructor. That is fine by me. I spoke to a friend of mine about this, and he advocates going for a Data Transport Object-only route, where I'd have to maintain a separate DataContract object-graph for the transport of data and re-implement my server objects on the client. Another friend of mine said that because my service only has two operations ("GetServerConfiguration" and "PutServerConfiguration") it might be worthwhile just skipping WCF entirely and implementing my own server that uses Sockets. So my questions are: Has anyone faced a similar problem before and if so, are there better approaches? Is it wise to send an entire object graph to the client for processing? Should I instead break it down so that the client requests a part of the object graph as it needs it and sends only bits that have changed (thus reducing concurrency-related risks?)? If sending the object-graph down is the right way, is WCF the right tool? And if WCF is right, what's the best way to get WCF to serialise my object graph?

    Read the article

  • WCF Custom SOAP Header Issues

    - by WayneC
    I'm trying to implement an endpoint behavior which injects a custom SOAP header into all messages to and from a service. I've gotten pretty close by implementing the approach from the accepted answer of this question: http://stackoverflow.com/questions/986455/wcf-wsdl-soap-header-on-all-operations/995951#995951 After implementing that solution, my custom SOAP header does indeed show up in the WSDL; however, when I try to call the methods on my service, I get the following exception/fault: <ExceptionDetail xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <HelpLink i:nil="true" /> <InnerException i:nil="true" /> <Message>Index was outside the bounds of the array.</Message> <StackTrace> at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.AddHeadersToMessage(Message message, MessageDescription messageDescription, Object[] parameters, Boolean isRequest) at System.ServiceModel.Dispatcher.OperationFormatter.SerializeReply(MessageVersion messageVersion, Object[] parameters, Object result) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.SerializeOutputs(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace> <Type>System.IndexOutOfRangeException</Type> </ExceptionDetail> Looking in Reflector at the DataContractSerializerOperationFormatter.AddHeadersToMessage method thats throwing the exception, leads me to believe that the following snippet is causing the problem...but I'm not sure why. MessageHeaderDescription description = (MessageHeaderDescription) headerPart.Description; object parameterValue = parameters[description.Index]; I think the last line above is throwing the exception. The parameters variable is from IDispatchFormatter.SerializeReply What's going on?!?!! Any help would be greatly appreciated...

    Read the article

  • Can't get KnownType to work with WCF

    - by Kelly Cline
    I have an interface and a class defined in separate assemblies, like this: namespace DataInterfaces { public interface IPerson { string Name { get; set; } } } namespace DataObjects { [DataContract] [KnownType( typeof( IPerson ) ) ] public class Person : IPerson { [DataMember] public string Name { get; set; } } } This is my Service Interface: public interface ICalculator { [OperationContract] IPerson GetPerson ( ); } When I update my Service Reference for my Client, I get this in the Reference.cs: public object GetPerson() { return base.Channel.GetPerson(); I was hoping that KnownType would give me IPerson instead of "object" here. I have also tried [KnownType( typeof( Person ) ) ] with the same result. I have control of both client and server, so I have my DataObjects (where Person is defined) and DataInterfaces (where IPerson is defined) assemblies in both places. Is there something obvious I am missing? I thought KnownType was the answer to being able to use interfaces with WCF. ----- FURTHER INFORMATION ----- I removed the KnownType from the Person class and added [ServiceKnownType( typeof( Person ) ) ] to my service interface, as suggested by Richard. The client-side proxy still looks the same, public object GetPerson() { return base.Channel.GetPerson(); , but now it doesn't blow up. The client just has an "object", though, so it has to cast it to IPerson before it is useful. var person = client.GetPerson ( ); Console.WriteLine ( ( ( IPerson ) person ).Name );

    Read the article

  • How to specify allowed exceptions in WCF's configuration file?

    - by tucaz
    Hello! I´m building a set of WCF services for internal use through all our applications. For exception handling I created a default fault class so I can return treated message to the caller if its the case or a generic one when I have no clue what happened. Fault contract: [DataContract(Name = "DefaultFault", Namespace = "http://fnac.com.br/api/2010/03")] public class DefaultFault { public DefaultFault(DefaultFaultItem[] items) { if (items == null || items.Length== 0) { throw new ArgumentNullException("items"); } StringBuilder sbItems = new StringBuilder(); for (int i = 0; i Specifying that my method can throw this exception so the consuming client will be aware of it: [OperationContract(Name = "PlaceOrder")] [FaultContract(typeof(DefaultFault))] [WebInvoke(UriTemplate = "/orders", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "POST")] string PlaceOrder(Order newOrder); Most of time we will use just .NET to .NET communication with usual binds and everything works fine since we are talking the same language. However, as you can see in the service contract declaration I have a WebInvoke attribute (and a webHttp binding) in order to be able to also talk JSON since one of our apps will be built for iPhone and this guy will talk JSON. My problem is that whenever I throw a FaultException and have includeExceptionDetails="false" in the config file the calling client will get a generic HTTP error instead of my custom message. I understand that this is the correct behavior when includeExceptionDetails is turned off, but I think I saw some configuration a long time ago to allow some exceptions/faults to pass through the service boundaries. Is there such thing like this? If not, what do u suggest for my case? Thanks a LOT!

    Read the article

  • Class with property referenced with dll not serializing

    - by djerry
    Hey guys, I got this class TapiCall. It has 4 properties : 2 datetimes, 1 string and an object. The object is a class that's referenced by Atapi3.dll, so i cannot alter it. My class TapiCall looks like this : [DataContract] public class TapiCall { private DateTime start, end; private TCall call; private string status; [DataMember] public string Status { get { return status; } set { status = value; } } [DataMember] public TCall Call { get { return call; } set { call = value; } } [DataMember] public DateTime End { get { return end; } set { end = value; } } [DataMember] public DateTime Start { get { return start; } set { start = value; } } public TapiCall() { } public TapiCall(DateTime start, DateTime end, TCall call) { this.Start = start; this.End = end; this.Call = call; } } Now when i use my visual studio command line, to generate my proxy class, it generates an error. When i remove TapiCall from the method in my app, i can rebuild my proxy again, so i know [OperationContract] void StuurUpdatedCall(TapiCall tpCall); is causing the problem. My question now is can i Serialize a class that's referenced by a dll? Thanks in advance.

    Read the article

  • WCF - Return object without serializing?

    - by Mayo
    One of my WCF functions returns an object that has a member variable of a type from another library that is beyond my control. I cannot decorate that library's classes. In fact, I cannot even use DataContractSurrogate because the library's classes have private member variables that are essential to operation (i.e. if I return the object without those private member variables, the public properties throw exceptions). If I say that interoperability for this particular method is not needed (at least until the owners of this library can revise to make their objects serializable), is it possible for me to use WCF to return this object such that it can at least be consumed by a .NET client? How do I go about doing that? Update: I am adding pseudo code below... // My code, I have control [DataContract] public class MyObject { private TheirObject theirObject; [DataMember] public int SomeNumber { get { return theirObject.SomeNumber; } // public property exposed private set { } } } // Their code, I have no control public class TheirObject { private TheirOtherObject theirOtherObject; public int SomeNumber { get { return theirOtherObject.SomeOtherProperty; } set { // ... } } } I've tried adding DataMember to my instance of their object, making it public, using a DataContractSurrogate, and even manually streaming the object. In all cases, I get some error that eventually leads back to their object not being explicitly serializable.

    Read the article

  • Strange response from WCF service, how to return json easily

    - by Exitos
    I want to get a service to respond with just JSON. I have written the following code: namespace BM.Security { [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class AssocFileService { [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json)] public List<Person> GetPeople(int message) { List<Person> myList = new List<Person>(); Person p = new Person() { Age = 28, Name="Name1" }; Person p2 = new Person() { Age = 26, Name = "Name2" }; myList.Add(p); myList.Add(p2); return myList; } } [DataContract] public class Person { [DataMember] public string Name { get; set; } [DataMember] public int Age { get; set; } } } But im getting the following JSON back which is really wierd... { "d" : [ { "Age" : 28, "Name" : "Name1", "__type" : "Person:#Bm.Security" }, { "Age" : 26, "Name" : "Name2", "__type" : "Person:#BM.Security" } ] } I'm totally stumped by the "d" no idea where that has come from. And also by the __type variable, no thanks don't really want that in my Json :-( How do I set the root node in my data to replace that d? Where did the d come from? So many questions... Hope someone can help....

    Read the article

  • WCF client side List<> problem

    - by MrKanin
    Hey there.. i got a WCF service with a method (GetUserSoftware)to send a List to a client. the software i have difined like this: [DataContract] public class Software { public string SoftwareID { get; set; } public string SoftwareName { get; set; } public string DownloadPath { get; set; } public int PackageID { get; set; } } the method is going through my db to get all software availeble to the clien, and generates a list of that to send back to the client. problem is i on the client side the list is turned into an array. and every item in that array dont contain any of my software attributs. i have debugged my way through the server side. and seen that the list its about to send is correct. with the expected software and attributs in it. any one know how to work around this or know what i can do ?

    Read the article

  • JQuery + WCF + HTTP 404 Error

    - by hangar18
    HI All, I've searched high and low and finally decided to post a query here. I'm writing a very basic HTML page from which I'm trying to call a WCF service using jQuery and parse it using JSON. Service: IMyDemo.cs [ServiceContract] public interface IMyDemo { [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)] Employee DoWork(); [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)] Employee GetEmp(int age, string name); } [DataContract] public class Employee { [DataMember] public int EmpId { get; set; } [DataMember] public string EmpName { get; set; } [DataMember] public int EmpSalary { get; set; } } MyDemo.svc.cs public Employee DoWork() { // Add your operation implementation here Employee obj = new Employee() { EmpSalary = 12, EmpName = "SomeName" }; return obj; } public Employee GetEmp(int age, string name) { Employee emp = new Employee(); if (age > 0) emp.EmpSalary = 12 + age; if (!string.IsNullOrEmpty(name)) emp.EmpName = "Server" + name; return emp; } WEb.Config <system.serviceModel> <services> <service behaviorConfiguration="EmployeesBehavior" name="MySample.MyDemo"> <endpoint address="" binding="webHttpBinding" contract="MySample.IMyDemo" behaviorConfiguration="EmployeesBehavior"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="EmployeesBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="EmployeesBehavior"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel> MyDemo.htm <head> <title></title> <script type="text/javascript" language="javascript" src="Scripts/jquery-1.4.1.js"></script> <script type="text/javascript" language="javascript" src="Scripts/json.js"></script> <script type="text/javascript"> //create a global javascript object for the AJAX defaults. debugger; var ajaxDefaults = {}; ajaxDefaults.base = { type: "POST", timeout : 1000, dataFilter: function (data) { //see http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/ data = JSON.parse(data); //use the JSON2 library if you aren’t using FF3+, IE8, Safari 3/Google Chrome return data.hasOwnProperty("d") ? data.d : data; }, error: function (xhr) { //see if (!xhr) return; if (xhr.responseText) { var response = JSON.parse(xhr.responseText); //console.log works in FF + Firebug only, replace this code if (response) alert(response); else alert("Unknown server error"); } } }; ajaxDefaults.json = $.extend(ajaxDefaults.base, { //see http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/ contentType: "application/json; charset=utf-8", dataType: "json" }); var ops = { baseUrl: "/MyService/MySample/MyDemo.svc/", doWork: function () { //see http://api.jquery.com/jQuery.extend/ var ajaxOptions = $.extend(ajaxDefaults.json, { url: ops.baseUrl + "DoWork", data: "{}", success: function (msg) { console.log("success"); console.log(typeof msg); if (typeof msg !== "undefined") { console.log(msg); } } }); $.ajax(ajaxOptions); return false; }, getEmp: function () { var ajaxOpts = $.extend(ajaxDefaults.json, { url: ops.baseUrl + "GetEmp", data: JSON.stringify({ age: 12, name: "NameName" }), success: function (msg) { $("span#lbl").html("age: " + msg.Age + "name:" + msg.Name); } }); $.ajax(ajaxOpts); return false; } } </script> </head> <body> <span id="lbl">abc</span> <br /><br /> <input type="button" value="GetEmployee" id="btnGetEmployee" onclick="javascript:ops.getEmp();" /> </body> I'm just not able to get this running. When I debug, I see the error being returned from the call is " Server Error in '/jQuerySample' Application. <h2> <i>HTTP Error 404 - Not Found.</i> </h2></span> " Looks like I'm missing something basic here. My sample is based on this I've been trying to fix the code for sometime now so I'd like you to take a look and see if you can figure out what is it that I'm doing wrong here. I'm able to see that the service is created when I browse the service in IE. I've also tried changing the setting as mentioned here Appreciate your help. I'm gonna blog about this as soon as the issue is resolved for the benefit of other devs Thanks -Soni

    Read the article

  • Moving DataSets through BizTalk

    - by EltonStoneman
    [Source: http://geekswithblogs.net/EltonStoneman] Yuck. But sometimes you have to, so here are a couple of things to bear in mind: Schemas Point a codegen tool at a WCF endpoint which exposes a DataSet and it will generate an XSD which describes the DataSet like this: <xs:elementminOccurs="0"name="GetDataSetResult"nillable="true">  <xs:complexType>     <xs:annotation>       <xs:appinfo>         <ActualTypeName="DataSet"                     Namespace="http://schemas.datacontract.org/2004/07/System.Data"                     xmlns="http://schemas.microsoft.com/2003/10/Serialization/" />       </xs:appinfo>     </xs:annotation>     <xs:sequence>       <xs:elementref="xs:schema" />       <xs:any />     </xs:sequence>  </xs:complexType> </xs:element>  In a serialized instance, the element of type xs:schema contains a full schema which describes the structure of the DataSet – tables, columns etc. The second element, of type xs:any, contains the actual content of the DataSet, expressed as DiffGrams: <GetDataSetResult>  <xs:schemaid="NewDataSet"xmlns:xs="http://www.w3.org/2001/XMLSchema"xmlns=""xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">     <xs:elementname="NewDataSet"msdata:IsDataSet="true"msdata:UseCurrentLocale="true">       <xs:complexType>         <xs:choiceminOccurs="0"maxOccurs="unbounded">           <xs:elementname="Table1">             <xs:complexType>               <xs:sequence>                 <xs:elementname="Id"type="xs:string"minOccurs="0" />                 <xs:elementname="Name"type="xs:string"minOccurs="0" />                 <xs:elementname="Date"type="xs:string"minOccurs="0" />               </xs:sequence>             </xs:complexType>           </xs:element>         </xs:choice>       </xs:complexType>     </xs:element>  </xs:schema>  <diffgr:diffgramxmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">     <NewDataSetxmlns="">       <Table1diffgr:id="Table11"msdata:rowOrder="0"diffgr:hasChanges="inserted">         <Id>377fdf8d-cfd1-4975-a167-2ddb41265def</Id>         <Name>157bc287-f09b-435f-a81f-2a3b23aff8c4</Name>         <Date>a5d78d83-6c9a-46ca-8277-f2be8d4658bf</Date>       </Table1>     </NewDataSet>  </diffgr:diffgram> </GetDataSetResult> Put the XSD into a BizTalk schema and it will fail to compile, giving you error: The 'http://www.w3.org/2001/XMLSchema:schema' element is not declared. You should be able to work around that, but I've had no luck in BizTalk Server 2006 R2 – instead you can safely change that xs:schema element to be another xs:any type: <xs:elementminOccurs="0"name="GetDataSetResult"nillable="true">  <xs:complexType>     <xs:sequence>       <xs:any />       <xs:any />     </xs:sequence>  </xs:complexType> </xs:element>  (This snippet omits the annotation, but you can leave it in the schema). For an XML instance to pass validation through the schema, you'll also need to flag the any attributes so they can contain any namespace and skip validation:  <xs:elementminOccurs="0"name="GetDataSetResult"nillable="true">  <xs:complexType>     <xs:sequence>       <xs:anynamespace="##any"processContents="skip" />       <xs:anynamespace="##any"processContents="skip" />     </xs:sequence>  </xs:complexType> </xs:element>  You should now have a compiling schema which can be successfully tested against a serialised DataSet. Transforms If you're mapping a DataSet element between schemas, you'll need to use the Mass Copy Functoid to populate the target node from the contents of both the xs:any type elements on the source node: This should give you a compiled map which you can test against a serialized instance. And if you have a .NET consumer on the other side of the mapped BizTalk output, it will correctly deserialize the response into a DataSet.

    Read the article

  • Stop lazy loading or skip loading a property in NHibernate? Proxy cannot be serialized through WCF

    - by HelloSam
    Consider I have a parent, child relationship class and mapping. I am using NHibernate to read the object from the database, and intended to use WCF to send the object across the wire. Goal For reading the parent object, I want to selectively, at different execution path, decide when I would want to load the child object. Because I don't want to read more than what I needed. Those partially loaded object must be able to sent through WCF. When I mean I don't load it, neither side will access such property. Problem When such partially loaded object is being sent through WCF, as those property is marked as [DataContract], it cannot be serialized as the property is lazy load proxy instead of real known type. What I want to archive, or solution that I can think of lazy=false or lazy=true doesn't work. Former will eagerly fetch all the relationships, latter will create a proxy. But I want nothing instead - a null would be the best. I don't need lazy load. I hope to get a null for those references that I don't want to fetch. A null, but not just a proxy. This will makes WCF happy, and waste less time to have a lazy-load proxy constructed. Like could I have a null proxy factory? -OR- Or making WCF ignoring those property that's a proxy instead of real. I tried the IDataContractSurrogate solution, but only parent is passed to GetObjectToSerialize, I never observe an proxy being passed through GetObjectToSerialize, leaving no chance to un-proxy it. Edit After reading the comments, more surfing on the Internet... It seems to me that DTO would shift major part of the computation to the server side. But for the project I am working on, 50% of time the client is "smarter" than the server and the server is more like a data store with validation and verification. Though I agree the server is not exactly dumb - I have to decide when to fetch the extra references already, and DTO will make this very explicit. Maybe I should just take the pain. I didn't know http://automapper.codeplex.com/ before, this motivates me a little more to take the pain. On the other hand, I found http://trentacular.com/2009/08/how-to-use-nhibernate-lazy-initializing-proxies-with-web-services-or-wcf/, which seems to be working with IDataContractSurrogate.GetObjectToSerialize.

    Read the article

  • WCF Webservices and FaultContract - Client's receiving SoapExc insted of FaultException<TDetails>

    - by Alessandro Di Lello
    Hi All, i'm developing a WCF Webservice and consuming it within a mvc2 application. My problem is that i'm using FaultContracts on my methods with a custom FaultDetail and i'm throwing manyally the faultexception but when the client receive the exception , it receives a normal SoapException instead of my FaultException that i throwed from the service side. Here is some code: Custom Fault Detail Class: [DataContract] public class MyFaultDetails { [DataMember] public string Message { get; set; } } Operation on service contract: [OperationContract] [FaultContract(typeof(MyFaultDetails))] void ThrowException(); Implementation: public void ThrowException() { var details = new MyFaultDetails { Message = "Exception Test" }; throw new FaultException<MyFaultDetails >(details , new FaultReason(details .Message), new FaultCode("MyFault")); } Client side: try { // Obv proxy init etc.. service.ThrowException(); } catch (FaultException<MyFaultDetails> ex) { // stuff } catch (Exception ex) { // stuff } What i expect is to catch the FaultException , instead that catch is skipped and the next catch is taken with an exception of type SoapException. Am i missing something ? i red a lot of threads about using faultcontracts within wcf and what i did seems to be good. I had a look at the wsdl and xsd generated and they look fine. here's a snippet regarding this method: <wsdl:operation name="ThrowException"> <wsdl:input wsaw:Action="http://tempuri.org/IAnyJobService/ThrowException" message="tns:IAnyJobService_ThrowException_InputMessage" /> <wsdl:output wsaw:Action="http://tempuri.org/IAnyJobService/ThrowExceptionResponse" message="tns:IAnyJobService_ThrowException_OutputMessage" /> <wsdl:fault wsaw:Action="http://tempuri.org/IAnyJobService/ThrowExceptionAnyJobServiceFaultExceptionFault" name="AnyJobServiceFaultExceptionFault" message="tns:IAnyJobService_ThrowException_AnyJobServiceFaultExceptionFault_FaultMessage" /> </wsdl:operation> <wsdl:operation name="ThrowException"> <soap:operation soapAction="http://tempuri.org/IAnyJobService/ThrowException" style="document" /> <wsdl:input> <soap:body use="literal" /> </wsdl:input> <wsdl:output> <soap:body use="literal" /> </wsdl:output> <wsdl:fault name="AnyJobServiceFaultExceptionFault"> <soap:fault use="literal" name="AnyJobServiceFaultExceptionFault" namespace="" /> </wsdl:fault> </wsdl:operation> Any help ? Thanks in advance Regards Alessandro

    Read the article

< Previous Page | 4 5 6 7 8 9 10  | Next Page >