Archive

Archive for the ‘.NET’ Category

ASP.NET AJAX AutoCompleteExtender not working

January 19th, 2010 joelhainley 2 comments

I was working on some new features for a client recently and they had a need for an AutoCompleteExtender on one of their forms. I hadn’t used the AutoCompleteExtender yet so I read through the documentation, coded up a webservice, and added  the appropriate items to the page and ran the app. When I tried typing into the TextBox that the AutoCompleteExtender was pointed at, nothing happened. In this posting I will detail the things that I looked at, and try to put together an accurate guide to making sure you’re AutoComplete works. I tried some of the “tips” that are out there after I had things working and they don’t help. So hopefully this will be a bit more definitive and useful than what I came across.

The first thing that I looked at was the method signature of the webservice. The documentation indicates that you need to use one of the following method signatures :

public string[] GetCompletionList(string prefixText, int count) { … }

..OR..

public string[] GetCompletionList( string prefixText, int count, string contextKey) { … }

What the documentation doesn’t tell you is that the name/spelling/capitalization of the method signature must match EXACTLY. If you decide that you don’t like the camelcase on the prefixText and want to use prefixtext instead….IT WON’T WORK. So make sure you have those signature matching correctly. I have seen some indications on the internet that you should use a static method such as :

public static string[] GetCompletionList(string prefixText, int count) { … } // !!! DON”T DO THIS !!!

DON’T DO THIS. It doesn’t work. Only the exact methods defined in the documentation and shown above will work.

Back to my project, I get these methods defined properly, compile the project, go to my textbox start to type and still I get NOTHING. So I look over the documentation and see some information about the class/method attributes that must be added. The documentation shows the following :

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] GetCompletionList(
string prefixText, int count) { … }

What they don’t show in the documentation is that you need to also add the following to the class definition

[System.Web.Script.Services.ScriptService]

So I make these changes and run the application again, and STILL it doesn’t work. I’m stumped. I put a break at the webservice method and run again and it’s not even hitting the webservice. After a little bit of digging I come across Adding ASP.NET AJAX Configuration Elements to an Existing Web Site and a lightbulb goes on. This project was not setup as an AJAX.NET site, in fact it predates ASP.NET AJAX by a couple of years. Sure enough as I start to dig through the documentation I notice mappings to handlers for the webservice calls. So I follow the changes specified and run the site and it worked!

It took me a while to get this figured out, and I suspect there might be a few others out there that might have some problems getting this working. Below is a complete class that you can use as a reference. I haven’t included any of the code defining the AutoCompleteExtender because the documentation seems sufficient and I didn’t have any problems. There is also a video on the ASP.NET AJAX site that walks you through configuring your first AutoCompleteExtender and does a good job, as long as your site is configured properly!

Good luck!

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using DALInterface;
using CGWeb.framework;

namespace CGWeb.webservices {
///


/// Summary description for NewDXCompletion
///

///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class NewDXCompletion : System.Web.Services.WebService {

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] GetCompletionList(string prefixText, int count) { … }
}
}

C# Partial Classes and NUnit

April 13th, 2009 joelhainley 1 comment

Shad, a fellow developer and good friend, and I were hiking a great new loop I found in Mt. Diablo State Park the other day and after solving the rest of the world’s problems we eventually came around to talking about things that were driving us nuts in our current projects. We both had recently found ourselves with code that was initially a quick and dirty library with a “Button 1″ interface. ( You know the type, programmer’s make them. They have a single command button on them and you click them and then they do stuff..and never notify you when they are done, and don’t resize and a host of other things that a normal UI should have ). These “Button 1″ quick and dirty apps have a nasty habit of turning themselves into indispensible tools for production/operations stuff.

The big problem we were both having was that while the apps were decent enough for their initial use we were being asked to extend them and both of us wanted to do some refactoring of the application before we released them into the wild. The best approach for this sort of thing is to develop unit tests so that, once refactored, we could be sure that we hadn’t broken anything important.

The biggest problem with dropping unit testing into an application after the fact is that sometimes you run into problems where you have to refactor just to get the unit tests access to all of the routines that you want to test. This isn’t an ideal situation, as you quickly end up wondering if you are breaking things just trying to get some unit tests built that are supposed to ensure you aren’t breaking anything. So you start wondering if instead of refactoring if you simply make functions that wrap your private functions and expose the behaviour might be the answer, pretty soon you have stuff everywhere and you wonder which is your testing code and which is your unit testing code to make all of this possible. Madness.

As we dropped off of the fire trail back into a heavily wooded area with a nice creek, it came up in conversation that perhaps partial classes were the way to go. If you haven’t used c# partial classes, you will. You can write class code in multiple files and yet at compile time it is assembled into a single logical unit. Several days later I had some free time and was able to verify that this would indeed work, I could drop all of my unit testing code into a single file that would provide all of the unit testing logic and wouldn’t muddy up the existing class. Furthermore, with a couple conditional complilation statements I could get rid of all of the unit testing code from the final release of the new library.

This is obviously not the approach you want to take if you can avoid it. It is arguable that you do not want your classes invaded in such a way for the purposes of unit testing. This is something you can work around if you use unit testing from the beginning, but what if you inherit a project and it doesn’t have any unit test capabilities built into it? What if the way that the classes are structured make unit testing pieces of the application difficult? Do you just plow forward and hope for the best? I hope not, and hopefully this stop gap measure to get unit tests built into the classes so that you can test existing functionality is the way to go. With these “nunit partials” in place you should be able to then start refactoring the rest of the application to be a little bit better structured for unit tests without having to risk dropping anything.

Categories: .NET, c#, programming Tags: , ,

Example of Proxying Binary Data With ASP.NET

February 28th, 2009 joelhainley No comments

Recently I was working on a project and needed to proxy a request to a website that was returning a binary file.  I ran into some problems with my first pass at a solution. I believe the problem was a consequence of proxying binary data without getting at the underlying streams. I’m not sure how often I’ll need to do this, but I thought it might be useful to post here for others to know about in case they ran into the same problem I did. So here’s the code that worked for me, hopefully it’ll work for you too.


HttpWebRequest req = (HttpWebRequest)WebRequest.Create(”http://to.some.binary.data”);
req.Timeout = “blah”;
req.Method = “GET”;

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream reader = resp.GetResponseStream();
// you might want to set your responses content type here
System.IO.Stream r = Response.OutputStream;

int Length = 256;
Byte [] buffer = new Byte[Length];

int bytesRead = reader.Read(buffer, 0, Length);
while(bytesRead > 0){
r.Write(buffer, 0, bytesRead);
bytesRead = reader.Read(buffer, 0, Length);
}


Hope that helps.

Alternatives to Throwing Exceptions to Flex/Silverlight Clients From a .NET Web Service – part 2

February 7th, 2009 joelhainley No comments

In part 1 of this article I argued that exceptions sent “over the wire” to flex/silverlight clients from a webservice weren’t necessarily the right way to put things together. I argued that that exposing your clients to raw exceptions happening in your server was not elegant in the same way that throwing raw exceptions to a user in a windows desktop app was not elegant. In talking about the last article with some people I realized that I needed to make a point. There are times when an exception is appropriate, and I’m not advocating avoiding exceptions altogether. My point was that I felt people were relying on exceptions too heavily when a more appropriate method might be possible.

Let’s take a look at input validation to see what we mean about relying too heavily on exceptions. Validation is a bear, you want to try and have your validation rules in one spot only. This way you can avoid the chore of duplicating validation logic on the client and the server. This seems to be one of the main reasons people are looking at bubbling exceptions over the wire because if they can simply put the validation logic in the server side, then they can throw an exception back to the client and deal with it there. It solves the the problem of duplication of validation logic and allows developers to deal with validation errors in the same way that they do within desktop application environments.

The question now becomes can we avoid exceptions and still provide for a rich validation environment? I believe that we can and I’m going to spend the rest of this article describing an approach. It may not be the best approach, it may not be the only approach, but it was worked well for me on the last few projects and enough people I’ve talked to about the approach seem to feel that it’s powerful enough to consider for their future efforts along these lines.

In order to provide a framework upon which to hang our theory let’s consider a simplified method of a web service named “CreateAccount” that takes as it’s only parameter an Account object.

Account UML

When we want to create a new account we will fill out the information about the account as described and then pass it to the CreateAccount method of the webservice. However, instead of just having a void for the return value and throw exceptions if there are errors you simply use a response object such that the method signature would look something like the following :

CreateAccountResponse  CreateAccount( Account acct)

This is certainly not a new concept. Response objects litter many namespaces, but in this particular situation they allow us to avoid having a lot of exceptions flying out of our webservice and doing all sorts of ridiculous plumbing hacks to get it all to operate nicely.  Now let’s take a quick look at the CreateAccountResponse class and see what it looks like, then we can talk about how a response object allows us to avoid duplicate validation and exceptions. Below is the UML for the CreateAcountResponse object

We see that this class mmics the Account class pretty closely with the addition of a couple of routines that would be needed to actually communicate results. The Success flag would indicate whether the account creation was successful and the error message would only be filled out if there was a particular error that you wanted to communicate to the user such as “You do not have the rights to create accounts” or something along those lines. The other fields would be filled out if there were problems with the validation of the individual fields of the account object. This would allow us to have all of the validation/error messages specified on the server side in a single location and still be able to get the information out to your users. Such that if you require the state field to be only 2 characters long and someone puts in 4 you could set the success flag to false and then add error text to the State field of the response object that could then be displayed to the end user.

WIth this approach if there was an exception generated in the webservice, we could trap it server side and provide the appropriate message to the CreateAccountResponse object and not have to require the client to exception handling just to know what is happening.

Now one of the complaints  that I have heard about this approach is “but now you have to create all of these response objects”. Well yeah, but one way or another you’re going to have to write some code to deal with errors and wouldn’t it be nice if you could deal with the errors and the error messages in a single place? Also you could simply create a generic results object that would suffice for most of the calls that you want to make. Then again consider that in some of the more mature environments such as .NET WebServices  you can easily create webservices that provide this sort of functionality and the WSDL’s and whatnot are all created for you.So it’s not nearly as much work to do this as it could be.

What about the overhead of all of these custom classes? Is it really any more overhead than the throwing of exceptions? Exception throwing, and handling are expensive operations. I find it a little be cleaner to my thinking because now you have a clear and concise definition of what you need to program against when you are dealing with your WebService’s API.

I’m not saying this is necessarily the best approach for all occassions, and I’m not really down on exceptions in general, or even for web services. However I think that there are many times when the extra effort you have to go through just to get robust exception handling done will lead you into a lot of needless efforts. Especially if you are just trying to provide validation/failure information back to the client applications.Keep in mind that what I’ve presented here isn’t a blueprint, it’s more like a pattern of how you might consider structuring your webservices in certain situations.

Your mileage may vary.

Silverlight : Communication Exception was unhandled by user code

February 4th, 2009 joelhainley 4 comments

Ran into the following error the other day :

An error occurred while trying to make a request to URI ‘http://localhost/T2WS/AdminServices.asmx’. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. Please see the inner exception for more details.

The error message was self-explanatory but it didnt’ solve the problem. I had my cross domain file setup appropriately and yet I was still receiving the error. As seen below the stack trace didn’t offer much help either:

System.ServiceModel.CommunicationException was unhandled by user code
Message=”An error occurred while trying to make a request to URI ‘http://localhost/T2WS/AdminServices.asmx’. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. Please see the inner exception for more details.”
StackTrace:
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.ClientBase`1.ChannelBase`1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
at T2SL.T2AdminService.AdminServicesSoapClient.AdminServicesSoapClientChannel.EndgetAccountList(IAsyncResult result)
at T2SL.T2AdminService.AdminServicesSoapClient.T2SL.T2AdminService.AdminServicesSoap.EndgetAccountList(IAsyncResult result)
at T2SL.T2AdminService.AdminServicesSoapClient.EndgetAccountList(IAsyncResult result)
at T2SL.T2AdminService.AdminServicesSoapClient.OnEndgetAccountList(IAsyncResult result)
at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)
InnerException: System.Security.SecurityException
Message=”"
StackTrace:
at System.Net.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
InnerException: System.Security.SecurityException
Message=”Security error.”
StackTrace:
at System.Net.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
at System.Net.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)
InnerException:

Still no luck, i spent some time fiddling with the clientaccesspolicy.xml file but it didn’t seem to be the problem. After a bit of digging and avoiding the obvious, it finally hit me right between the eyes. I had setup the Silverlight project to be the startup and it was running the file locally, instead of running it through the web project I had setup to wrap Silverlight with.

Once I changed the startup project to the Web project and the file to the Silverlight testpage everything worked just fine and dandy except that the Silverlight project wasn’t updating. Looking through the Silverlight project properties I was able to point the build for the Silverlight “executable” to the Web project’s ClientBin directory and everything fell into place.

I just mention this hear because I’m sure I’ll forget how I solved this problem the next time I run into it. ;-)