Quantcast
Channel: WCF Data Services forum
Viewing all 877 articles
Browse latest View live

By using Webbrowser for windose service print functionality is not working

$
0
0

Hi,

My code is as follows when  i normally  execute the code.. its working but when i install the service using same it does not work(print functionality)


 public void Print() {
            WebBrowser webBrowserForPrinting = new WebBrowser();
            
        
            webBrowserForPrinting.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(PrintDocument);
            webBrowserForPrinting.Url = new Uri(FilePath);
            webBrowserForPrinting.Visible = true;
            webBrowserForPrinting.ScrollBarsEnabled = false;
            webBrowserForPrinting.ScriptErrorsSuppressed = true;
            //webBrowserForPrinting.DocumentCompleted += WebBrowserDocumentCompleted;
            while (webBrowserForPrinting.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            
            }
             
               webBrowserForPrinting.Dispose();
            
        }


private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser webBrowserForPrinting = sender as WebBrowser;
            // Print the document now that it is fully loaded.
        
            ((WebBrowser)webBrowserForPrinting).Print();

          

        }

or

private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
         
            // Print the document now that it is fully loaded.
            ((WebBrowser)sender).Print();
        
          

        }

thanks


Filter data in ProcessingPipeline.ProcessedRequest

$
0
0

Hi,

I am working on oData (WCF data service) with entity framework.

In the ProcessingPipeline.ProcessedRequest method i want to filter the data that will returned to the client.

Below is the code i have created

this.ProcessingPipeline.ProcessedRequest += new EventHandler<DataServiceProcessingPipelineEventArgs>(PrecessedReq);

void PrecessedReq(object sender, DataServiceProcessingPipelineEventArgs e)
        {

// What should i do here. 

}

Please suggest if we could filter the result data here or anywhere else in the life cycle.

C# consuming a wcf request in a restful way

$
0
0

We have been provided with a couple of xsd's from a third party. I have used the XSD Utility to create some classes. On one of these classes there is a method called 'GetProducts' and it has one method on it called Request.

The idea is that the 3rd party will call this method and then we need to act on the information that it has sent via this method.

in my ServiceContract class how do I consume this method in a Restful way? I'm not sure how I should declare the operationcontract. Can anybody offer a good code sample.

X.509 certificate signature

$
0
0

The cert signature for ecdsa-with-SHA256 algorithm is shown as two INTEGERs. Each one should have a size of 32 octets. However, one of them is shown having a size of 33 octets with a leading 0x00 octet. See the sample below. Why? Thank you.

 SEQUENCE                                                                  -- signatureAlgorithm

 {

   OBJECT IDENTIFIER=EcdsaWithSHA256 (1.2.840.10045.4.3.2)                 -- algorithm

 }

 BIT STRING, encapsulates:                                                 -- signatureValue

   SEQUENCE

   {

     INTEGER=

       3E 75 41 BD 18 AF 7F B5   >uA½.¯.µ

       93 D8 6C EC F5 A0 C1 22   .Ølìõ Á"

       8C AE D0 DF 12 9B 25 16   .®Ðß..%.

       D0 B1 94 E7 FC 08 C0 B2   б.çü.À²

     INTEGER=

       00 80 0D 74 2F A3 37 C7   ...t/£7Ç

       D0 B8 7C C0 0C 72 61 40   и|À.ra@

       D2 E4 66 1A 27 DA D2 96   Òäf.'ÚÒ.

       CF 3E E7 0D 3F 62 AB 6F   Ï>ç.?b«o

       56                       V

   }

}

How do i take wcf Odata service .developed in my Development machine to a production server?

$
0
0
My wcf Ogata Serviço Works pefectly in my development machine. How can I take it to tee production server?

"General Access Denied" Trying to Update AD User from WCF Service

$
0
0

I have used WCF services to create and update employees for years.  I have done this using PS scripting to create the Exchange Mailbox (and thereby creating an AD user), then getting the AD object, updating it further and saving those changes.  It has worked well.

Now, we have changed our configuration to a Hybrid Exchange configuration.  We have a local server and local AD with synchronization to O365 and Azure.

I am reworking my service to use our new setup.  I can create the Exchange mailbox (hitting our local server to do that), targeting our local AD I can load the newly-created user object. But when I try to update, I get theGeneral Access Denied error.  From code, I also force the scheduled task to sync local to cloud and when it's done, I reach out and update the O365 mailbox properties.  EVERYTHING works fine EXCEPT the AD object update.

Any help would be GREATLY appreciated!!

Thanks,
Glen

NOTE:  When I run it from my dev environment in Visual Studio, it works fine.  When I publish and try to test using WCF Test Client, THAT'S when it fails.

Problem with Response Keyword in WCF Operation Contract Name ( Method name)

$
0
0

Hi

I am developing a WCF service using VB .Net and Framework 4.

My service interface code is:

<ServiceContract()>
Public Interface IService1

#Region "Test1"

    ' interface object for Insert Statements
    <OperationContract()> Function InsertInterview() As Integer

    ' interface object for Insert Statements
    <OperationContract()> Function InsertInterviewResponse() As Integer

#End Region

End Interface

My problem is when i run this service it gives me an error:

An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior
 contract: http://tempuri.org/:IService1 ----> System.InvalidOperationException: The SLAF.ProxyTest.IService1.InsertInterviewResponse operation references a message element [http://tempuri.org/:InsertInterviewResponse] that has already been exported from the SLAF.ProxyTest.IService1.InsertInterview operation. You can change the name of one of the operations by changing the method name or using the Name property of OperationContractAttribute. Alternatively, you can control the element name in greater detail using the MessageContract programming model.
   at System.ServiceModel.Description.MessageContractExporter.AddElementToSchema(XmlSchemaElement element, String elementNs, XmlSchemaSet schemaSet)

Now as you can see in service code I have two different method name but only difference between two method name is one method name contains "Response" at it's end.

If I change this Response to any other text service starts working with no error.

My Question is, am I breaking any convention by using "Response" keyword in my Method name ? or it is a bug ?

Best Regards

Tanvir Raihan

DataServiceContext consume ODATA Service & Authentication

$
0
0

IhaveaLightswitch developerODATA services, theSilverlightclientrunsgood,the web config:

<authentication mode="Forms">

NowI amusingWPF todevelopanewclient,theDataServiceContext objectcanconsumeODATA services. CODE :

ApplicationData dataSvc

form_load:

 dataSvc = new ApplicationData(
    new Uri("http://ip.../Test/ApplicationData.svc/"));
dataSvc.Format.UseJson();
dataSvc.Credentials = new NetworkCredential("username", "pwd");

Button_click:

var query = from a in dataSvc.ProjectDocuments select a;
MessageBox.Show(query.ToList().Count.ToString());
var  query1 = from  b in dataSvc.ProjectItemSet select b;
MessageBox.Show(query1.ToList().Count.ToString());

Icanuse thedataservicecontextobjecttoautomaticallylog onandgetODATA data.

ButIfound thatthere weretwoproblems.Use theFiddlertool,Ifound asecondcalling,therewere4HTTP requests.Eachtime it iscalled, thefirstrequestwillberejected by theserver, anddisplays a401error, thesecondrequest iscanIget theexpecteddata.
BySQLServerProfiler tomonitor,Ifound thateachtime it iscalledserviceagainin thedatabaseagainusing theMemberShip toauthenticateusers.

I'mfeeling theDataServiceContext objectas ifnotforsessionstatemanagement,everycallwillinitiateasessionagain.

How todeal withthisphenomenon,andwhatneeds to bedone tomodify.

   void dataSvc_SendingRequest2(object sender, SendingRequest2EventArgs e)
        {
        
            if (cookie != null)
            {
               
                e.RequestMessage.SetHeader("Cookie", cookie);
            }
           
        }
        string cookie = null;
        void dataSvc_ReceivingResponse(object sender, ReceivingResponseEventArgs e)
        {
           
          
            if (cookie == null)
            {
                cookie = e.ResponseMessage.GetHeader("Set-Cookie");
            }
        }

Imanuallyset theCOOKIE,butnothing haschanged



Filter by datetime: Has the syntax changed in Version 4?

$
0
0

Before, this filter worked: $filter=CreatedRowDate ge datetime'2015-11-24T14:00:59.5500000'

But after updating to V4 of oData, it doesn't  work. Reason?

TryGetEntity returns always false

$
0
0

Hello,

I'm using WCF Data Services with Generic types, My class looks like the following:

public abstract class DataPagingViewModelBase<TContext, TEntity>

Inside this class I want to refresh an entity (Which is the selected item by the end-user).

To do that I created the following method:

public void RefreshSelectedEntity()
        {
            var selectedEntity = this.SelectedDataItem;
            Uri identity;
            if (this.ServiceContext.TryGetUri(selectedEntity, out identity))
            {
                this.ServiceContext.Detach(selectedEntity);
                object loadedEntity;
                if (this.ServiceContext.TryGetEntity(identity, out loadedEntity))
                {
                    this.SelectedDataItem = (TEntity)loadedEntity;
                }
            }
        }

My question is: Why the method TryGetEntity is returning always false even if the Uri exist (I tested the url on the IE and it works without a problem). Knwoing that the URi (identity) is gotten by using the method TryGetUri.

My second question is in the same context, The method TryGetUri Is working fine for me, except if the Entity was really edited by the user (using a wpf property grid control),

So if the one or more properties are edited by the user , then, the method TryGetUri is always returning false also!!

Can you help me please?

Query regarding Windows 10 build 10586

$
0
0

We are getting issue while installing safesign middleware 3.093 on Windows 10 build 10586.

Error - 1904 module. C:\WINDOWS\system32\aetcsss 1.dll failed to register. HRESULT -2147220473. Contact your support personnel.

But with WINDOWS 10 build 10240, installation for safesign middleware is OK and working fine.

Please suggest for this issue.

This safesign middleware is used for digital signature.

This middleware is working on WINDOWS XP. WIN7 WIN 8 and WINDOWS 10 build 10240.

Error: A binding instance has already been associated to listen URI

$
0
0

Hello. I have the following problem:

I'm trying to configure a WCF DataService, but it keeps throwing an error. Currently this web service works properly in another local server. Besides Dataservice I have another service for managing images.

Here there is a solution, but do not work for me: http://stackoverflow.com/questions/11506107/wcf-invalidoperationexception-a-binding-instance-has-already-been-associated-to

ERROR:

A binding instance has already been associated to listen URI 'http://domain.com/wsData/DataService.svc'. If two endpoints want to share the same ListenUri, they must also share the same binding object instance. The two conflicting endpoints were either specified in AddServiceEndpoint() calls, in a config file, or a combination of AddServiceEndpoint() and config.

 web.config:

<?xml version="1.0" encoding="utf-8"?><!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  --><configuration><configSections><!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --><section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /><!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections><system.web><customErrors mode="Off"></customErrors><compilation ><assemblies><add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /></assemblies></compilation><!--<httpRuntime targetFramework="4.5" />--></system.web><system.serviceModel><bindings><webHttpBinding><binding
          maxBufferPoolSize="2147483647"
          maxReceivedMessageSize="2147483647"
          maxBufferSize="2147483647" transferMode="Streamed"><security mode="None"><transport clientCredentialType="None" /></security></binding></webHttpBinding></bindings><behaviors><serviceBehaviors><behavior name="ServiceBehavior"><serviceMetadata httpGetEnabled="true" /><serviceDebug includeExceptionDetailInFaults="true"/></behavior></serviceBehaviors><endpointBehaviors><behavior name="EndpBehavior"><webHttp/></behavior></endpointBehaviors></behaviors><services><service behaviorConfiguration="ServiceBehavior" name="wsPALLQC.ImagenHandler"><endpoint address="ImagenHandler.svc" binding="webHttpBinding"
            contract="wsPALLQC.IImagenHandler" behaviorConfiguration="EndpBehavior" listenUri="/"></endpoint></service></services><serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /></system.serviceModel><connectionStrings><add name="QCEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=host;initial catalog=db;persist security info=True;user id=user;password=pass;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /></connectionStrings><entityFramework><defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /></entityFramework><system.webServer><security><authentication><anonymousAuthentication enabled="true"/><windowsAuthentication enabled="false"/><basicAuthentication enabled="false"/></authentication></security><modules ><add name="WcfReadEntityBodyModeWorkaroundModule" type="wsPALLQC.WcfReadEntityBodyModeWorkaroundModule, wsPALLQC" /></modules></system.webServer></configuration>

In advance thank you very much for any help.

Add DataContext property at Entity Level in LinqToSql class with WCF DataService

$
0
0

Hello

I am new to WCF DataService. I want to expose DataContext Property at Entity level . But when I try to update service at view side it is giving following error:

The server encountered an error processing the request. The exception message is 'The property 'Regions' on a complex type 'WcfService1.DataClasses1DataContext' is not a valid property. Navigation properties are not supported on complex types.'."

Following is my code for Entity.

#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34209
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace WcfService1
{
	using System.Data.Linq;
	using System.Data.Linq.Mapping;
	using System.Data;
	using System.Collections.Generic;
	using System.Reflection;
	using System.Linq;
	using System.Linq.Expressions;
	using System.ComponentModel;
	using System;


	[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="Northwind")]
	public partial class DataClasses1DataContext : System.Data.Linq.DataContext
	{

		private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();

    #region Extensibility Method Definitions
    partial void OnCreated();
    partial void InsertRegion(Region instance);
    partial void UpdateRegion(Region instance);
    partial void DeleteRegion(Region instance);
    partial void InsertTerritory(Territory instance);
    partial void UpdateTerritory(Territory instance);
    partial void DeleteTerritory(Territory instance);
    #endregion

		public DataClasses1DataContext() :
				base(global::System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString, mappingSource)
		{
			OnCreated();
		}

		public DataClasses1DataContext(string connection) :
				base(connection, mappingSource)
		{
			OnCreated();
		}

		public DataClasses1DataContext(System.Data.IDbConnection connection) :
				base(connection, mappingSource)
		{
			OnCreated();
		}

		public DataClasses1DataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
				base(connection, mappingSource)
		{
			OnCreated();
		}

		public DataClasses1DataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
				base(connection, mappingSource)
		{
			OnCreated();
		}

		public System.Data.Linq.Table<Region> Regions
		{
			get
			{
				return this.GetTable<Region>();
			}
		}

		public System.Data.Linq.Table<Territory> Territories
		{
			get
			{
				return this.GetTable<Territory>();
			}
		}
	}
   //  [System.Data.Services.IgnoreProperties("DataContext")]
	[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Region")]
	public partial class Region : INotifyPropertyChanging, INotifyPropertyChanged
	{

		private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);

		private int _RegionID;

		private string _RegionDescription;

		private EntitySet<Territory> _Territories;

    #region Extensibility Method Definitions
    partial void OnLoaded();
    partial void OnValidate(System.Data.Linq.ChangeAction action);
    partial void OnCreated();
    partial void OnRegionIDChanging(int value);
    partial void OnRegionIDChanged();
    partial void OnRegionDescriptionChanging(string value);
    partial void OnRegionDescriptionChanged();
    #endregion

		public Region()
		{
			this._Territories = new EntitySet<Territory>(new Action<Territory>(this.attach_Territories), new Action<Territory>(this.detach_Territories));
			OnCreated();
		}

		[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_RegionID", DbType="Int NOT NULL", IsPrimaryKey=true)]
		public int RegionID
		{
			get
			{
				return this._RegionID;
			}
			set
			{
				if ((this._RegionID != value))
				{
					this.OnRegionIDChanging(value);
					this.SendPropertyChanging();
					this._RegionID = value;
					this.SendPropertyChanged("RegionID");
					this.OnRegionIDChanged();
				}
			}
		}

		[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_RegionDescription", DbType="NChar(50) NOT NULL", CanBeNull=false)]
		public string RegionDescription
		{
			get
			{
				return this._RegionDescription;
			}
			set
			{
				if ((this._RegionDescription != value))
				{
					this.OnRegionDescriptionChanging(value);
					this.SendPropertyChanging();
					this._RegionDescription = value;
					this.SendPropertyChanged("RegionDescription");
					this.OnRegionDescriptionChanged();
				}
			}
		} private DataClasses1DataContext _DataContext;

        public DataClasses1DataContext Context
        {
            get { return _DataContext; }
            set { _DataContext = value; }
        }
		[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Region_Territory", Storage="_Territories", ThisKey="RegionID", OtherKey="RegionID")]
		public EntitySet<Territory> Territories
		{
			get
			{
                ////DataClasses1DataContext DataContext = this.GetDataContext();if (DataContext != null && _Territories == null)
                {
                    // DataContext.LoadProperty(this, "Territories");
                    const BindingFlags FLAGS = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
                    var method = DataContext.GetType().GetMethod("ClearCache", FLAGS);
                    method.Invoke(DataContext, null);
                    // DataContext.DeferredLoadingEnabled = false;
                    var MasterUnitsloadOption = new DataLoadOptions();
                    MasterUnitsloadOption.LoadWith<Region>(p => p.Territories);
                    DataContext.LoadOptions = MasterUnitsloadOption;
                }
				return this._Territories;
			}
			set
			{
				this._Territories.Assign(value);
			}
		}

		public event PropertyChangingEventHandler PropertyChanging;

		public event PropertyChangedEventHandler PropertyChanged;

		protected virtual void SendPropertyChanging()
		{
			if ((this.PropertyChanging != null))
			{
				this.PropertyChanging(this, emptyChangingEventArgs);
			}
		}

		protected virtual void SendPropertyChanged(String propertyName)
		{
			if ((this.PropertyChanged != null))
			{
				this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}

		private void attach_Territories(Territory entity)
		{
			this.SendPropertyChanging();
			entity.Region = this;
		}

		private void detach_Territories(Territory entity)
		{
			this.SendPropertyChanging();
			entity.Region = null;
		}
	}

	[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Territories")]
	public partial class Territory : INotifyPropertyChanging, INotifyPropertyChanged
	{

		private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);

		private string _TerritoryID;

		private string _TerritoryDescription;

		private int _RegionID;

		private int _Id;

		private EntityRef<Region> _Region;

    #region Extensibility Method Definitions
    partial void OnLoaded();
    partial void OnValidate(System.Data.Linq.ChangeAction action);
    partial void OnCreated();
    partial void OnTerritoryIDChanging(string value);
    partial void OnTerritoryIDChanged();
    partial void OnTerritoryDescriptionChanging(string value);
    partial void OnTerritoryDescriptionChanged();
    partial void OnRegionIDChanging(int value);
    partial void OnRegionIDChanged();
    partial void OnIdChanging(int value);
    partial void OnIdChanged();
    #endregion

		public Territory()
		{
			this._Region = default(EntityRef<Region>);
			OnCreated();
		}

		[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_TerritoryID", DbType="NVarChar(20) NOT NULL", CanBeNull=false, IsPrimaryKey=true)]
		public string TerritoryID
		{
			get
			{
				return this._TerritoryID;
			}
			set
			{
				if ((this._TerritoryID != value))
				{
					this.OnTerritoryIDChanging(value);
					this.SendPropertyChanging();
					this._TerritoryID = value;
					this.SendPropertyChanged("TerritoryID");
					this.OnTerritoryIDChanged();
				}
			}
		}

		[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_TerritoryDescription", DbType="NVarChar(50) NOT NULL", CanBeNull=false)]
		public string TerritoryDescription
		{
			get
			{
				return this._TerritoryDescription;
			}
			set
			{
				if ((this._TerritoryDescription != value))
				{
					this.OnTerritoryDescriptionChanging(value);
					this.SendPropertyChanging();
					this._TerritoryDescription = value;
					this.SendPropertyChanged("TerritoryDescription");
					this.OnTerritoryDescriptionChanged();
				}
			}
		}

		[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_RegionID", DbType="Int NOT NULL")]
		public int RegionID
		{
			get
			{
				return this._RegionID;
			}
			set
			{
				if ((this._RegionID != value))
				{
					if (this._Region.HasLoadedOrAssignedValue)
					{
						throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
					}
					this.OnRegionIDChanging(value);
					this.SendPropertyChanging();
					this._RegionID = value;
					this.SendPropertyChanged("RegionID");
					this.OnRegionIDChanged();
				}
			}
		}

		[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.Always, DbType="Int NOT NULL IDENTITY", IsDbGenerated=true)]
		public int Id
		{
			get
			{
				return this._Id;
			}
			set
			{
				if ((this._Id != value))
				{
					this.OnIdChanging(value);
					this.SendPropertyChanging();
					this._Id = value;
					this.SendPropertyChanged("Id");
					this.OnIdChanged();
				}
			}
		}

		[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Region_Territory", Storage="_Region", ThisKey="RegionID", OtherKey="RegionID", IsForeignKey=true)]
		public Region Region
		{
			get
			{
				return this._Region.Entity;
			}
			set
			{
				Region previousValue = this._Region.Entity;
				if (((previousValue != value)
							|| (this._Region.HasLoadedOrAssignedValue == false)))
				{
					this.SendPropertyChanging();
					if ((previousValue != null))
					{
						this._Region.Entity = null;
						previousValue.Territories.Remove(this);
					}
					this._Region.Entity = value;
					if ((value != null))
					{
						value.Territories.Add(this);
						this._RegionID = value.RegionID;
					}
					else
					{
						this._RegionID = default(int);
					}
					this.SendPropertyChanged("Region");
				}
			}
		}

		public event PropertyChangingEventHandler PropertyChanging;

		public event PropertyChangedEventHandler PropertyChanged;

		protected virtual void SendPropertyChanging()
		{
			if ((this.PropertyChanging != null))
			{
				this.PropertyChanging(this, emptyChangingEventArgs);
			}
		}

		protected virtual void SendPropertyChanged(String propertyName)
		{
			if ((this.PropertyChanged != null))
			{
				this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}
	}
}
#pragma warning restore 1591

If I remove DataContext property from Region class then it will work fine.

But my issue is I want to use Territories property from Region object (SetProperty) . So I have to get dataContext at entity level to set LoadOpetions property of DataContext.

But here it is giving error. So can anybody please guide me how to use it?

Or how the structure it should be to use LinqToSql with WCF DataService with WPF?

I want to expose EntityRef & EntitySet for all entities so after searching I got that we can do that If we use loadopetion of datacontext. But here If I add this property then after rebuild service project When I try to update Reference at view side it is giving error.

Please help me for this issue.

Regards

Vipul



Linq To Sql with WCFDataService with WPF project structure

$
0
0

Hello

I am new to this WCF DataService.

I want to use linq to sql with WCFDataService with wpf.

My existing project is with MVVM architecture with LinqToSql at model side. So we want to continue with same but with WCF DataService.

Here can anybody please guide me what kind of structure it could be?

My idea is creating application server where Database will be there. Plus we also planning to add Model & viewModel (business logics -> partial classes) at there . On client side there will be only view. Both will communicate using WCF DataService.

Is this architecture is possible? Here for basics we are facing lots of difficulties like:

1) CRUD operations issue: need to apply IUpdatable mechanism to do it.

2) EntityRef EntitySet can not be exposed . need some mechanism for it. (Still searching for proper way)

3) Complex types at Entity level can not be supported. ( still searching)

& many more issues.

Can any body please guide me about architecture we can adopt & any limitations that can not make it possible to use this kind of mechanism?

Regards

Vipul

InvalidDataContractException While Trying To Serialize DuplicateKeyException?

$
0
0
I have an BinaryMessageEncoder in some server-side WCF code, and I am calling WriteMessage(). At one point, the call is throwing an exception of type System.Runtime.Serialization.InvalidDataContractException. As I dig into it, I see that it's trying to serialize an object of type System.Data.Linq.DuplicateKeyException, which is (obviously) not anywhere in my object graph. I am guessing that the serialization is throwing a DuplicateKeyException, which WCF then tries (and fails) to serialize. Any thoughts on how to track this down? Specifically, how can I find out where the DuplicateKeyException is coming from?

The type 'System.Data.Services.Client.DataServiceResponsePreference' has no settable properties." On Save data with WCF DataService using Binding List

$
0
0

Hello

I am using WCF DataService with Entity framework.

At at client app I have added service reference. So that My dataContext (NorthwindEntities) can be reflacted at client side.

I have to use BindingList . Plus I have property of DataContext at BindingList side which I am setting.

Following is my code

public class OrderBindingList : BindingList<Order> { #region Constructor /// <summary> /// Initializes a new instance of the <see cref="AvailableStockBindingList" /> class. /// </summary> /// <param name="list"> an IList object.</param> public OrderBindingList(IList<Order> list) : base(list) { } #endregion #region Public Properties /// <summary> /// Gets or sets a value for DataContext. /// </summary> [DoNotSerialize] public ServiceReference1.NorthwindEntities DataContext { get; set; } #endregion } public partial class MainWindow : Window { public OrderBindingList mibl { get; set; } public MainWindow() { InitializeComponent(); ServiceReference1.NorthwindEntities dc = new ServiceReference1.NorthwindEntities(new Uri("http://localhost:50474/WcfDataService1.svc")); mibl = new OrderBindingList(dc.Orders.ToList()); mibl.DataContext = dc ; /// If I set this then ///error comes. I must set this. Order mi = mibl.FirstOrDefault(); if (mi != null) { mi.Freight += 1; } dc.UpdateObject(mi); dc.SaveChanges(); /// Here error comes } }

/// Following is my Order class code which is generated. I have added one property to Order generated class.

/// Here I am sharing some code which I added to it

 [global::System.Data.Services.Common.EntitySetAttribute("Orders")]
    [global::System.Data.Services.Common.DataServiceKeyAttribute("OrderID")]
    public partial class Order : global::System.ComponentModel.INotifyPropertyChanged, global::System.ComponentModel.INotifyPropertyChanging
    {
       
        object wait = new object();
        private NorthwindEntities _DataContext;
        [DoNotSerialize]
        public NorthwindEntities DataContext
        {
            set { _DataContext = value; }
            get
            {
                object value;
                if (_DataContext != null)
                    return _DataContext;
                else
                {
                    INotifyPropertyChanging obj = this;
                    FieldInfo fEvent = (obj.GetType()).GetField("PropertyChanging", BindingFlags.NonPublic | BindingFlags.Instance);
                    MulticastDelegate dEvent = (MulticastDelegate)fEvent.GetValue(obj);
                    if (dEvent != null)
                    {
                        Delegate[] onChangingHandlers = dEvent.GetInvocationList();

                        foreach (Delegate handler in onChangingHandlers)
                        {
                            if (handler.Target.GetType().Name == "StandardChangeTracker")
                            {
                                object tracker = handler.Target;
                                object services = tracker.GetType().GetField("services", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(tracker);

                                global::System.Data.Services.Client.DataServiceContext context = services.GetType().GetProperty("Context").GetValue(services, null) as global::System.Data.Services.Client.DataServiceContext;
                                if (context is NorthwindEntities)
                                {
                                    _DataContext = (NorthwindEntities)context;
                                    return _DataContext;
                                }
                            }
                        }
                    }
                    else
                    {
                        INotifyPropertyChanged objChanged = this;
                        FieldInfo finfoPropertyChanged = (objChanged.GetType()).GetField("PropertyChanged", BindingFlags.NonPublic | BindingFlags.Instance);
                        MulticastDelegate mDelegate = (MulticastDelegate)finfoPropertyChanged.GetValue(objChanged);
                        if (mDelegate != null)
                        {
                            Delegate[] onChangedHandler = mDelegate.GetInvocationList();
                            object target = onChangedHandler.First().Target;
                            var data = target.GetType().GetField("data", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                            IBindingList lst = target as IBindingList;
                            if (lst == null) return null;
                            global::System.Data.Services.Client.DataServiceContext context = target.GetType().GetProperty("DataContext").GetValue(target, null) as global::System.Data.Services.Client.DataServiceContext;
                            ////global::System.Data.Services.Client.DataServiceContext context = DataContextHelper.GetDataContext(lst);
                            if (context is NorthwindEntities)
                            {
                                _DataContext = (NorthwindEntities)context;
                                return _DataContext; ;
                            }
                        }
                    }
                    return null;
                }
            }
        }

/// .... Other code as it is

At the time of saving following error coming:

"The type 'System.Data.Services.Client.DataServiceResponsePreference' has no settable properties."

  at System.Data.Services.Client.SaveResult.HandleResponse()
   at System.Data.Services.Client.BaseSaveResult.EndRequest()
   at System.Data.Services.Client.DataServiceContext.SaveChanges(SaveChangesOptions options)
   at System.Data.Services.Client.DataServiceContext.SaveChanges()
   at EntityFWBindingListCHK.MainWindow..ctor() in d:\projects\EntityFWBindingListCHK\EntityFWBindingListCHK\MainWindow.xaml.cs:line 39

Can any one please guide me how to solve this issue?

I have asked same question at following

https://social.msdn.microsoft.com/Forums/vstudio/en-US/4196e382-1849-4719-a49c-daa9e165b01c/the-type-systemdataservicesclientdataserviceresponsepreference-has-no-settable-properties?forum=wcf

But unfortunately not got exact reason about & issue & solution of it.

So can any one please help me to solve this issue?

Regards

Vipul

Odata Controller: How to convert Odata response to C# object at client

$
0
0

We have got a Odata response as below:

"{\r\n  \"@odata.context\":\"http://localhost/ApplicationService/model/$metadata#Edm.String\",\"value\":\"{\\\"Messages\\\":[\\\"message 1\\\",\\\"message 2\\\",\\\"message 3\\\",\\\"message 4\\\"],\\\"IsValidEntity\\\":false}\"\r\n}"

                            

///////////////////////////

//////////////Now say we have a class:
////////////// Odata controller part -Start -------------------------------------------------

public class myValidationResult

    public class myValidationResult
    {
        public myValidationResult()
        {
            Messages = new List<string>();
        }
        public List<string> Messages { get; set; }
        public bool IsValidEntity { get; set; }
    }

///////////////////////////This class used in MyOdataController class as below:


public class MyODataController : ODataController

{

  // NEW ENTITY
        [Authorize(Roles = "Admin")]
        public async Task<IHttpActionResult> Post(T entity)
        {         

                myValidationResult  vResult = new myValidationResult();
                vResult.Messages.Add("message 1");
                vResult.Messages.Add("message 2");
                vResult.Messages.Add("message 3");
                vResult.Messages.Add("message 4");
                vResult.IsValidEntity = false;

                 var strResult = JsonConvert.SerializeObject(vResult);
                var resp = Content(HttpStatusCode.BadRequest, strResult );

                return resp;


        }
}////////////// Odata controller part -End-------------------------------------------------

///////////// Client Consuming this - Start --------------------------------------------------------------------

/// We created below Class:

    public class OData<T>
    {
        [JsonProperty("odata.context")]
        public string Metadata { get; set; }
        public T value { get; set; }
    }

/// in method where we call the Odata method & store response in 'msg':

  var resp = msg.Result.Content.ReadAsStringAsync().Result;

/*

resp is: 

"{\r\n  \"@odata.context\":\"http://localhost/ApplicationService/model/$metadata#Edm.String\",\"value\":\"{\\\"Messages\\\":[\\\"message 1\\\",\\\"message 2\\\",\\\"message 3\\\",\\\"message 4\\\"],\\\"IsValidEntity\\\":false}\"\r\n}"

*/

  var odatares = JsonConvert.DeserializeObject<OData<myValidationResult>>(resp);

/*

But Above line giving error: Can not convert value\":\"{\\\"Messages\\\":[\\\"message 1\\\",\\\"message 2\\\",\\\"message 3\\\",\\\"message 4\\\"],\\\"IsValidEntity\\\":false} 

to <.....namespace......>myValidationResult

*/

///////////// Client Consuming this - End--------------------------------------------------------------------

Please suggest accordingly.

Thanks in advance.


Ignore Client Side Entity Property

$
0
0

I have entities with additional entity properties that do not exist in server entity type, and can't save changes with error message "Resource not found for the segment 'EntityTypePropertyName'.

For non entity properties i use a workaround from link:http://blogs.msdn.com/b/phaniraj/archive/2008/12/11/customizing-serialization-of-entities-in-the-ado-net-data-services-client-library.aspx

but it cannot remove entity properties.

My scenario is as follows:

Server side entities:

public partial class A { int Id {get; set;} public virtual DbSet<B> Bs { get; set; } } public partial class B { int Id {get; set;} int A_Id {get; set;} public virtual A A { get; set; } } public partial class C { int Id {get; set;} int B_Id {get; set;} public virtual B B { get; set; } }

Client side:

public partial class C
{
    public A A { get; set; }
}
Here the property A is public for binding purposes and must be ignored when saving changes, but the above workaround does not work for entity property "A" with error message "Resource not found for the segment 'A'."




WCF custom Behavior to send response from Cache

$
0
0

Hi Experts,

I need to build WCF customer Behavior Service level

 I need to check the Data is available in cache then i need to retreive the data from cache and send it to the client.

If the requested data is not present in Cache ,then i need to send the request to the operation.

storing the data in the cache and retrieving from cache i have done.

In WCF custom behavior ----I need to implement method AfterReceiveRequest() --need to check requested data is available in cache or not,if data present in cache then return from cache else need to route the request to the operation.

Please share your valuable suggestions to implement this.

WCF custom Behavior to send response from Cache

$
0
0

Hi Experts,

I need to build WCF customer Behavior Service level

 I need to check the Data is available in cache then i need to retreive the data from cache and send it to the client.

If the requested data is not present in Cache ,then i need to send the request to the operation.

storing the data in the cache and retrieving from cache i have done.

In WCF custom behavior ----I need to implement method AfterReceiveRequest() --need to check requested data is available in cache or not,if data present in cache then return from cache else need to route the request to the operation.

Please share your valuable suggestions to implement this.

Viewing all 877 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>