Tuesday, September 29, 2009
#
in·ane (ĭn-ān') adj. in·an·er, in·an·est
One that lacks sense or substance.
The American Heritage® Dictionary of the English Language, Fourth Edition
Copyright © 2009 by Houghton Mifflin Company.
Published by Houghton Mifflin Company. All rights reserved.
One of the first signs that code needs to be refactored is that it looks complex. Complex solutions are rather easy to come by, but are far less maintainable than their harder to write, easier to read brethren. Like any well-crafted sculpture, it didn’t like start that way, and it requires work to craft that beautiful piece of code. But sometimes you come across code for which there is no reason for the complexity. It appears that someone just wanted to type extra characters throughout their code.
A while back, I analyzed another developer’s code that used a lot of generics. Since nothing was being returned from many of these methods, I decided to look at the signature to discover why the generics were necessary. Here’s one of them.
public static void PrintReport<T>(T report)
{
WriteEvent(report.ToString());
IReport r = report as ClientReport;
if (r != null)
{
//Do stuff
}
r = report as EmployeeReport;
if (r != null)
{
//Do stuff
}
}
Looking at this, you may notice there is absolutely no reason for the generic declaration. There are no constraints on it, so it is the same thing as declaring the parameter as an object. Everwhere this was used, it was calling PrintReport<ClientReport>(report) and so on. I pointed this out to the developer, and said it should be refactored because a) the generic adds no value, and b) there are object oriented solutions that are much better than static methods and casting. Of course, this is what I got back.
public static void PrintReport<T>(T report) where T : IReport
{
WriteEvent(report.ToString());
IReport r = report as ClientReport;
if (r != null)
{
//Do stuff
}
r = report as EmployeeReport;
if (r != null)
{
//Do stuff
}
}
There’s now a constraint! A constraint that has no meaning other than preventing someone from printing an object that isn’t an IReport. Of course, the same thing could be accomplished by making the parameter be an IReport rather than a T. I then showed the developer how the generic adds absolutely no value (I think I saw a grimace as I cut all of those <xReport>s out of the myriad of classes making that call). I then explained how when I see things like casting in a method like that, it makes me consider that perhaps that behavior belongs on the class, perhaps called by a method defined on the interface.
public static void PrintReport(IReport report)
{
WriteEvent(report.ToString());
report.DoStuff();
}
For future reference, inane usage of generics involves using a generic on a method, not involving a parameterized class, where 1) the return type isn’t the generic type, and 2) the constraint isn’t new() or class.
If someone can think of a situation where this is actually useful, post a comment.
Also, another quick lesson. The developer did place PrintReport<ClientReport> in many places, but did you know that this wasn’t even necessary? With generic methods, you get generic inference. The compiler will determine the type for you. This is very handy with LINQ. Without generic inference, you would have to write ugly methods like strings.Where<string>(s => s.StartsWith(“s”)).
Note: Cross posted from
KodefuGuru.
Permalink
Tuesday, September 15, 2009
#
I was tasked with taking this small project stored in TFS and compiling it for delivery to a stakeholder. It’s really nothing more than a prototype, and I will be building the full-fledged product.
Of course, it didn’t compile… when the task is that simple, something is bound to go wrong. In this case, the app.config was just missing. I checked source control, and it was like it was never added. I decided to add one myself and deal with and configuration issues as I came across them.
I then came across this error: Unable to find manifest signing certificate in the certificate store.
If you get this, open the project’s properties and go to the Signing tab. Uncheck the “Sign the ClickOnce manifests” unless you’re actually going to sign the application.
After that, the application compiled and ran without any problems. I’m rather curious as to how these issues manifested.
Note: Cross posted from
KodefuGuru.
Permalink
Microsoft has released extensions to the XNA Game Studio 3.1 for the Zune HD. The add-on will allow you to take advantage of the Touch APIs and the new Accelerometer. Included in the download are documentation and examples on how to leverage the new APIs.
Note: Cross posted from
KodefuGuru.
Permalink
Tuesday, September 08, 2009
#
Reading in a series of blog posts is made easy utilizing classes that came in the .NET Framework 3.5. As long as the feed is in the Atom 1.0 or RSS 2.0 formats, you easily build your own aggregator service.
SyndicationFeed feed = null;
using (XmlReader reader = XmlReader.Create(feedUrl))
{
feed = SyndicationFeed.Load(reader);
}
foreach (SyndicationItem item in feed.Items)
{
}
Off of the item, you will probably want to grab the Title.Text and the Summary.Text. Be sure to HtmlDecode them! Another important thing is the Categories collection, which I’m using as tags. Here’s the line of code from my project: Tags = item.Categories.Select(c => c.Name).Aggregate((a, b) => a + "," + b).
Lastly, an aggregator would be pointless unless you were grabbing the url (get it from Links[0].Uri.ToString()). However, many feeds are using Feedburner. If you pull from feedburner, the url will be a feedproxy.google.com url instead of one that goes directly to the blog article. The trick to get around this turned out to be quite simple. Make a WebRequest to the feedproxy url then read the WebResponse’s url.
private static string GetTrueUrl(string url)
{
if (url.StartsWith("http://feedproxy.google.com"))
{
var request = WebRequest.Create(url);
using (var response = request.GetResponse())
{
url = response.ResponseUri.ToString();
response.Close();
}
}
return url;
}
That’s all there is to reading in standard feeds. I’ll leave it up to you to decide on a specific implementation.
Note: Cross posted from
KodefuGuru.
Permalink
Tuesday, August 18, 2009
#
I had one of those problems that I had trouble resolving with a search engine this past weekend. Once it was pointed out to me what I did wrong, it was really quite simple. Basically, I needed the enter key to fire a function from a certain input textbox. I wrote up a jquery script, and it worked for IE, Chrome, and Safari, but it did not work for Firefox. Here was the script.
$("#Location").keydown(function(evt) {
switch (event.keyCode) {
case 13:
findFresh();
break;
}
});
Do you see the problem? The parameter for the function is named evt, but I switched on event instead. When this was pointed out, I was perplexed that three different browsers would automagically map this parameter to a variable for me.
Then someone else told me the real reason this works in everything but Firefox: event refers to a nonstandard (if everything but Firefox is nonstandard) object known as window.event. This contains the information from the last event that was fired.
I can deal with that because I would prefer my functions to be as pure as possible, and analyzing a parameter is more pure than analyzing a global object. I changed my code to use the evt parameter and would do so even if Firefox supported window.event. However, I really do feel that Firefox goes out of its way to make a developer’s life miserable. It’s like they’re standing on the principle that if Microsoft initiated it, they want nothing to do with it.
Window.event is such a small item that one could let it slide, but what about when you need to do something with an element in JavaScript? In every other browser, you assign an ID to the element, then reference the ID directly as a variable. Not in Firefox. They force you to call document.getElementById, and this preserves no functional purity as you’re accessing the global variable document. There is no reasoning behind this other than asininity.
Message to the Mozilla team: there are hundreds of thousands of search hits related to people trying to figure out how to make their code work in Firefox. Their code works in all other major browsers, but they are wasting hours of their precious evenings and weekends pleasing users of your browser. Please consider the millions of wasted man-hours and make your browser compatible with IE, Chrome, and Safari.
Note: Cross posted from
KodefuGuru.
Permalink
Wednesday, August 05, 2009
#
Fields… not the kind with green grass and butterflies. Rather, fields that contain the deep dark secrets of a class. You know: member variables.
There’s plenty of divergence in naming these pieces of class data. Some developers prefix the field name with an underscore. Some prefer m (meaning member) and an underscore. I personally prefer straight camelCasing. Here are some variations I’ve seen.
- private string name;
- private string _name;
- private string m_name;
- private string _Name;
- private string m_Name;
- private string mName;
There’s a lot of argument to be had concerning, and I was involved in a debate yesterday concerning this. A fellow developer in Greenville claimed that camelCasing was a bad practice because it confuses VB developers. He was advocating for PascalCased fields (and even regular variables / parameters… ::shudder::).
Here’s the deal. PascalCasing private member fields and variables is confusing to me as a C# developer. When I see PascalCasing, I assume that it’s part of the interface of the class. When I see camelCasing, I assume it’s private. Besides, I will
I find prefixing with an “m” rather bizarre. I believe this may be a holdover from some other language. I’ve heard the argument that it helps you differentiate between your members and local variables within a method. I would respond that underscore works just as well for that purpose, and your methods are too long if you couldn’t differentiate between the two.
This leaves underscore. I just think underscores are ugly. They are practical when a parameter name is the same as a field name, but I scope my variables in that situation which is the recommended practice anyway (e.g. this.name = name).
Number 1 (camelCasing with no underscore) is the rule I’ve always followed because it felt most natural. But I can also say definitively that it is the accepted best C# styling practice. StyleCop rules SA1306 and SA1309 dictate that field names must begin with a lower case letter and must not begin with an underscore. For those that think “aha, m_ it is,” SA1310 states that field names must not contain an underscore.
The only time you should violate this rule when naming a field is when the field is not private. The only time your field should not be private is when it marked readonly. Be careful when doing this, as this will cause a change to your interface if you need to promote the field to a property. The only time I’ve seen a real use for this is with static readonly fields.
I’ve seen some people expose fields as protected. When this happens, it is important to remember that protected means the fields are public to derived classes. In other words, you have broken encapsulation. Encapsulate your fields as properties when you need to expose them anywhere outside of the class (except for static readonly fields, shorthand for “I need a const but need an instance in this context”).
That concludes my rant on fields. I’m sure some will disagree… feel free to voice your opinion in the comments. Keep in mind that unless your authority is greater than StyleCop (aka the styling authority of Microsoft), I will be hard to persuade. At the same time, I understand that different organizations adopt different styles for different reasons, and that’s find for your organization as long as you don’t start breaking framework guidelines
as those affect consumers of your product.
Note: Cross posted from
KodefuGuru.
Permalink
Tuesday, August 04, 2009
#
Registration for PDC 2009 is now open. If you register by September 15th you can save a hundred bucks. Or you could get there my way: win a contest (hey, I’m a poor developer). As I mentioned in a previous article, INETA has a component contest that prizes a trip to PDC. But, it’s not the only one: Microsoft has announced the Code7 Contest - Code the Power of 7. It pays out great prizes, but you have to take advantage of the technologies built into Windows 7 like Libraries, Touch, Shell Integration, DirectX 11, and Sensors.
The PDC has also announced an initial list of sessions that will be available. Here are a few I’m interested in.
Zero to Awesome in Nothing Flat: The Microsoft Web Platform and You
Heavy on code and demos and light on slides. Join Scott Hanselman and build a seriously nice Web site in less than an hour using the Microsoft Web App Gallery, Web Platform Installer and the guts and glory of the Microsoft Web Platform. Starting from an open source application from the Gallery, the app customization goes into hyper drive with Microsoft Web Platform dev tools, frameworks, and database. Finish it off by optimizing for SEO and a few clicks to deploy to a real live Windows Server.
Windows Workflow Foundation 4 from the Inside Out
See why Windows Workflow Foundation 4 is a powerful platform for simplifying application coordination logic and state management. Learn about the core runtime abstractions and under-the-hood improvements related to areas such as performance, transactions, and persistence. Get insights and techniques that enhance your investments in Workflow.
The State of Parallel Programming
Parallel programming has been more difficult than it needs to be, perhaps because its tools have been treated as an “add-on” to serial programming. The objectives of composability and productivity demand something better. Come hear a relatively recent consensus view about what is needed for productive parallel programming, and why.
Petabytes for Peanuts! Making Sense Out of “Ambient” Data
Today, the key to success with data is no longer about who can afford to acquire, store and process data effectively. That’s the cheap and easy part. The challenge now is to develop ways to better use data than your competition so you can make sense of all the data you have. Learn how algorithmic processing, at modest and extreme scale, is completely changing how we build information systems. Hear how Microsoft is dealing with this shift and using these emerging concepts in their online services. Also see examples of how some of this technology is beginning to surface in Microsoft’s product stream.
Microsoft Unified Communications: Developer Platform Futures
Learn how Microsoft Communications Server and Microsoft Exchange provide a comprehensive and flexible communications platform for developers. Get a first look at the next generation of this platform through a series of demos and code examples. See how to embed Communicator features in your application using new Microsoft Silverlight and Windows Presentation Foundation (WPF) controls, and learn about the new API to develop full custom clients for Communications Server. Also see how the UC Managed API 3.0 provides access to the new Voice-over-IP features of Communication Server.
Developing Quality Software using Visual Studio Team System 2010
Poor software quality causes unnecessary losses for companies every year. Learn how Visual Studio Team System 2010's new code quality features can improve your teams ability to discover flaws early and to better understand the root cause of any issue. There are tools for everybody including architects, developers, managers, and testers.<br /><br />During this full-day workshop, we’ll start at the beginning with requirements and design, and then move into unit testing, debugging, testing, and collaboration. We will complement these with demonstrations of code quality best practices that have proven to work on a variety of projects. Come see how much easier it can be to improve code quality by using VSTS 2010!
It looks exciting! If anyone wants to hook me up with a trip to PDC, please use the contact form on my website.

Note: Cross posted from
KodefuGuru.
Permalink
Thursday, July 30, 2009
#
This is part 3 of a series on KiGG Automation. Code in this article may be dependent on previous entries.
Part 1: Automating KiGG Publishing
Part 2: KiGG’s Story Summary
Part 3: Automating KiGG Submission
When you’re first starting a KiGG site and your user base is low, creating a bot can ease the pain of obtaining content. However, in the default install of KiGG there is no way to automate this. You can search blogs and news sites, but submitting articles from those sites is a manual process; even for the sources you trust.
My goal in this article is to build off of the first article so that submission can be automated. There are many sources of content out there, and I may cover some aspects of retrieving this in future articles. But for now, that it is up to you to explore.
Finding the submit route is pretty simple: it is Submit and it is handled by the StoryController.
_routes.MapRoute("Submit", "Submit",
new { controller = "Story", action = "Submit" });
The method on the controller makes it clear what http method we must use and the parameters required.
[AcceptVerbs(HttpVerbs.Post), ValidateInput(false), Compress]
public ActionResult Submit(string url,
string title, string category, string description, string tags)
Analyzing this method shows that another JSON class can be used: JsonCreateViewData. We will need to add this to our bot’s codebase. It uses two properties already found on KiggResult, so we will call this KiggCreateResult and derive from the former class.
public class KiggCreateResult : KiggResult
{
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
public static KiggCreateResult Create(string json)
{
return JsonConvert.DeserializeObject<KiggCreateResult>(json);
}
}
Now, inside KiggBot.cs, we will need to add our submit method. I think it may be better to return the url to the story here, but I’ll worry about refactoring this later. Remember that HttpDictionary will handle the form encoding for us.
public bool Submit(string storyUrl, string title,
string category, string description, string tags)
{
HttpDictionary dictionary = new HttpDictionary {
{"url", storyUrl},
{"title", title},
{"category", category},
{"description", description},
{"tags", tags}
};
var result = KiggCreateResult.Create(
session.Post(url + "Submit", dictionary));
return result.IsSuccessful;
}
That seemed easy enough. Now, in the test program I will call this with a few parameters to see how it works.
KiggBot bot = new KiggBot("http://localhost:1736");
bot.Login("bee", "iambusy");
bot.Submit("http://example.com/", "Example", "Agile",
"This is a test", "Example, News");
bot.Logout();
No dice. I received an error that the user agent must be set. I think user agent should be configurable in our program, but for simplicity I will add a constant to WebSession for userAgent and set it on the request object in the Post method.
private const string userAgent = "Pigg";
public string Post(string url, string formData)
{
var request = WebRequest.Create(url) as HttpWebRequest;
request.UserAgent = userAgent;
...
}
I tried again, and it worked perfectly. The bot created an entry with two new tags: Example and News. Keep in mind that Category must match a valid category in your KiGG install.
If you’re following along, you can now automate KiGG publishing and article submission. You can also define what part of the html from which the story summary is retrieved. Leave a comment on what part of KiGG automation you would like me to look at next.
Note: Cross posted from
KodefuGuru.
Permalink
Friday, July 24, 2009
#
Thursday, July 23, 2009
#
When I recently started looking through a certain project’s tests, I was struck by how difficult it was for me to read and understand. The tests were laid out haphazardly, and the code contained enough logic to make me wonder if it would be easier to analyze the functional code. Tests don’t do anyone good if they require that much analysis. In contrast, one of my favorite open source projects contains tests that allow me to learn the functionality of the system without looking at any functional code.
The intent of this post isn’t to describe advanced unit testing techniques but to describe a few guidelines that I feel should be implemented regardless if you’re mocking objects, using test driven development, or just want to ensure your code works. I am using Microsoft’s unit testing framework, but these same guidelines apply in most other unit testing frameworks.
Name Code Files Sensibly
You should be able to find your test, which may be difficult to do if you name your file “MyTests.cs.” Naming the file after the class you’re testing is a guideline many people use. Alternatively, you can name it after a functional area if you have more than one fixture per file. Yes, generally speaking you should have one class per file, but I admit to relaxing this rule because you are going to experience class explosion if you’re striving for 100% coverage. I prefer to name my class files after the class just as I do in functional development.
Name Fixture After Scenario
Your test fixture should set up a scenario, and the name of the class should reflect that scenario. For example, if you’re testing what happens when a user activates an account, name the class “WhenUserActivatesAccount.”
[TestClass]
public class WhenUserActivatesAccount
{
}
Setup Code in Constructor
Usually, your constructor (or Setup method in some frameworks) should initialize the scenario that you’re testing. If external setup must be done, use the ClassInitializer attribute on a static method.
User user;
Account account;
public WhenUserActivatesAccount()
{
user = new User("kodefuguru");
account = user.Account;
account.Activate();
}
If you expect exceptions with certain parameters in various, similar scenarios; it may be necessary to call the setup code from within the testing method. I prefer to refactor my tests so that the test for the expected exception is in a derived class that tweaks the modifications within its constructor before calling the base constructor… for example, “public class WhenInvalidUserActivatesAccount : WhenUserActivatesAccount.”
Name Test After Expected Result
Ideally, tests contain one Assert statement. You’re testing a specific condition that you expect to occur as a result of the scenario you’ve presented. When a user activates an account, you expect the account to activated. Therefore, your test should be named “AccountActivatedShouldBeTrue,” with the assertion “Assert.IsTrue(account.Activated).”
[TestMethod]
public void AccountActivatedShouldBeTrue()
{
Assert.IsTrue(account.Activated);
}
No Conditionals Containing Assertions
If assertions are contained within a conditional statement, then you aren’t really ensuring that your code is running as expected. When you’re writing tests, you’re declaring the behavior of your system based upon certain conditions.
[TestMethod]
public void AccountActivatedShouldDependOnUserValid()
{
if (user.Valid)
{
Assert.IsTrue(account.Activated);
}
else
{
Assert.IsFalse(account.Activated);
}
}
If I have a test like this, I’m not really declaring a fact about the system. Instead, I’m declaring facts about two different situations, one of which will not occur. Whether user.Valid is true or not should depend on the setup of my test, and I should know what the value will be when this test runs.
Differentiate Between Unit Tests and Integration Tests
Unit tests are for testing an individual unit of code. Integration tests are for testing functionality between different systems. It is best to separate unit tests and integration tests by placing them in separate projects. If you’re not already doing so, at some point you may wish to automate your testing process. In a continuous integration environment, unit tests should be run with every build. Integration tests tend to be slower, and it is oftentimes not practical to automate them as frequently.
If you have trouble differentiating between unit tests and integration tests (i.e. everything you do connects to a service or persists to the database), it would be a good idea to look into mocking and inversion of control so that you can create tests for units of functionality.
---
There are many more things you can do to create effective unit tests, but if you follow the few guidelines I have listed you will benefit immediately. It is important that it is easy for anyone looking at your tests to know how the system is supposed to behave. There is additional benefit in that you can harvest fixture and test names to create functional documentation for your software.
Note: Cross posted from
KodefuGuru.
Permalink
Wednesday, July 15, 2009
#
A week ago, I posted a few summer contests to partake in during those lazy weekends we all experience (yea right). Since that time, another contest was announced by Silverlight MVP, Page Brooks.
This contest is all about building a Silverlight control. The boundaries are rather loose. You can make it practical, you can make it cool, but most importantly have fun making it!
The deadline for the contest is September 19, leaving just 66 days to get your entry in. If you win, you’ll receive tons of goodies from Devexpress, Infragistics, Telerik, and the SilverlightShow.
Good luck… I will be competing in this one as well.
Note: Cross posted from
KodefuGuru.
Permalink
Arnon Rotem-Gal-Oz wrote an article for Architect Zone where he makes the claim that CRUD is bad for REST. I couldn’t disagree more, so I felt it important to respond to his criticism.
CRUD which stands for Create, Read, Update and Delete, are the four basic database operations. Some of the HTTP verbs, namely POST, GET, PUT and DELETE (there are others like OPTIONS or HEAD) seem to have a 1-1 mapping to CRUD. As I said earlier they don’t. The table below briefly contrast HTTP verbs and CRUD
Actually, they do map perfectly as CRUD itself is pretty simple (it’s literally create, retrieve, update, delete without caveats). The examples that are laid out in Arnon’s article are comparing REST directly to SQL Server commands. The question shouldn’t be do http verbs fit perfectly with SQL operations, but rather do they map to the four basic functions of persistent storage? I can say without any doubt that POST, GET, PUT, and DELETE map quite well, making it possible for REST useful for persistence.
The way I see it, the HTTP verbs are more document oriented than database oriented (which is why document databases like CouchDB are seamlessly RESTful). In any event, what I tried to show here is that while you can update, delete and create new resources the way you do that is not exactly CRUD in the database sense of the word – at least when it comes to using the HTTP verbs.
I see http verbs as resource oriented, and data is just one type of resource. Of course, if I’m creating an ADO.NET Data Service, I want to expose my data as more useful resources (e.g. a useful representation of a Customer rather than just the customer data).
However, the main reason CRUD is wrong for REST is an architectural one. One of the base characteristics [1] of REST is using hypermedia to externalize the statemachine of the protocol (a.k.a. HATEOS– Hypertext as the engine of state). The URI to URI transition is what makes the protocol tick. […] If you are busy with inserting and updating (CRUDing) resources you are not, in fact, thinking about protocols or externalizing a State machine and, in my opinion, miss the whole point about REST.
I could think about protocols, but a useful one already exists (HTTP). I could think about externalizing my state machine, but that’s already taken care of when using a product like ADO.NET Data Services. If you are busy with inserting and updating resources, you probably have a resource oriented architecture which doesn’t miss the whole point of REST as it *is* an implementation of a REST architecture.
CRUD services leads and promoted to the database as a service kind of thinking (e.g. ADO.NET data services) which as I explained in another post last year is a bad idea since:
- It circumvents the whole idea about "Services" - there's no business logic.
- It is exposing internal database structure or data rather than a thought-out contract.
- It encourages bypassing real services and going straight to their data.
- It creates a blob service (the data source).
- It encourages minuscule demi-serices (the multiple "interfaces" of said blob) that disregard few of the fallacies of distributed computing.
- It is just client-server in sheep's clothing.
1. ADO.NET Data Services provides a standard ORM that can be consumed by any application. That in itself is useful as a service (retrieve entities rather than data, mapping is hidden). However, one can provide business logic in that tier if one chooses, but I think that’s bad design.
2. Even with the most direct ORM, you’re still providing mapped objects rather than an internal data structure. If you have a well-thought out map, then you will be providing that instead.
3. You aren’t going straight to the data, you are utilizing entities. The service exists and can act as a gate keeper.
4. I don’t understand this complaint… the data source is a binary large object service? If blob is meant in another sense, my answer is that you only expose what you want to expose with ADO.NET Data Services.
5. I suppose I’ve never thought about setting up multiple demi-services?
6. The problem with client-server is the disregard of object-relational mapping and business layers. Even in the worst case scenario with ADO.NET Data Services, you get object-relational mapping.
I don’t believe CRUD is bad for REST at all. In fact, I believe they perfectly complement each other in the construction of a resource oriented architecture.
Note: Cross posted from
KodefuGuru.
Permalink
Tuesday, July 14, 2009
#
When I set up my first KiGG site, I was surprised to discover that I had to manually publish articles. I assumed it would be an automated process that would run once a day. Since there are times I may not be able to log into my website, I set about figuring out how to automate the process.
I should note that during this process, I didn’t use best practices. I had one requirement: make a program that I can schedule to publish stories on KiGG. I wasn’t really sure what I would need to go about doing that. So, I did what I assume most developers do: create a console application prototype. I don’t claim this code is perfect, but if you want classes to automate publishing in KiGG (or control MVC applications), this will do the trick.
KiGG is an ASP.NET MVC application. This made it easy to figure out where to begin. I wanted to Publish, so I needed to find the admin link and see what it called. I guessed it would be something like, /Publish, and I was correct.
scriptManager.RegisterOnReady("Administration.set_publishUrl('{0}');"
.FormatWith(Url.RouteUrl("Publish")));
set_publishUrl is simply a setter in the JavaScript to prevent a url from being hardcoded in script. Looking over the JavaScript I could tell there wasn’t much more needed than calling the proper url.
$.ajax(
{
url: Administration._publishUrl,
type: 'POST',
dataType: 'json',
data : '__MVCASYNCPOST=true', // a fake param to fool iis for content-lenth,
beforeSend: function()
{
$U.showProgress('Publishing stories...');
},
success: function(result)
{
$U.hideProgress();
if (result.isSuccessful)
{
$U.messageBox('Success', 'Story publishing process completed.', false);
}
else
{
$U.messageBox('Error', result.errorMessage, true);
}
}
}
);
The script is doing a POST on the /Publish url with fake data (to fool IIS?).
Next, it was time to check the routing for /Publish. Routing in KiGG is defined in Kigg.Web\BootstrapperTasks\RegisterRoutes.cs. It was done this way to be consistent with the Open Closed Principle.
_routes.MapRoute("Publish", "Publish",
new { controller = "Story", action = "Publish" });
Now we know the entry to this is in the story controller and that the method is Publish. The story controller being used is defined within the web.config file using Unity.
<typeAlias alias="StoryController" type="Kigg.Web.StoryController, Kigg.Web"/>
I set up a break point and wrote a quick routine to post to the publish url.
var request = WebRequest.Create(http://localhost:1736/Publish);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
var form = Encoding.ASCII.GetBytes("__MVCASYNCPOST=true");
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(form, 0, form.Length);
requestStream.Close();
}
var response = request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var responseText = reader.ReadToEnd();
Debug.WriteLine(responseText);
reader.Close();
}
Everything executed fine, but the return message indicated something was wrong: “{"isSuccessful":false,"errorMessage":"You are currently not authenticated."}.” It’s pretty obvious that authentication would be necessary, otherwise I could publish DotNetShoutOut whenever I wanted. Unfortunately, the obvious way to authenticate does not work.
request.Credentials = new NetworkCredential("admin", "password");
Since it is a NetworkCredential, I assume this code would work with Windows authentication turned on. However, we’re using forms authentication. I looked at the routes and found one for Login and Logout. At this point it was clear that I would be calling post multiple times, so I moved the code to a method that would accept a url and formdata as a string.
Post("http://localhost:1736/Login", "userName=admin&password=password");
Post("http://localhost:1736/Publish", "__MVCASYNCPOST=true");
Post("http://localhost:1736/Logout", "__MVCASYNCPOST=true");
This returned the following results:
{"isSuccessful":true,"errorMessage":null}
{"isSuccessful":false,"errorMessage":"You are currently not authenticated."}
{"isSuccessful":false,"errorMessage":"You are currently not logged in."}
I put a breakpoint in the Login method of the MembershipController, and from there was able to see what was happening. Although it was a few levels deep, it was clear that FormsAuthentication.SetAuthCookie was the important piece of code; I needed a way to retain cookies between requests.
Cookies are only available by using HttpWebRequest and HttpWebReponse rather than their base classes. So, I cast my variables to the proper class. One odd thing I found was the cookies have to be retrieved from the request rather than the response after you have requested the response. I wrapped this functionality up in a WebSession class.
public class WebSession
{
protected CookieCollection Cookies { get; set; }
public WebSession()
{
Cookies = new CookieCollection();
}
public string Post(string url, HttpDictionary formData)
{
return Post(url, formData.ToString());
}
public string Post(string url, string formData)
{
var request = WebRequest.Create(url) as HttpWebRequest;
if (request == null)
{
throw new HttpException();
}
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(request.RequestUri, Cookies);
var form = Encoding.ASCII.GetBytes(formData);
WriteToRequest(request, form);
var response = request.GetResponse() as HttpWebResponse;
if (response == null)
{
throw new HttpException();
}
var responseText = ReadResponse(response);
Cookies = request.CookieContainer.GetCookies(request.RequestUri);
Debug.WriteLine(responseText);
return responseText;
}
private static void WriteToRequest(WebRequest request, byte[] form)
{
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(form, 0, form.Length);
requestStream.Close();
}
}
private string ReadResponse(WebResponse response)
{
using (StreamReader reader =
new StreamReader(response.GetResponseStream()))
{
var responseText = reader.ReadToEnd();
reader.Close();
return responseText;
}
}
}
If you look closely you’ll notice an HttpDictionary class. This is because I wanted to treat the form data as a dictionary rather than a string. I suppose this could be written as an extension method on Dictionary<string, string> instead.
public class HttpDictionary : Dictionary<string, string>
{
public override string ToString()
{
return this.Select(q => EncodePair(q))
.Aggregate((a, b) => a + "&" + b);
}
private string EncodePair(KeyValuePair<string, string> pair)
{
return HttpUtility.HtmlEncode(pair.Key) +
"=" + HttpUtility.HtmlEncode(pair.Value);
}
}
I also felt it necessary to wrap up the result received from KiGG in a class that can be used. Otherwise, it’s difficult to know whether or not the call was successful. To convert from Json, I used Json.NET.
public class KiggResult
{
[JsonProperty(PropertyName="isSuccessful")]
public bool IsSuccessful{ get; set; }
[JsonProperty(PropertyName = "errorMessage")]
public string ErrorMessage { get; set; }
public static KiggResult Create(string json)
{
return JsonConvert.DeserializeObject<KiggResult>(json);
}
}
Finally, I made a KiggBot class to provide us an interface that makes sense for accessing a KiGG site. This can be changed to throw an exception if the result indicates the call was not successful.
public class KiggBot
{
private static readonly HttpDictionary mvcAsyncPost = new HttpDictionary
{
{"__MVCASYNCPOST", "true"}
};
private WebSession session;
private string url;
public KiggBot(string url)
{
if (!url.EndsWith("/"))
url += "/";
this.url = url;
session = new WebSession();
}
public bool Login(string userName, string password)
{
HttpDictionary dictionary = new HttpDictionary {
{"userName", userName}, {"password", password}};
var result = KiggResult.Create(
session.Post(url + "Login", dictionary));
return result.IsSuccessful;
}
public bool Logout()
{
var result = KiggResult.Create(
session.Post(url + "Logout", mvcAsyncPost));
return result.IsSuccessful;
}
public bool Publish()
{
var result = KiggResult.Create(
session.Post(url + "Publish", mvcAsyncPost));
return result.IsSuccessful;
}
}
With these classes, it’s fairly easy to create an automated publishing program. At the very least, write a console app and use scheduler to fire it daily.
KiggBot bot = new KiggBot("http://localhost:1736");
bot.Login("admin", "password");
bot.Publish();
bot.Logout();
Hope that helps. If anyone makes a cool GUI for this and releases it, might I recommend PiGG?
Note: Cross posted from
KodefuGuru.
Permalink
Monday, July 13, 2009
#
I don’t approve of calling a WCF server from SQL Server, but there was a business requirement that had to be met. It concerned regulations regarding the safeguarding of certain data elements. Due to performance issues and the application’s infrastructure, calling the service from the application itself wasn’t an option.
Coding the CLR functions were the easy part. To do this, reference the Microsoft.SqlServer.Server and System.Data.SqlTypes namespaces (contained in System.Data.dll) and set the appropriate attributes on static methods contained within a static class. Also, it is probably best if you use the SqlTypes (SqlString, SqlDateTime, etc) for parameters and return values rather than rely on Sql Server to convert the values for you. Be sure to enable CLR on your SQL Server.
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public static class SqlFunctions
{
[SqlFunction(DataAccess = DataAccessKind.Read, IsDeterministic = true)]
public static SqlString HelloWorld()
{
return new SqlString("Hello World!");
}
}
I wanted to avoid pulling too many assemblies into SQL Server, so I limited my references to the bare essentials for working with WCF and Sql Server: System, System.Data, System.Runtime.Serialization, System.ServiceModel, and System.XML.
Here’s the script to drop the assemblies if they exist and add them back (double slashes are intentional to allow copy/paste with formatting to work). Because of dependencies, it is necessary to add more assemblies than directly referenced by the project. If you created this within a database project, you can deploy by right-clicking the project. I have previously posted instructions on how to convert a class library to a database project.
IF EXISTS (SELECT * FROM sys.assemblies asms
WHERE asms.name = N'Microsoft.Transactions.Bridge')
DROP ASSEMBLY [Microsoft.Transactions.Bridge]
GO
IF EXISTS (SELECT * FROM sys.assemblies asms
WHERE asms.name = N'System.IdentityModel.Selectors')
DROP ASSEMBLY [System.IdentityModel.Selectors]
GO
IF EXISTS (SELECT * FROM sys.assemblies asms
WHERE asms.name = N'System.IdentityModel')
DROP ASSEMBLY [System.IdentityModel]
GO
IF EXISTS (SELECT * FROM sys.assemblies asms
WHERE asms.name = N'System.Messaging')
DROP ASSEMBLY [System.Messaging]
GO
IF EXISTS (SELECT * FROM sys.assemblies asms
WHERE asms.name = N'System.Web')
DROP ASSEMBLY [System.Web]
GO
IF EXISTS (SELECT * FROM sys.assemblies asms
WHERE asms.name = N'SMDiagnostics')
DROP ASSEMBLY [SMDiagnostics]
GO
CREATE ASSEMBLY
SMDiagnostics from
'C:\Windows\Microsoft.NET\Framework\v3.0\
\Windows Communication Foundation\SMDiagnostics.dll'
with permission_set = UNSAFE
GO
CREATE ASSEMBLY
[System.Web] from
'C:\Windows\Microsoft.NET\Framework\v2.0.50727\
\System.Web.dll'
with permission_set = UNSAFE
GO
CREATE ASSEMBLY
[System.Messaging] from
'C:\Windows\Microsoft.NET\Framework\v2.0.50727\
\System.Messaging.dll'
with permission_set = UNSAFE
GO
CREATE ASSEMBLY
[System.IdentityModel] from
'C:\Program Files\Reference Assemblies\Microsoft\
\Framework\v3.0\System.IdentityModel.dll'
with permission_set = UNSAFE
GO
CREATE ASSEMBLY
[System.IdentityModel.Selectors] from
'C:\Program Files\Reference Assemblies\Microsoft\
\Framework\v3.0\System.IdentityModel.Selectors.dll'
with permission_set = UNSAFE
GO
CREATE ASSEMBLY
[Microsoft.Transactions.Bridge] from
'C:\Windows\Microsoft.NET\Framework\v3.0\
\Windows Communication Foundation\Microsoft.Transactions.Bridge.dll'
with permission_set = UNSAFE
GO
You will need to add your own assembly to the list in a similar manner as the .NET assemblies. Notice that they are marked UNSAFE. This is a necessary evil if you wish to use WCF with SQL Server. Because of this, if you have not done so you will need to reconfigure your database to allow it.
ALTER DATABASE KodefuGuru SET TRUSTWORTHY ON
reconfigure
The interesting part about this is that more assemblies than those specified are pulled in. When you remove the ones you specifically added, these are removed as well. Here is the list of assemblies:
Accessibility
Microsoft.Transactions.Bridge
SMDiagnostics
System.Configuration.Install
System.Design
System.DirectoryServices
System.DirectoryServices.Protocols
System.Drawing
System.Drawing.Design
System.EnterpriseServices
System.IdentityModel
System.IdentityModel.Selectors
System.Messaging
System.Runtime.Remoting
System.Runtime.Serialization
System.Runtime.Serialization.Formatters.Soap
System.ServiceModel
System.ServiceProcess
System.Web
System.Web.RegularExpressions
System.Windows.Forms
System.Windows.Forms? What?! Some of the dependencies are truly mind boggling.
This should be just enough to allow you to put your service calls inside of CLR functions. I attempted to be as lightweight as possible and avoided pulling in extra libraries, though you certainly could pull in a massive programmatic infrastructure with this.
I only agreed to this because the service call was directly related to the integrity of the data and further restrictions prevented the use of a separate physical tier to handle it. If you’re in the same situation, I hope this helps.
Note: Cross posted from
KodefuGuru.
Permalink
Tuesday, July 07, 2009
#
I never seem to have the time to enter coding competitions. It’s a shame, because they look like a lot of fun! I do usually bookmark these contests just in case I find myself with a free weekend, and I want to share those with the community. It may mean more competition in case I do enter, but it also means more cool community applications that I get to play with. For example, Twtri is great for updating Twitter or Facebook with your flight status, and it won the grand prize in the new CloudApp() competition!
ComponentArt is hosting the 2009 Summer Silverlight Coding Competition from June 22nd to September 22nd. The grand prize is $10,000 USD, and the authors of the top two runner-up apps each get a Component Art license. You must have designed the Silverlight 1, 2, or 3 application yourself, and use of ComponentArt products is not required.
Will Code For Green is sponsored by Bing and Gnomedex, and two grand prize winners will each receive $10,000 USD. The point of the contest is to design a web application or mashup that uses Bing services to help people in this bad global economy or to improve the ecology of our planet. Submission is open through August 12th. The winners will be announced at Gnomedex 2009.
Win a trip to PDC 2009 with INETA Component Code Challenge. The goal of the competition is to mash together at least 2 components from 2 different approved vendors to create a .NET application. Then, you must create a 3-5 minute Camtasia video showing off your application and the components you used. Submissions must be received by August 25th, and winners will be announced on September 14th. The top 10 entries will receive prizes, but only the top 2 go to PDC.
The deadline has passed to register for the Dream-Build-Play 2009 Challenge, but you can still enjoy the entries as they come in by visiting the gallery. What is Dream-Build-Play? Well, it’s a competition to create an XNA game. It also has the largest payouts of all the contests I’ve come across: $40,000 grand prize, $20,000 first prize, $10,000 second prize, and $5,000 third prize. Not only that, but the winning teams have an opportunity to potentially receive an Xbox LIVE Arcade Publishing Contract. If you were lucky enough to register in time, you have until August 6th to submit your entry.
I only support contests that I feel contribute back to the community, but I sometimes come across a contest that seems interesting, only to read the fine print and discover they claim sole rights to the application you enter. An example of this is the “Super Sexy” Mortgage Calculator Contest. I’m not sure how a mortgage calculator can be thought of as “sexy,” but it nevertheless seemed interesting to me. I tried to read their terms and conditions only to discover they linked to the terms and conditions of a mortgage rather than a contest. However, next to the link was the text, “Mortgage Loan Place will retain sole right to ownership of all submissions.” Dirty stuff.
I’m sure I missed a few contests out there. If you know of any, be sure to leave a comment.
Note: Cross posted from
KodefuGuru.
Permalink