How do I make a client-side helper class in Silverlight? - c#

In Silverlight, I call my Silverlight-enabled WCF service asynchronously to retrieve, say, a list of values for a combobox. On the server, I cache these values for performance. But I want to cache them on the client to prevent the unnecessary round-trip.
Now, I understand how to use local storage to cache them except that I do not want all of the "if in local storage, return local storage values else get values from server asynchronously" stuff in the code-behind of my xaml app.
So, I tried moving that code to a helper class but the async calls need a callback which is where I get lost. I tried passing a generic EventHandler into my helper class but the helper class method really needs to be static. So, that is throwing me off. Will my helper method need to be non-static, and, if so, do I need to worry about thread safety? Aaarh! Too many questions! Haha. Anyway, I bet some smart person out there can tell me a better way to approach this almost immediately! Thanks in advance.

I've done one major Silverlight app in the past. It has taught me that you shouldn't fight against the system.
If I'm not mistaken, Silverlight itself uses the browser network layer to connect to the internet. So you can still leverage--and Silverlight still respects--things with proper cache-control headers and such.
So just from my experience, I'd suggest that you try to make the server component (WCF server) do proper output-caching ala ASP.NET style and the network layer in Silverlight and the hosting browser will handle caching automatically for you.
You may have better luck with RESTful WCF mode since you can leverage proper HTTP caching throughout, see this blog post: REST in WCF – Part X – Supporting Caching and Conditional GET for a start.
This also makes your code less complex, since you don't have to add yet another complex layer to your system and tame it to work with the confusing XAML binding system.

Related

Moving SqlDataSource to class file ASP.NET

I have been tasked with moving all SqlDataSource objects out of an ASP.NET pages aspx files and putting them into a separate class file but am lost. Is there a way to create a SqlDataSource object in a separate class and assign query strings to the SelectCommand, DeleteParameters, InsertParameters, etc?
To where you can call the object on a separate page rather than have the code in the aspx?
Yes, you can do that. I would recommend that you move all the database IO to a web service.
I also want to add that this is a very good step that you are taking, as far as the security of your application. Separating your data access from your user IO like this is something I consider to be a must-have security measure. Done right, you will bump up the security of your application significantly.
You can create a WCF web service easily enough. There are plenty of tutorials on the web, and I'll be happy to give you pointers as you go along. The web service would have CRUD (insert, select, update, delete) operations. You can then create an "Object" type datasource on the web page, that points to your web service, and the elements on the page can get their data from those object datasources. You can also instantiate the web service in your code behind, and use it to manipulate the data. When you create the object type data sources, you will specify the service methods that correspond to each of the commands (select, insert, update...). Hope this points you in the right direction, and feel free to ask me more in the comments, or you can initiate a chat and I will give you my email where you can holler at me.
As already mentioned, it is possible to move the SqlDataSource controls out of the WebForm. I'll assume for the moment that your current code declares these controls in the .aspx file. You could change to an imperative approach, for example, and instantiate the datasource controls in an event handler of a WebForm's code-behind class, but you don't gain much by doing so. Indeed, you could even move a lot of the code that does the instantiation into a helper class that is called by the code-behind class, but this doesn't get you much further.
The original intent of the DataSource controls was to provide developers with a way to create rapid prototypes / proofs of concept. But these controls aren't really meant for production systems. They are a violation of the separation of concerns and make unit testing difficult, if not impossible.
In some ways, the DataSource controls can be easier to work with (say, in conjunction with a GridView control). But, this convenience comes at a price, which probably helps explain (in part) why you're being asked to do something with the controls. It's unfortunate that at when ASP.Net 2.0 (WebForms) was released in 2005, the literature that was published at the time heavily promoted the use of these DataSource controls. The community has learned since then that the production value of these controls is questionable, unless you are working on simple systems that don't need to evolve much over time.
As was mentioned by Anon316, you could use a web service to handle the CRUD operations. However, this solution might not be what you really need. Additional overhead is incurred by using a web service (i.e., additional HTTP requests to the service). Having your application make direct calls to the database can still be a very good approach.
With that said, consider creating a separate class (or classes) that provide data access facilities (e.g., a Repository). Entity Framework, for example, makes creating this kind of thing fairly straightforward (and there are many other data access libraries available in the .Net ecosystem). Be prepared for adding more code to the code-behind classes of your WebForms in order to make them interact with your Repository (or other Data Access) class(es). The benefit you'll gain is more testability and reuse of your data access code. Consider putting your data access class(es) into a separate project in your solution (to start).
Whether you create separate data access class(es) in your solution or a web service, you still have significant refactoring to do in order to move away from the DataSource controls. So, again, be mindful of the additional overhead involved in using a web service, recognizing that a web service tends to make sense when you have multiple clients (e.g. web and mobile), not when you only have one.

What is a typical way to create your own static error code list in C# ASP.NET?

I'm trying to find the most efficient way to create an error code list for my web service so that when certain problems occur my client app will know what it is. I don't want to return a lengthy string, so I'd rather use simple numbers. I'm just curious as to how some of you would create your own error code table for an asp.net app. Would you just create a bunch of constants, or an enum type in your web service? Or would you create some kind of class that only holds constants? I'm not sure what the best way to handle this would be. I don't want to instantiate a class just for errors codes every time someone hits the web service.
Edit: I should have been a little more specific. The web service does use data contracts, but doesn't use WCF. I'm using a home brewed implementation of JSON-RPC, which requires that an error code be stored in the response json.
Just a thought for you, but ... don't worry about creating the class, the garbage collector will dispose of it when you no longer need it, and if you use it often enough, then it will stay in the applications memory in Jit form so it will be performant!
Personally, I try to not worry that much about "performance" to the extreme as it is typically not even noticeable...
However, if you are worried, then you should look at creating a single static class which can be used application wide and instantiated on start up and hold the constants there as then a single in memory class will be used saving on memory and any perceived performance hit.
Best wishes
Matthew
Assuming you mean the WCF type of web services, you can use FaultContract to specify different errors and how to handle them on the client side.
You are not programming in C, why error codes?
Web service is broad here but I assume you mean WCF?
Anyway WCF throws a FaultException which bubbles up to the client and this is a lot better than using error codes. Error codes don't tell me anything, and can be prove to be a PITA to maintain later.
But if a FaultException occurs there are lots of information that I can glean from the object.
FaultException (or SomeException) > Error Code.

LINQ to SQL in Silverlight client

Okay, so I have this Silverlight client program. I'm not allowed to use the web project, but I do need to be able to read from an SQL database for my data.
Some internet searching brought me to LINQ to SQL and the System.Data.Linq.DataContext object, as well as SQLMetal.exe. I have created my data context object from the meta data in a remote SQL database and the code looks okay (from what I can tell - all the right names and types seem to be there).
What I wanted to do was add this into Silverlight, but I realised, on importing the code, that you can't use System.Data in a Silverlight application, which sort of rules out having this code in the Silverlight client itself. Now this is annoying because a DataContext quite conveniently comes with properties which are tables and such like (I find those really convenient in Silverlight).
So I can't do it the 'normal way'. I can do it with a WCF service, but... well, here's where I could use some advice. I can create a WCF service with asynch calls, but I'm not really sure in what way to wire up the DataContext object. I mean... I need access to the classes in there within my Silverlight application (for my entities in the database) (and I'm not quite sure how to do that - help there would be appreciated). Then to synchronise it all up? Well, I could use some suggestions. For example, before, I have an exposed ObservableCollection. In its getter, it repopulated itself with the contents of, for example, Context.Customers. This made things nice and easy, but I can't see a way of doing something like that now. If I made a call to an asynch service for every 'get', surely this would be unacceptably slow.
If you could help me pick my way through this, I would be grateful. Thanks.
You definitely need to read about Entity Framewrok and couple articles about using WCF RIA + EF in Silverlight applications.
Hope, that will help you.
As mentioned above, you can use RIA services.
But more importantly... you should never use the classes that are generated in LINQ to SQL or EF in your client application. Your client application should only know about and use Domain Layer objects. Your datacontext and the types it uses should stay buried behind a repository pattern that gives you back Domain types.
Your client, whatever that may be (Silverlight app, WPF app, etc) only needs to (and should only) use these domain types. This is part of the whole separation of concerns and SOLID principles. Because I can guarantee you at some point in the lifecycle of the app you will swap out your source for data, so you may end up using Entity Framework, or NHibernate to talk to the db instead, in that case your client would be hard-wired to your LINQtoSQL types, and you wouldn't be able to swap out the ORM layer without breaking the client.

database access from multiple applications

I have a windows form application(c#) and an asp.NET web application which both access Sql Server database. I want to centralize the database access. Which metedologies should i follow? What is the common approach to this issue?
Writing DAL and Model Libraries and using them in both application?
Writing WCF service including DAL model and using this service with both applicaiton?
None of the above?
Can you give me any idea?
Thank you.
I would go with the WCF approach. Keep in mind that when (not if, when) you have to make changes that pertain to one app, but not the other (yet), you will have to account for that in the common layer, so using interfaces may make your life a little easier.
The cleanest way is to wrap the DB with a WCF services.
If you don't write large amounts of data in one go you can use a WCF Data Service; this directly wraps an Entity Framework model and you can configure access to tables and methods in various ways.
What you want is to have one place where the DB is accessed, so that if there is an issue, you can fix it in one location, for instance.
Furthermore, if you want to log all calls to a particular table, for instance, the only way to make sure that will be done is by centralizing all calls to the DB this way and not allow anybody direct access to the DB.
Wrap the service, then keep the connection string secret.
I think using the SOA approach is really better (WCF or WebServices with a DAL layer) because this way you don't need to publish your DAL dll with the Windows Forms exe. Then, all changes to your data model will automatically happens to your both UI clients.
Remember that this can cause its own problems:
Concern with security so that your Services cannot be accessed directly by URL, allowing someone to run your methods.
Concern about maintenance, because changes in data layer that needs to affect only one interface will be more difficult to control and needs to be better planned before (with the creation of new methods specific to certain intercace).
Decrease in performance, because the HTTP access is always more costly than direct communication with a dll.
Risk of lack of communication with the server, something that is expected to ASP.NET but requires additional concerns in the Windows Forms client to behave properly in these cases.
Option 1 seems simpler and I would do the same.
Option 2 with WCF will add additional code to your product and hence maintenance. Also this would mean an additional layer as well.
Corporate programmers like the second option (WCF service including DAL).

Software Design & Web Service Design

I'm about to design my Web service API, most of the functions of my API is basically very simular to my web application.
Now the question is, should I create 1 single method and reuse them for both the web application and the web service api? (This seems to be the logical solution, however its very complicated; it's much easier to duplicate the method used by the web application, and keep both separate, ie one method for the web application and one method for the web service.)
How do you guys do it?
1) REUSE: one main method and reuse them for both web application and web service application (I like this but it's complicated)
WebAppMethodX --uses-->
COMMONFUNCTIONMETHOD_X
APIMethodX ---uses---->
COMMONFUNCTIONMETHOD_X
ie Commonfunctionmethod_x contains reusable set of common features
PRO: less code, less maintenance, less bugs.
CON: very complicated
2) DUPLICATE: two methods, one method for the web application and one method for the web service.
WebAppMethodX
APIMethodX
PRO: simple
CON: duplication = more code, more maintenance, more bugs!
Your use case will very likely be different for your public webservice API than for your internal application API. Create a common service project / tier and use that same tier from both your web app and your public-facing webservice API. Create a separate http-invokable method for each of your web app and your webservice.
It comes down to there being
1) different security concerns. For instance, it is nice (often required) to provide a sample client application making use of your public API so that others can easily get up to speed with what you've provided. That client API may need to pass object constructs that you provide them that have been stripped of internal, secure logic/content. (Remember that compiled C# might as well be clear text with Reflector!)
2) different needs and constraints. For instance, for an internal application call you're going to sometimes enforce different business rules vs. your public facing webservice API (often with the latter being much more constrained to scope).
If you design your business logic into your service layer and invoke those classes/methods well from your web project and your webservice project respectively you're going to have a lot of code reuse anyway without trying to overcomplicate things by mixing use cases.
One method. Otherwise when you find a bug and fix it in one, then forget to in the other... you will cry.
One method, in the web service, and have your web application call it.
I don't understand what "one main method" for both means. Web applications don't have a main method; they're deployed to an app server.
One other point to note: you should write your service in terms of a POCO interface. Once you do that, deployment becomes a choice you make.
It depends..
Normally, I would separate them. This way you remove interdependency between two high level processes. code reuse is good within a process but sometimes you want to be able to use a different app on the same service.
If the two are highly dependant on each other, however, you will want to reuse the same functions so that changing it in one place will change it in another. Thus avoiding more potential issues with the development process.

Categories