473,669 Members | 2,458 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

WCF Question

WCF Question

Hi guys,

I’m pretty new to WCF, and have a basic question about how it works. I’m
trying to use WCF to write an “SOA-system”, and am having a few problems.

The following analogy explains what I’m trying to do. I have a very simple
class:

[DataContract]
public class MyClass
{
private string data = "default data";

[DataMember]
public string Data
{
get
{
return data;
}
set
{
data = value;
}
}
}

This is exposed via a WCF Service:

[ServiceContract]
public interface IMyClassService
{
[OperationContra ct]
void Add(MyClass item);
}

public class MyClassService : IMyClassService
{
public void Add(MyClass item)
{
//Do something with the data...
Debug.WriteLine (item.Data);
}
}

As you can see, this is extremely simple. I’ve put the service in an ASP.NET
web application, created the correct web-config entries, included an svc file
with the correct tag, and the service does work. I’ve consumed the service
via a console application (by creating a service reference). I have the
following (very simple) code in the console application:

public static class Program
{
public static void Main(string[] args)
{
MyClassServiceC lient client = new MyClassServiceC lient();

MyClass myClass = new MyClass();

client.Add(myCl ass);
}
}

Obviously, the MyClass reference in the console application is a proxy class
generated automatically by WCF. It only knows about the properties marked
with [DataMember] attributes. This means that any “private” code within
MyClass is not executed by the console application. However, when the proxy
is passed to the service, I would expect an instance of the “real” or full
MyClass class to be instantiated on the WCF server, and I would expect the
private code to run on construction. It doesn’t! This can be proved by
looking at the value of the Data property on the server. It is still set as
null, despite giving it a value in the field declaration.

Hence, if MyClass has a constructor with code, this would not fire on the
server.

So, my questions is this: Is there a way to ensure that MyClass is
constructed fully on the server? It would be great if constructor code could
be fired. Can this behaviour be obtained by tweaking the attributes in the
service classes?

Thanks in advance,

Steve.

Aug 21 '08 #1
16 2403

I don't know if this helps or not.

But this is a non-proxy-class approach, in a DotNet to DotNet world with
WCF.

http://sholliday.space s.live.com/Blog/cns!A68482B9628 A842A!158.entry

"Steve Barker" <st**********@n ospam.nospamwro te in message
news:88******** *************** ***********@mic rosoft.com...
WCF Question

Hi guys,

I'm pretty new to WCF, and have a basic question about how it works. I'm
trying to use WCF to write an "SOA-system", and am having a few problems.

The following analogy explains what I'm trying to do. I have a very simple
class:

[DataContract]
public class MyClass
{
private string data = "default data";

[DataMember]
public string Data
{
get
{
return data;
}
set
{
data = value;
}
}
}

This is exposed via a WCF Service:

[ServiceContract]
public interface IMyClassService
{
[OperationContra ct]
void Add(MyClass item);
}

public class MyClassService : IMyClassService
{
public void Add(MyClass item)
{
//Do something with the data...
Debug.WriteLine (item.Data);
}
}

As you can see, this is extremely simple. I've put the service in an
ASP.NET
web application, created the correct web-config entries, included an svc
file
with the correct tag, and the service does work. I've consumed the service
via a console application (by creating a service reference). I have the
following (very simple) code in the console application:

public static class Program
{
public static void Main(string[] args)
{
MyClassServiceC lient client = new MyClassServiceC lient();

MyClass myClass = new MyClass();

client.Add(myCl ass);
}
}

Obviously, the MyClass reference in the console application is a proxy
class
generated automatically by WCF. It only knows about the properties marked
with [DataMember] attributes. This means that any "private" code within
MyClass is not executed by the console application. However, when the
proxy
is passed to the service, I would expect an instance of the "real" or full
MyClass class to be instantiated on the WCF server, and I would expect the
private code to run on construction. It doesn't! This can be proved by
looking at the value of the Data property on the server. It is still set
as
null, despite giving it a value in the field declaration.

Hence, if MyClass has a constructor with code, this would not fire on the
server.

So, my questions is this: Is there a way to ensure that MyClass is
constructed fully on the server? It would be great if constructor code
could
be fired. Can this behaviour be obtained by tweaking the attributes in the
service classes?

Thanks in advance,

Steve.

Aug 21 '08 #2
It looks like the problem here is that you did actually send a <nullup
the wire, because you instantiated with:

MyClass myClass = new MyClass();
client.Add(myCl ass);

Because the proxy MyClass doesn't know any better, all fields are
initialized to their defaults (null for string) and actively sent. This
(at the server) essentially does (for the real objects):

MyClass serverObj = new MyClass();
serverObj.Data = null;
// etc

You need to tell the class about defaults... in this case, you can do it
by (on the server object):

private string data = "default data";

[DataMember, DefaultValue("d efault data")]
public string Data {...}

(although you'll probably need to regenerate the client proxies to
update it).

This [DefaultValue] is part of the contract, so now the client proxy
will a: initialize as "default data", and b: not bother sending "default
data", as it can be assumed at the server (you can make it send default
values by tweaking the optional [DataMember] properties).

Marc
Aug 21 '08 #3
Well, you can't stop the client doing what it likes... and by definition
proxies don't have any logic. You also can't take away the default ctor,
or the serializer will break.

So you *could* have a New() method on the service, but it seems
overkill. What sort of logic did you have in mind?

Alternatively, you could create a method in a partial class at the
client (in a separate file for the service, but same types) that creates
a New() method. You could also check whether the WCF-generated proxy
exposes any partial methods that might help (if you are using C# 3).

If you are doing .NET-to-.NET, note that you don't have to limit
yourself to the proxies; you can also share the .cs (or the entire
assemlby containing your data-contracts / service-contracts) between the
client and the server; this allows you to run the same code at each, but
note that the server shouldn't assume that any such logic has occurred
(since a hostile client could be sending any old rubbish).

Note that in addition to [DefaultValue], DataContractSer ializer also
supports the "bool ShouldSerialize {PropertyName}( )" pattern for complex
optional values, but this won't work at the client if shallow proxies
are used.

Marc
Aug 21 '08 #4
That's a good point about not being able to stop the client from
instantiating an object. Hence, the New() method is not a good idea!

The sort of logic I'm talking about is stuff like checking business rules (a
la Rockford Lhotka). I want each class to maintain a set of which business
rules have been broken. (The class exposes an IsValid property.) For this, I
need certain code to run in the constructor of the class when it gets back to
the server, otherwise the rules structures are not instantiated.

It sounds as though I'm going to have to run the full class code in the
client as well as the server, which is a shame as standard WCF seems quite
elegant in that you don't have to have knowledge of the class at the client.

I don't understand what you mean by "bool ShouldSerialize {PropertyName}( )".
Can you point me in the right direction of an article on this please?

Sloan mentions that it's possible to get WCF to serialise the entire class
and send it down the wire, rather than sending a proxy. I think it has
something to do with NetDataContract Serializer. I'm having trouble
understanding the articles I've read on this, so can you help me with this at
all?

Many thanks,

Steve.

"Marc Gravell" wrote:
Well, you can't stop the client doing what it likes... and by definition
proxies don't have any logic. You also can't take away the default ctor,
or the serializer will break.

So you *could* have a New() method on the service, but it seems
overkill. What sort of logic did you have in mind?

Alternatively, you could create a method in a partial class at the
client (in a separate file for the service, but same types) that creates
a New() method. You could also check whether the WCF-generated proxy
exposes any partial methods that might help (if you are using C# 3).

If you are doing .NET-to-.NET, note that you don't have to limit
yourself to the proxies; you can also share the .cs (or the entire
assemlby containing your data-contracts / service-contracts) between the
client and the server; this allows you to run the same code at each, but
note that the server shouldn't assume that any such logic has occurred
(since a hostile client could be sending any old rubbish).

Note that in addition to [DefaultValue], DataContractSer ializer also
supports the "bool ShouldSerialize {PropertyName}( )" pattern for complex
optional values, but this won't work at the client if shallow proxies
are used.

Marc
Aug 21 '08 #5
Actually, scratch that, the NetDataContract Serializer is actually really easy
to use, and completely solves the problem.

Sloan: Thanks very much for providing that solution!

"Steve Barker" wrote:
That's a good point about not being able to stop the client from
instantiating an object. Hence, the New() method is not a good idea!

The sort of logic I'm talking about is stuff like checking business rules (a
la Rockford Lhotka). I want each class to maintain a set of which business
rules have been broken. (The class exposes an IsValid property.) For this, I
need certain code to run in the constructor of the class when it gets back to
the server, otherwise the rules structures are not instantiated.

It sounds as though I'm going to have to run the full class code in the
client as well as the server, which is a shame as standard WCF seems quite
elegant in that you don't have to have knowledge of the class at the client.

I don't understand what you mean by "bool ShouldSerialize {PropertyName}( )".
Can you point me in the right direction of an article on this please?

Sloan mentions that it's possible to get WCF to serialise the entire class
and send it down the wire, rather than sending a proxy. I think it has
something to do with NetDataContract Serializer. I'm having trouble
understanding the articles I've read on this, so can you help me with this at
all?

Many thanks,

Steve.

"Marc Gravell" wrote:
Well, you can't stop the client doing what it likes... and by definition
proxies don't have any logic. You also can't take away the default ctor,
or the serializer will break.

So you *could* have a New() method on the service, but it seems
overkill. What sort of logic did you have in mind?

Alternatively, you could create a method in a partial class at the
client (in a separate file for the service, but same types) that creates
a New() method. You could also check whether the WCF-generated proxy
exposes any partial methods that might help (if you are using C# 3).

If you are doing .NET-to-.NET, note that you don't have to limit
yourself to the proxies; you can also share the .cs (or the entire
assemlby containing your data-contracts / service-contracts) between the
client and the server; this allows you to run the same code at each, but
note that the server shouldn't assume that any such logic has occurred
(since a hostile client could be sending any old rubbish).

Note that in addition to [DefaultValue], DataContractSer ializer also
supports the "bool ShouldSerialize {PropertyName}( )" pattern for complex
optional values, but this won't work at the client if shallow proxies
are used.

Marc
Aug 21 '08 #6
//I think it has
something to do with NetDataContract Serializer. I'm having trouble
understanding the articles I've read on this, so can you help me with this
at
all?
//

My blog entry has a completely downloadable example of C# code.


"Steve Barker" <st**********@n ospam.nospamwro te in message
news:EB******** *************** ***********@mic rosoft.com...
That's a good point about not being able to stop the client from
instantiating an object. Hence, the New() method is not a good idea!

The sort of logic I'm talking about is stuff like checking business rules
(a
la Rockford Lhotka). I want each class to maintain a set of which business
rules have been broken. (The class exposes an IsValid property.) For this,
I
need certain code to run in the constructor of the class when it gets back
to
the server, otherwise the rules structures are not instantiated.

It sounds as though I'm going to have to run the full class code in the
client as well as the server, which is a shame as standard WCF seems quite
elegant in that you don't have to have knowledge of the class at the
client.

I don't understand what you mean by "bool
ShouldSerialize {PropertyName}( )".
Can you point me in the right direction of an article on this please?

Sloan mentions that it's possible to get WCF to serialise the entire class
and send it down the wire, rather than sending a proxy. I think it has
something to do with NetDataContract Serializer. I'm having trouble
understanding the articles I've read on this, so can you help me with this
at
all?

Many thanks,

Steve.

"Marc Gravell" wrote:
>Well, you can't stop the client doing what it likes... and by definition
proxies don't have any logic. You also can't take away the default ctor,
or the serializer will break.

So you *could* have a New() method on the service, but it seems
overkill. What sort of logic did you have in mind?

Alternativel y, you could create a method in a partial class at the
client (in a separate file for the service, but same types) that creates
a New() method. You could also check whether the WCF-generated proxy
exposes any partial methods that might help (if you are using C# 3).

If you are doing .NET-to-.NET, note that you don't have to limit
yourself to the proxies; you can also share the .cs (or the entire
assemlby containing your data-contracts / service-contracts) between the
client and the server; this allows you to run the same code at each, but
note that the server shouldn't assume that any such logic has occurred
(since a hostile client could be sending any old rubbish).

Note that in addition to [DefaultValue], DataContractSer ializer also
supports the "bool ShouldSerialize {PropertyName}( )" pattern for complex
optional values, but this won't work at the client if shallow proxies
are used.

Marc

Aug 21 '08 #7

Well, these guys saved us both:
http://www.thoughtshapes.com/WCF/Usi...ametersTwo.htm
( I reference them in my post )

They're the ones to thank.

"Steve Barker" <st**********@n ospam.nospamwro te in message
news:88******** *************** ***********@mic rosoft.com...
Actually, scratch that, the NetDataContract Serializer is actually really
easy
to use, and completely solves the problem.

Sloan: Thanks very much for providing that solution!

"Steve Barker" wrote:
>That's a good point about not being able to stop the client from
instantiatin g an object. Hence, the New() method is not a good idea!

The sort of logic I'm talking about is stuff like checking business rules
(a
la Rockford Lhotka). I want each class to maintain a set of which
business
rules have been broken. (The class exposes an IsValid property.) For
this, I
need certain code to run in the constructor of the class when it gets
back to
the server, otherwise the rules structures are not instantiated.

It sounds as though I'm going to have to run the full class code in the
client as well as the server, which is a shame as standard WCF seems
quite
elegant in that you don't have to have knowledge of the class at the
client.

I don't understand what you mean by "bool
ShouldSerializ e{PropertyName} ()".
Can you point me in the right direction of an article on this please?

Sloan mentions that it's possible to get WCF to serialise the entire
class
and send it down the wire, rather than sending a proxy. I think it has
something to do with NetDataContract Serializer. I'm having trouble
understandin g the articles I've read on this, so can you help me with
this at
all?

Many thanks,

Steve.

"Marc Gravell" wrote:
Well, you can't stop the client doing what it likes... and by
definition
proxies don't have any logic. You also can't take away the default
ctor,
or the serializer will break.

So you *could* have a New() method on the service, but it seems
overkill. What sort of logic did you have in mind?

Alternatively, you could create a method in a partial class at the
client (in a separate file for the service, but same types) that
creates
a New() method. You could also check whether the WCF-generated proxy
exposes any partial methods that might help (if you are using C# 3).

If you are doing .NET-to-.NET, note that you don't have to limit
yourself to the proxies; you can also share the .cs (or the entire
assemlby containing your data-contracts / service-contracts) between
the
client and the server; this allows you to run the same code at each,
but
note that the server shouldn't assume that any such logic has occurred
(since a hostile client could be sending any old rubbish).

Note that in addition to [DefaultValue], DataContractSer ializer also
supports the "bool ShouldSerialize {PropertyName}( )" pattern for complex
optional values, but this won't work at the client if shallow proxies
are used.

Marc

Aug 21 '08 #8
Strictly speaking, the main difference here is that
NetDataContract Serializer simply *forces* you to have the same CLR
type at each end. You can get the same result with regular
DataContractSer ializer (and hence retaining portability) simply by
*choosing* to have the same CLR type at each end, either by assembly
sharing or copying the class file(s). It doesn't actually transmit the
runnable type - just the metadata to resolve it at each end.

ShouldSerialize {foo} is just a more complex way of expressing things
like default values, but where the decision isn't just a comparison to
a constant; it doesn't sound like this is going to be hugely helpful
in this case (but depending on which problems you were trying to
solve, it might have been).

Marc
Aug 21 '08 #9
Hi Steve,

WCF use service description WSDL to expose its service interface and data
contract, it is reasonable that only those public parts(propertie s and
method signature) can be got by the client-side. The default
implemeation(su ch as the validation logic in method) is implemeation
specific which is not conpliant to service oritented or contract based
development.

For your scenario, if you do want to let the client-side also use the same
classes as the WCF service, I suggest you directly let the client side
proxy use the same classes as service(separat e those reusable classes into
a single class library project). And when you create the client WCF proxy,
you can specify the assembly in which you want to reuse classes. You can
refer to the following articles and refernce for more ideas about sharing
and reusing types in WCF service and client proxy:
#Type sharing in WCF service reference
http://blogs.msdn.com/lifenglu/archi...-in-wcf-servic
e-reference.aspx

#What's New for WCF in Visual Studio 2008
http://msdn.microsoft.com/en-us/magazine/cc163289.aspx

#Sharing WCF Collection Types between Service and Client
http://www.codeproject.com/KB/WCF/WC...peSharing.aspx

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsof t.com.

=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/en-us/subs...#notifications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://support.microsoft.com/select/...tance&ln=en-us.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

--------------------
>From: =?Utf-8?B?U3RldmUgQmF ya2Vy?= <st**********@n ospam.nospam>
Subject: WCF Question
Date: Thu, 21 Aug 2008 06:12:00 -0700
>
WCF Question

Hi guys,

I’m pretty new to WCF, and have a basic question about how it works.
I’m
>trying to use WCF to write an “SOA-system? and am having a few
problems.
>
The following analogy explains what I’m trying to do. I have a very
simple
>class:

[DataContract]
public class MyClass
{
private string data = "default data";

[DataMember]
public string Data
{
get
{
return data;
}
set
{
data = value;
}
}
}

This is exposed via a WCF Service:

[ServiceContract]
public interface IMyClassService
{
[OperationContra ct]
void Add(MyClass item);
}

public class MyClassService : IMyClassService
{
public void Add(MyClass item)
{
//Do something with the data...
Debug.WriteLine (item.Data);
}
}

As you can see, this is extremely simple. I’ve put the service in an
ASP.NET
>web application, created the correct web-config entries, included an svc
file
>with the correct tag, and the service does work. I’ve consumed the
service
>via a console application (by creating a service reference). I have the
following (very simple) code in the console application:

public static class Program
{
public static void Main(string[] args)
{
MyClassServiceC lient client = new MyClassServiceC lient();

MyClass myClass = new MyClass();

client.Add(myCl ass);
}
}
Aug 22 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3096
by: Mohammed Mazid | last post by:
Can anyone please help me on how to move to the next and previous question? Here is a snippet of my code: Private Sub cmdNext_Click() End Sub Private Sub cmdPrevious_Click() showrecord
3
5029
by: Stevey | last post by:
I have the following XML file... <?xml version="1.0"?> <animals> <animal> <name>Tiger</name> <questions> <question index="0">true</question> <question index="1">true</question> </questions>
7
2654
by: nospam | last post by:
Ok, 3rd or is it the 4th time I have asked this question on Partial Types, so, since it seems to me that Partial Types is still in the design or development stages at Microsoft, I am going to ask it differently. FOUR QUESTIONS: The background: I got three (3) files
3
3076
by: Ekqvist Marko | last post by:
Hi, I have one Access database table including questions and answers. Now I need to give answer id automatically to questionID column. But I don't know how it is best (fastest) to do? table before rowID answID qryrow questionID datafield 1591 12 06e 06e 06e question 1593 12 06f 06f 06f question 1594 12 answer to the question 06f
10
3418
by: glenn | last post by:
I am use to programming in php and the way session and post vars are past from fields on one page through to the post page automatically where I can get to their values easily to write to a database or continue to process on to the next page. I am now trying to learn ASP to see if we can replace some of our applications that were written in php with an ASP alternative. However, after doing many searches on google and reading a couple...
10
3711
by: Rider | last post by:
Hi, simple(?) question about asp.net configuration.. I've installed ASP.NET 2.0 QuickStart Sample successfully. But, When I'm first start application the follow message shown. ========= Server Error in '/QuickStartv20' Application. -------------------------------------------------------------------------------- Configuration Error Description: An error occurred during the processing of a configuration file
53
4059
by: Jeff | last post by:
In the function below, can size ever be 0 (zero)? char *clc_strdup(const char * CLC_RESTRICT s) { size_t size; char *p; clc_assert_not_null(clc_strdup, s); size = strlen(s) + 1;
56
4754
by: spibou | last post by:
In the statement "a *= expression" is expression assumed to be parenthesized ? For example if I write "a *= b+c" is this the same as "a = a * (b+c)" or "a = a * b+c" ?
2
4272
by: Allan Ebdrup | last post by:
Hi, I'm trying to render a Matrix question in my ASP.Net 2.0 page, A matrix question is a question where you have several options that can all be rated according to several possible ratings (from less to more for example). I have a question object that has two properties that contain the collections Options and Ratings. now I want this kind of layout: --- Rating1 Rating2 Rating3 Option 1 () () ...
3
2548
by: Zhang Weiwu | last post by:
Hello! I wrote this: ..required-question p:after { content: "*"; } Corresponding HTML: <div class="required-question"><p>Question Text</p><input /></div> <div class="not-required-question"><p>Question Text</p><input /></div>
0
8465
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8383
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8895
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8809
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8658
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7407
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5682
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2797
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2032
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.