Monday, May 3, 2010

Making Cross Domain jQuery AJAX Calls

Today's web browsers do not allow web pages to make cross-domain ajax calls. By this i mean that if you are at www.ajax.com and try to make an Ajax call ( an HTTP request using the XmlHttpRequest object) to www.other-domain.com the browser would not allow this to happen. Why? For security purposes that i cannot currently name.

However, at some point you get to a project where you're interfacing this third-party site that needs to talk to your main site, or some other similar situation where the only way you're going to get the data you need from point a to point b is with some javascript magic. Here is how to accomplish it:

How to get/post data using jQuery/javascript (JSONP)

The short answer: its not ajax at all, its JSONP. Yes, JSONP is not Ajax. I just learned this today. Like i said earlier, browsers do not allow XHR/Ajax cross-browser requests. JSONP avoids this by making a request for a script file-- no Ajax at all. Let me explain:

  1. Instead of accessing the XHR object, the browser first creates a new script tag to inject into the HTML DOM
  2. The script tag's URL is set to the URL you're looking to get/post(using HTTP GET) data to
  3. The script tag is injected into the page, causing...
  4. The request is sent to the server, even if its cross-domain
  5. The server returns the data in the form of a javascript function call
  6. The browser receives the data and executes the function call

jQuery code

//use a get to post a querystring value via HTTP GET to an asp.net webhandler
$.getJSON("http://www.example.com/get-post.ashx?var1=var1value&callback=?",function(data){
     //really no need to do anything here, we're just posting data
     //but this will output success
     alert(data.return);
});

asp.net generic handler/webhandler code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace jsonp_test
{
    /// 
    /// Summary description for $codebehindclassname$
    /// 
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class get_post : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string callback = "";
            try
            {
                if (!string.IsNullOrEmpty(context.Request["callback"]))
                {
                    if (!string.IsNullOrEmpty(context.Request["var1"]))
                        SaveData(context.Request["var1"]);
                    callback = context.Request["callback"];

                    context.Response.Write(callback + "({ \"return\": \"Success\" })");
                }
            }
            catch (Exception exc)
            {
                //hopefully this error doesnt contain any quotes... you know?
                context.Response.Write(callback + "({ \"return\": \"" + exc.Message + "\" })");
            }
        }

        private void SaveData(string value)
        {
            //do something with the var1 posted to us
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

So what we effectively have here is the setup for asp.net cross domain ajax calls using jQuery

How to do cross-domain calls to others' servers: YQL

What if you need to do a get but don't have the ability to make the page its posting to return a JSONP response? Using YQL is a great way to achieve this.

YQL is a way to query the internet like it is a database. For example, one could easily run

select * from html where url="http://www.microsoft.com"

and recieve a JSONP return containing all of the site's HTML. You could also, do the following

select * from html where url="http://www.mircorosft.com?var1=var1value"

and HTTP GET values to the server. YQL does not allow this to happen on any area of any site that is blocked by the robots.txt file. Here's full example code:

//feel free to add querystring vars to this
var myurl="http://www.example.com/get-post.ashx?var1=var1value&callback=?";
//make the call to YQL 
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
                "q=select%20*%20from%20html%20where%20url%3D%22"+
                encodeURIComponent(myurl)+
                "%22&format=xml'&callback=?",
        function(data){
          if(data.results[0]){
            //this data.results[0] is the return object you work with, 
            //if you actually want to do something with the returned json
            alert(data.results[0]);
          } else {
            var errormsg = '

Error: could not load the page.

'; //output to firebug's console //use alert() for other browsers/setups conole.log(errormsg); } } );

Wednesday, March 31, 2010

Random Order LINQ Query

I get a lot of requests for random ordering at my job... this helps a lot.

(from s in myset orderby Guid.NewGuid() select s).Take(5)

Updated 10/4/2011

Wednesday, February 10, 2010

C# Design Patterns: Factory

What is the factory design pattern? Well to begin with it is something that is referenced frequently in software architecture. Functionally, a factory builds an object. More specifically, factories render instances of an abstract class type.

C# Example

How often have you got caught up in creating objects based upon business logic? Something like this:

 public interface ICar
{
 decimal Price {get;set;}
 int HorsePower{get;set;}
}
//found somewhere randomly in your code...
 ICar result;
 //this code is heavily biased
 if(user.IsRich)
  return new AstonMartin();
 else if(user.IsSteelWorker)
  return new Ford();
 else if(user.IsPractical)
  return new Honda();
 return MomsCar();

I've found code like this in projects many times and have done it myself. What's really wrong with this?

  1. If you need this code again, and copy/paste, you'll be violating DRY (do not repeat yourself)
  2. Not reusable
  3. Not centrally based, so a change in one place will need copied to another
  4. Whatever class this code is in is at this point violating the Single Responsibility Principle

The Factory Design Pattern Fix

Take a look over why this is architectually better:

public enum CarTypes { NotSet, Honda, AstonMartin, Ford };
public sealed class CarFactory
{
    public ICar Create(CarTypes cType)
    {
        if (cType == CarTypes.Honda)
            return new Honda();
        else if (cType == CarTypes.AstonMartin)
            return new AstonMartin();
        else if (cType == CarTypes.Ford)
            return new Ford();
        throw new ArgumentOutOfRangeException("cType");
    }
}

What have we changed in this example?

  1. All of our code is in one area--easy to update and reuse
  2. The factory is sealed, so we need not worry about any other classes changing the factory behavior

Simple stuff!

Monday, February 1, 2010

Dependency Injection in .NET

I'm really on an architecture kick at this point. Honestly, it's probably about time. I find few senior-style job postings that do not ask for some knowledge of Spring.NET or Castle Windsor. Now that i've done a little reading up on the subject, I see that this is for good reason.


Introduction: What is Dependency Injection?


This stuff is tricky--I'm not going to lie. First of all, I would recommend reading up on the basics. Until you start to really see the power behind defining interfaces and working with abstractions dependency injection will be unnecessary for you.


Dependency Injection strives to decouple classes from dependencies. For instance:


public interface IComplaintHearer
{
void RegisterComplaint(string message);
}
public class Manager : IComplaintHearer
{
public Manager() { }
public void RegisterComplaint(string message)
{
//do something with message
}
}
public class Employee
{
//completely dependent upon this exact class
private Manager _itsManager;
public Employee() { }
public void Complain(string complaint)
{
_itsManager.RegisterComplaint(complaint);
}
}

What's the issue? What if we want the employee to report to someone other than its immediate boss? Or, what if we want the employee to complain to a co-worker? We would have to completely change the class. Right now this code completely violates the open closed principle(among others) we discussed when reviewing the S.O.L.I.D. principles. So lets use the dependency inversion principle and make this class dependent upon an abstraction:


public interface IComplaintHearer
{
void RegisterComplaint(string message);
}
public class Manager : IComplaintHearer
{
public Manager() { }
public void RegisterComplaint(string message)
{
//do something with message
}
}
public class Employee:IComplaintHearer
{
//completely dependent upon this exact class
private IComplaintHearer _complaintHearer;
public Employee(IComplaintHearer hearer)
{
_complaintHearer=hearer;
}
public void RegisterComplaint(string message)
{
//do something with the message
}
public void Complain(string complaint)
{
_complaintHearer.RegisterComplaint(complaint);
}
}

And we would need to run this code like so:


//we could pass a manager, or another employee if we wanted to
Employee myEmp = new Employee(new Manager());

Injecting the Class, Instead of Providing It


Imagine a scenario where we had tons of classes that implemented the IComplaintHearer interface. We'd have to recompile the code everytime we want to change who the employee complains to. This is where a dependency injection steps in and allows you to:


  1. Specify a class's dependency at run-time
  2. Dynamically use classes in another assembly
  3. Make changes without recompilation

Let's take a look at an example:


public interface IComplaintHearer
{
void RegisterComplaint(string message);
}
public class Manager : IComplaintHearer
{
public Manager() { }
public void RegisterComplaint(string message)
{
//do something with message
}
}
public class Employee:IComplaintHearer
{
//completely dependent upon this exact class
private IComplaintHearer _complaintHearer;

//use the IComplaintHearer subclass that the Dependency Injection Framework (StructureMap in this case) tells us to
// this depends upon the xml that defines what to use (below)
public Employee(): this ( ObjectFactory.GetInstance()){}
public Employee(IComplaintHearer hearer)
{
_complaintHearer=hearer;
}
public void RegisterComplaint(string message)
{
//do something with the message
}
public void Complain(string complaint)
{
_complaintHearer.RegisterComplaint(complaint);
}
}





What just happened? By using the StructureMap Framework for .NET, we just specified the IComplaintHearer that our employee class will default to--the manager. In the XML above, we mapped the expected type/assembly to the default type/assembly. Further, we could set up defaults for all of our classes that we could change later without ever having to change any code. In some ways, I feel like this is moving a problem from one environment to another, but in other ways i think it is a great architectural tool.


What do you think?


Friday, January 29, 2010

The S.O.L.I.D. Object Oriented Programming(OOP) Principles

Introduction


What does it take to be an Object Oriented Programmer? There was a time where I believed all that meant was that you worked with a language such as C#, C++, or Java. However, the more I get acquainted with newer technologies, the more I realize that there is a set of fundamentals core to the title. And really, these fundamentals are about architecting the best, most update-able, scalable systems. Just yesterday while diving into DataObjects.NET I was greeted by Domain Driven Design(DDD)-- a popular architectural abstraction. It motivated me to think about the basics, which is the purpose of this article.


The S.O.L.I.D. Principles of Class Design


The S.O.L.I.D. principles seem to be the least common denominator of creating great classes; even before Design Patterns. I recommend taking some time to really think about each of them and how you can apply them. Lets dive in, one by one.


The Single Responsibility Principle


There should never be more than one reason for a class to change. Basically, this means that your classes should exist for one purpose only. For example, lets say you are creating a class to represent a SalesOrder. You would not want that class to save to the database, as well as export an XML-based receipt. Why? Well if later on down the road you want to change database type(or if you want to change your XML schema), you're allowing one responsibility's changes to possibly alter another. Responsibility is the heart of this principle, so to rephrase there should never be more than one responsibility per class.


The Open Closed Principle


Software entities(classes,modules,functions,etc.) should be open for extension, but closed for modification. At first this seems to be contradictory: how can you make an object behave differently without modifying it? The answer: by using abstractions, or by placing behavior(responsibility) in derivative classes. In other words, by creating base classes with override-able functions we are able to create new classes that do the same thing differently without changing the base functionality. Further, if properties of the abstracted class need compared or organized together, another abstraction should handle this. This is the basis of the "keep all object variables private" argument.


The Liskov Substitution Principle


Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.In other words, if you are calling a method defined at a base class upon an abstracted class, the function must be implemented properly on the subtype class. Or, "when using an object through its base class interface,[ the]derived object must not expect such users to obey preconditions that are stronger than those required by the base class." The ever-popular illustration of this is the square-rectangle example. Turns out a square is not a rectangle, at least behavior-wise.


The Dependency Inversion Principle


Depend on abstractions, not on concretions or High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon details. Details should depend upon abstractions. (I like the first explanation the best.) This is very closely related to the open closed principle we discussed earlier. By passing dependencies (such as connectors to devices, storage) to classes as abstractions, you remove the need to program dependency specific. Here's an example: a Employee class that needs to be able to be persisted to xml and a database. If we placed ToXML() and ToDB() functions in the class, we'd be violating the single responsibility principle. If we created a function that took a value that represented whether to print to XML or to DB, we'd be hard-coding a set of devices and thus be violating the open closed principle. The best way to do this would be to: 1) Create an abstract class (named DataWriter, perhaps) that can be inherited from for XML (XMLDataWriter) or DB (DbDataWriter) Saving, and then 2) Create a class (named EmployeeWriter) that would expose an Output(DataWriter saveMethod) that accepts a dependency as an argument. See how the Output method is dependent upon the abstractions just as the output types are? The dependencies have been inverted. Now we can create new types of ways for Employee data to be written, perhaps via HTTP/HTTPS by creating abstractions, and without modifying any of our previous code! No rigidity--the desired outcome.


The Interface Segregation Principle


Clients should not be forced to depend upon interfaces that they do not use. My favorite version of this is written as "when a client depends upon a class that contains inter- faces that the client does not use, but that other clients do use, then that client will be affected by the changes that those other clients force upon the class." Kinda sounds like the inheritance specific single responsibility principle.


Sources



Wednesday, December 16, 2009

I'm All About ASP.NET MVC

Tomorrow, when I walk the halls of my corporate job and find myself caught in an eye-to-eye stare-down with a Java web developer I may not be thinking the same thoughts. I've had my share of Java vs. .NET arguments over the years and I hate to admit it but the Java people have a lot going for them. Often times Java is the runway for .NET's future look. Thus it is to no surprise now that we've gotten our hands on ANT, Hibernate, and jUnit we follow up by stealing Swing. .NET makes its rounds with all of Java's daughters--which happens to be one of my favorite interjections in a .NET vs Java discussion. You should see their faces.

What is ASP.NET MVC?


Every ASP.NET developer I've talked to in the last few days about MVC have asked me this question, which kinda surprised me. In general, many of them have never heard of MVC at all. My first interaction with MVC occurred after reading an article over at A List Apart about JavaScript MVC--which is my preferred client-side architecture. Great article.
MVC stands for Model-View-Controller. When you think about web work, isn't it generally you got some data(Model) that you present to the user(View) and allow them to interact with(Controller)? I know that about sums up my work experience. ASP.NET MVC is .NETs response to the Java/Ruby MVC craze. All us .NET-ers are definitely a few seasons behind.
Remember when the .NET web platform released? Almost a decade ago. Honestly though, the web was still emerging as a platform for applications. In my opinion, when Microsoft released ASP.NET they were thinking "how can we easily convert our application developers into web developers" and not "how can we make the best web development platform out there?" They've reaped the consequences for it too-- such as the ViewState, lack of true architecture guidelines, the page life-cycle, oh and how about their ASP.NET Ajax(Atlas) implementation? Horrendous. All ease of use and no performance. ASP.NET MVC is Microsoft's way of trying to come clean. Let's try to be more forgiving.

Bottom Line: Whats the Code Like


Amazing. Simply amazing. I've been working through the Wrox Professional ASP.NET MVC book and have over and over again found myself making "exactly!" outbursts. I'm not going to go through a complete overview of the MVC framework, but here are a few "highlights:"

Using LINQ to SQL as Your Model


ORMs (object relational mappers) are pretty popular right now--especially NHibernate. No surprise, they save you a ton of time defining classes and writing SQL statements. After you have a database table set up and accessible in your Visual Studio Database Explorer, a little Solution Explorer right-click add-new > Data > LINQ to SQL and you're rolling. With the class that is created, one can alter database data by easily interacting with the generated class. Like:

// Retrieve Dinner object that reprents row with DinnerID of 1
Dinner dinner = db.Dinners.Single(d => d.DinnerID == 1);

// Update two properties on Dinner
dinner.Title = "Changed Title";
dinner.Description = "This dinner will be fun";

// Persist changes to database
db.SubmitChanges();

And yes, it supports transactions, SPROCs, views, checks your data for SQL Injection attacks, and is easily extendable using partial classes and partial methods. Not really an MVC feature, but new to me.

ASP.NET MVC HTTP Post Handling


This is one of the things that really impressed me. A situation I find myself programming over and over again is doing GridView FindControl()s to grab an inputted value. With MVC, you can create a method in your controller that accepts one of your model classes, completely avoiding all of the monotonous value/control finding work. The values are automatically mapped using .NET Reflection.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Dinner dinner)
{
if (ModelState.IsValid)
{
try
{
dinner.HostedBy = "SomeUser";
dinnerRepository.Add(dinner);
dinnerRepository.Save();
return RedirectToAction("Details", new { id = dinner.DinnerID });
}
catch
{
ModelState.AddRuleViolations(dinner.GetRuleViolations());
}
}
return View(dinner);
}


Theres More


I didn't even get to talk about Validation, separation of concerns, SEO-friendly URLs and more but... I need to get back to studying.

Tuesday, December 15, 2009

Using the YAML CSS Framework in ASP.NET

I've written the same CSS code at least a million times-- center the body, float the navigation, fix IE6--but I'm never going to do it again. Why? Because recently I've stumbled upon CSS Frameworks. Amazing stuff!

What is a CSS Framework?



Its kind of like a set of web page building blocks. Remember playing with Lincoln Logs as a child? They were great. However, imagine if instead of all that pre-cut goodness you had to fashion your own pieces. You'd be missing fingers! (Who gave that kid a knife?) Or bare minimum, trading play time for work time! Strangely enough, developers do just so. Essentially they are ignoring the vast amount of browser-specific tweaking that web design necessitates. Aren't there other areas of your project you'd rather be working on (like the ones that actually demand originality)?

The YAML CSS Framework


The folks over at YAML.de have run their product through the browser-specifc gauntlet. Emerging unscathed is a solid, well-thought, and well-documented package that you can quasi-drop into your web application. I need to reiterate the "well-documented." In fact, if I was teaching a class on web design I would use the framework's free pdf as it's textbook. Don't know what a float is? Or why they're not working in IE6? Any CSS novice should check it out. Unfortunately I did just write quasi-drop...



The Downside of the YAML CSS Framework


It's not all roses. In fact, its rather intimidating to jump into. The first time I downloaded it I felt as though the css files had been arranged by Stephanie Toppin(art featured). After consulting the documentation I was finally able to see the method through the madness. To elaborate on said madness:
  1. The framework relies heavily on CSS imports-- an Ajaxian no-no.
  2. The ultra-cool form styles rely on setting the <form> tag's class. (You know, that thing in ASP.NET that usually surrounds the entire page.) That is also a no-go.
  3. The folder structure makes me want to pull my hair out. I'm serious.

Making it Work in ASP.NET


To start out, lets put all the files in one place. Not only does this remove our CSS import issues, but also will decrease our HTTP requests and therefore improve our page's performance. So, that means:
  1. Taking YAML's base.css, content.css, form.css, and print.css and putting all their contents into one file. Done and done. Situation=averted. You will still need to reference the IE-specific fixes page separately, however.
  2. In order to rectify our form tag issues, all we need todo is change all the code that says form.yform to just .yform. Easy! Now us .NET-ers can wrap our wannabe forms in a div.yform and reap the rewards of all of YAML's pre-styled goodness.
I tend to keep all of my custom css classes in a section at the bottom of my concatenated YAML document.

Get Back to Work


... on things that deserve your attention!