using reference parameter for a web method in .NET - asp.net

I am working on a web application that consumes a web service. Web service is written in .NET.
I want to know whether using a reference parameter for a Web method is a good practice or not?

You can use ref and out params with WCF services, but under the hood they're wrapped up.
Anything passed to a WebMethod or service has to be serialised - you can make it behave as if it is a ref or out by wrapping it in something that sets the values back, but this is messy.
You're better off with a record class - a simple serialisable class that's basically just a list of auto properties that's the return of the WebMethod.
This results in extra classes, but is much easier to maintain.

It is best to have the ws message based.
You can still be doing so implicitly when you use multiple parameters, there is still the message you are receiving with those. Just keep them separated, if you need multiple outputs return a simple result class for the operation.

Related

Javascript calling C# with multiple parameters

I used the following - https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/hybridwebview/ to implement a hybrid webview. All works fine expect the part where I need to call the C# function from Javascript. The C# handler gets called but from the article, it seems like I can only get a single parameter passed to C#. So message.Body.ToString() gives me the arguments passed from Javascript. I however want to pass atleast to arguments. Can anybody please show me how I can achieve this.
It looks like you can only pass one parameter through. Hence you just need to develop your own way to pass more information through. You could for example create a class and serialize it in JSON, then deserialize it at the other end. JSON serializers and deserializers are widely available in .NET and JS, this shouldn't be much of a problem at all.
Or if the data is really simple, e.g. 2 numbers, you could do 1#4, and split via the hash at the other end.

Selective Explicit Loading in WCF Data Service

I'm about to implement a web service for my database, perhaps using WCF Data Services. Some of the objects I need to make available have child objects that need to be present for the objects to be useful. But because of lazy loading in the Entity Framework, those child objects are not going to be automatically loaded.
I'm going to be calling this service using JSON, and I don't want to have to specify the $expand option in each call. And it's not clear to me where I would use the LoadProperty method (same link), since I'm just writing the InitializeService method and letting the framework do the rest.
Is there a way to configure it to explicitly load some child objects and not others?
WCF Data Services currently doesn't support auto-expand on the server. The client always has to ask for expansions.
You could implement some kind of a workaround around the WCF DS, by modifying the incoming request. So for example if the client sends request for ~/Products you could modify it before it gets to WCF DS and let it process ~/Products&$expand=Category and that way effectively achieve auto-expand. But for such a service to be robust, you would have to parse the query URL and only add the expand if there's not already one in there and so on.
The other way is if its always necessary for the child object to be present, can we make the child object complex types instead of entities, so that they always come along with the parent. Is there a strong reason for the child objects to be individual entities?
Hope this helps.
Thanks
Pratik

ASP.NET. Is it better to pass an entire entity to a method or pass each property of this entity as parameters?

We're developing a business ASP.NET application. Is it better to pass an entire entity to a method or pass each property of this entity as parameters? What is the best practice?
Case 1. Pass Customer entity to a manager - InsertCustomer(Customer cust)
Case 2. Pass each property as a parameter - InsertCustomer(string name, string address...etc)
P.S. We're using Entity Framework as our data access layer
Pass the entire entity, not only for reasons given in the other answers, but generally methods with long parameter chains are bad. They are prone to error, and tough to work with from a development standpoint (just look at Interop with Office)
In general, if I see I am getting too many parameters (usually more than three), either I have a method trying to do too much, or I explore ways of encapsulating this data in a struct.
You should pass the entire entity as when you update the entity, e.g. add or remove members you do not have to update all your method calls in all your layers. You only need to change your datalayer and the layer where you are consuming the entity. asp.net is Object Oriented and therefore you should orientate your code around your objects
The whole concept of object orientation requires objects to be passed around. If all is happening internally I would go with this.
If this is being posted to a webservice / across a network etc you would need to serialize, and hence may find it better to pass each individual parameter, especially if the receiving framework is different.
Don't forget your Strings etc are all objects too.
I agree with another poster, passing a whole entity "encapsulates" everything so that it can be updated/modified so you have less to worry about.

HttpService Vs Remote Objects

I have a flex application and need to show the real time data into the chatrs and datagrids.
Eralier we are used Httpservices to showing the real time data and historical data into charts and datagrids. But now we are going to replace the Httpservices to remote objects.
So which places generally need to change. I have a little bit idea about remote objects.
Thanks,
Ravi
If you need to display real time data (or "near real time") you should use some kind of pushing mechanism - take a look on BlazeDS and read about polling and streaming.
If you just need to replace your webservices with remote objects you will need to replace the code dealing with the xml response (extracting data etc) with the code dealing with the objects returned by the remote calls. It is not mandatory to use strongly typed objects, but it will help.
If you are going to replace your HTTPService with RemoteObject, some questions you need riposte yourself.
What framework are you going to implement, if any then check their RemoteObject Invoker Tag if any.
Your resultEvent and FaultEvent will vary according to the framework you are going to apply.
If you are going with Flex default RemoteObject
Then you need to replace all your HTTPService with RemoteObject tags.
Your backend code also requires some changes with business logic should get into methods with the result of function or method returning an object.
Finally a suggestion.
Instead of going with Remote Objects, why not go with Webservice. You can re use the components somewhere else too.
Updated links about Cairngorm
http://www.adobe.com/devnet/flex/articles/cairngorm_pt5_03.html
http://www.jeffryhouser.com/index.cfm/2007/2/19/Learning-Cairngorm-Part-3
http://www.asfusion.com/blog/entry/hello-world-cairngorm-example
http://justjoshn.com/entry/contact-manager-part-2-cairngorm-example
Thanks

How do I mock/fake the session object in ASP.Net Web forms?

Is there a way to mock/fake the session object in ASP.Net Web forms when creating unit tests?
I am currently storing user details in a session variable which is accessed by my business logic.
When testing my business logic in isolation, the session is not available. This seems to indicate a bad design (though I'm not sure). Should the business logic layer be accessing session variables in the first place?
If so, then how would I go about swapping the user details with a fake object for testing?
You can do it with essentially 4 lines of code. Although this doesn't speak to the previous comment of moving session out of your business logic layer, sometimes you might need to do this anyway if you're working with legacy code that is heavily coupled to the session (my scenario).
The namespaces:
using System.Web;
using System.IO;
using System.Web.Hosting;
using System.Web.SessionState;
The code:
HttpWorkerRequest _wr = new SimpleWorkerRequest(
"/dummyWorkerRequest", #"c:\inetpub\wwwroot\dummy",
"default.aspx", null, new StringWriter());
HttpContext.Current = new HttpContext(_wr);
var sessionContainer = new HttpSessionStateContainer(
"id", new SessionStateItemCollection(),
new HttpStaticObjectsCollection(), 10, true,
HttpCookieMode.AutoDetect, SessionStateMode.InProc, false);
SessionStateUtility.AddHttpSessionStateToContext(
HttpContext.Current, sessionContainer);
You can then refer to the session without getting a NullReferenceException error:
HttpContext.Current.Session.Add("mySessionKey", 1);
This is a combination of code I compiled from the articles below:
Unit testing with HttpContext
Faking a current HttpContext
SimpleWorkerRequest, HttpContext, and session state
Unit testing code that uses HttpContext.Current.Session
In ASP.NET, you can't create a Test Double of HttpSessionState because it is sealed. Yes, this is bad design on the part of the original designers of ASP.NET, but there's not a lot to do about it.
This is one of many reasons why TDD'ers and other SOLID practictioners have largely abandonded ASP.NET in favor of ASP.NET MVC and other, more testable frameworks. In ASP.NET MVC, the HTTP session is modelled by the abstract HttpSessionStateBase class.
You could take a similar approach and let your objects work on an abstract session, and then wrap the real HttpSessionState class when you are running in the ASP.NET environment. Depending on circumstances, you may even be able to reuse the types from System.Web.Abstractions, but if not, you can define your own.
In any case, your business logic is your Domain Model and it should be modeled independently of any particular run-time technology, so I would say that it shouldn't be accessing the session object in the first place.
If you absolutely need to use Test Doubles for unit tets involving HttpSessionState, this is still possible with certain invasive dynamic mocks, such as TypeMock or Moles, althought these carry plenty of disadvantages as well (see this comparison of dynamic mocks).
Your instincts are correct---you shouldn't be accessing pieces of the ASP.NET framework from your business logic. This would include Session.
To answer your first question, you can mock static classes using a product like Typemock Isolator, but you'll be better off if you refactor your code to wrap access to Session in an interface (i.e., IHttpSession.) You can then mock IHttpSession.
In Asp.Net webforms, you cannot escape the fact that framework's entry into your code comes from aspx pages. I agree that your business layer should not touch the asp.net specific components directly but you have to have a model's storage container and session in asp.net is a good area. Thus, one possible approach is to create ISessionManager for purpose of interacting inside your business layer. Then, implement the concrete type by using HttpSessionState ... btw, a good trick is to use HttpContext.Current.Session to implement accessors/getters out of the HttpSessionState.
Your next challenge would be how to wire it all together.
One approach is to pass a lambda expression to your code that takes a string (or some other object) as input, and uses it to set either the Session object or a test container.
However, as others have said, it's a good idea to move access to the Session object out of your BLL.

Resources