A coworker ran into this one today as he was trying to call an old school web service using jQuery Ajax/Post. Keep throwing an exception/returning a 500 error. After some searching, both google and soul, it turns out that services that are expected to be used with scripts (Javascript or Jquery in this case) need the attribute ScriptService. Yeah, that’s it. The silly and cryptic message is really just an attribute needed on the code file above the service class. Go figure.
Category: C#
C#: Create Dynamic Image For Byte Array Data
So you have a unit test, but maybe for some reason you need to create an object that has a constructor that needs a byte array. Maybe for some reason that byte array needs to have more than 0 length. Maybe you don’t have any of this and you are just curious. Maybe I’ve said maybe too much.
Well in any case, here’s a way to do this:
using System.Drawing; using System.IO; private byte[] GetBitmapData() { //Create the empty image. Bitmap image = new Bitmap(50, 50); //draw a useless line for some data Graphics imageData = Graphics.FromImage(image); imageData.DrawLine(new Pen(Color.Red), 0, 0, 50, 50); //Convert to byte array MemoryStream memoryStream = new MemoryStream(); byte[] bitmapData; using (memoryStream) { image.Save(memoryStream, ImageFormat.Bmp); bitmapData = memoryStream.ToArray(); } return bitmapData; }
And presto you have a fake image to send through. Can’t get much easier than that. Well maybe it could but not in this example. Why are you judging me? I’m just trying to help. You know what? Go away. I don’t want you around here anymore. You and those beady, judging eyes. Always looking… Never stopping… WHY DON’T YOU LEAVE ME ALONE?!?!?
Connect Your Web App To Twitter Using Hammock & C-Sharp
The Challenge
Recently I was challenged with the task of connecting a web application to Twitter and sending out a tweet. This article will focus on the connection to Twitter, saving the talk about sending out a tweet for another article. Having used TweetSharp last year, I thought I would check for an updated version of it and be on my way. When I got to CodePlex, I learned that support for TweetSharp had pretty much stopped in May and the developers had moved onto Hammock.
After reading their explanation, and suggestions for future development, I decided to use Hammock to connect my web application to Twitter. What is Hammock you ask, in their own words, it is a REST library for .NET that greatly simplifies consuming and wrapping RESTful services. In plain English, it makes integrating REST APIs a snap. If you want an explanation of what REST is, please check out Wikipedia.
I have to give credit to ColinM, author of this forum post on CodePlex, for giving me the basis of this code.
Before The Code
Before you can connect your web application (or desktop application) to Twitter, you need to register with Twitter. This is not the same as creating a new Twitter account, which you will need, instead this is telling Twitter that your application is going to want to interact with it. To do this, go to http://twitter.com/apps/new.
Let’s talk about some of the settings you will need to configure when you register your application.
- Application Type – For this example, choose Browser (Web). If you choose Client (Desktop), you will see the Callback URL option go away.
- Callback URL – This is the URL Twitter will send your users to after they Allow or Deny your request to connect your application to Twitter. I would recommend entering this as your production URL. In this article I will show you how to override this setting in your code.
- Default Access type – If your application is only going to consume data from Twitter, you can leave it at Read-only, but if you intend on posting tweets you will need to select Read & Write
- Use Twitter for login – If you want to allow users to authenticate via Twitter, check this box.
After you register your application, Twitter will give you the information you need to connect. You will need to take note of your Consumer key and Consumer secret. This key/secret combination is unique to your application. The Request token URL, Access token URL and Authorize URL are the same for pretty much everyone. Now that we’ve established your secret identity with Twitter, we can get started.
A Four Step Process
To make my example as simple as can be, I broke it down into four steps. Also, I set up this example using two web forms. Steps One and Two are called from GetTwitterRequest.aspx and Steps Three and Four are called from ProcessTwitterResponse.aspx. You can do this from the same form if you wish. If you’re not into web forms, you can call it from an ASP.NET MVC View as well.
For simplicity, I have setup a couple of private strings called CONSUMER_KEY & CONSUMER_SECRET. Yeah, you guessed it, those are the values we needed from Twitter. You can store these in a database, in your web.config, or hard code them right in your C# code, that’s all up to you.
For the purpose of making a fast, lightweight example, I used Session to store certain information. You will probably want to store the accessKey and accessSecret in a database. You will want to associate these values with your user in your system. We will talk about each key later on.
Here are the related “usings”:
using System.Net;
using Hammock;
using Hammock.Authentication.OAuth;
using Hammock.Web;
Also, many developers have found the need to include the following line of code when talking to Twitter. I can’t explain why.
ServicePointManager.Expect100Continue = false;
Step One: Identify Your Application
var credentials = new OAuthCredentials
{
Type = OAuthType.RequestToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = CONSUMER_KEY,
ConsumerSecret = CONSUMER_SECRET,
CallbackUrl = "YOUR_CALLBACK_URL_GOES_HERE/ProcessTwitterResponse.aspx",
};
var client = new RestClient
{
Authority = "http://twitter.com/oauth",
Credentials = credentials
};
var request = new RestRequest
{
Path = "/request_token"
};
RestResponse response = client.Request(request);
Before you can connect your application with Twitter, you need your application to identify itself. Above you will find a pretty standard piece of code that you can use to do that. You won’t have to change much of this code to get it working with your application.
First, you need to instantiate your credentials. To do this, you’ll need to provide your CONSUMER_KEY, CONSUMER_SECRET, and Callback URL. Use your key/secret combination provided by Twitter. Your Callback URL is the URL of the page you want to process the response from Twitter. As a note, Twitter only supports hmac-sha1 signatures. After you’ve created your credentials, you’ll need to instantiate a RestClient and RestRequest.
In short, the RestClient uses your Credentials to execute your RestRequest. When you execute your RestRequest you will need to capture the RestResponse for use in Step Two.
Step Two: Ask For Permission To Connect
var collection = HttpUtility.ParseQueryString(response.Content);
Session["requestSecret"] = collection[1];
Response.Redirect("http://twitter.com/oauth/authorize?oauth_token=" + collection[0]);
In step two, we are going to parse the RestResponse from our RestRequest in Step One. If Twitter recognizes your application, you will receive a temporary key/secret combination that we’ll call requestKey and requestSecret. This key/secret combination will be used to request authorization to connect your application to your user’s Twitter account. It is important to note that this combination is good for one request. Once you use them, you’ll have to get a new requestKey and requestSecret to make new authorization requests.
I used HttpUtility.ParseQueryString to break apart the querystring in the RestResponse. The first part is going to be your requestKey, and the second part is your requestSecret. To actually make the request, you are going to send your requestKey back to Twitter. You will want to store your requestSecret for use in Step Three. For this example I stored the requestSecret in Session. You can store this in a database if you want, but due to it’s temporary nature, storing it in Session or a Cookie should work just as well.
When you redirect your user to Twitter for authorization to connect your app to their Twitter account, they should see a screen similar to the one below.
Step Three: Wait For Twitter’s Response
var requestToken = (String)Request.QueryString["oauth_token"];
var requestSecret = (String)Session["requestSecret"];
var requestVerifier = (String)Request.QueryString["oauth_verifier"];
var credentials2 = new OAuthCredentials
{
Type = OAuthType.AccessToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = CONSUMER_KEY,
ConsumerSecret = CONSUMER_SECRET,
Token = requestToken,
TokenSecret = requestSecret,
Verifier = requestVerifier
};
var client2 = new RestClient()
{
Authority = "http://twitter.com/oauth",
Credentials = credentials2
};
var request2 = new RestRequest
{
Path = "/access_token"
};
RestResponse response2 = client2.Request(request2);
At this point, your application will be waiting for Twiiter to send back a response. It will do so by redirecting the user to the URL you sent Twitter in Step Two. This step is very similar to Step One, with the exception that we will be sending more data. Besides your CONSUMER_KEY and CONSUMER_SECRET, you will need to provide your requestToken and requestVerifier, which you get from Twitter’s call to your Callback URL. You will also need your requestSecret which you stored in Step Two.
Again you will use a RestClient to execute your RestRequest. When you execute your RestRequest you will need to capture the RestResponse for use in Step Four.
Step Four: Remember Your Secret Handshake
Now all we need to do is parse the response from Twitter and save the token and secret they return.
var accessResponseCollection = HttpUtility.ParseQueryString(response2.Content);
Session["accessToken"] = accessResponseCollection["oauth_token"];
Session["accessSecret"] = accessResponseCollection["oauth_token_secret"];
Twitter will respond, if the user allowed the connection, with a permanent accessToken and accessSecret. This IS your secret handshake with Twitter. You will want to store the accessToken and accessSecret in your database. I know I stored it in Session, but that’s because I was too lazy to wire this example to a database. Using you accessToken and accessSecret in future Twitter API calls is how you connect to your user’s Twitter account to your application. This token and token secret do not expire unless the user removes the connection to your application via the Twitter web site.
In closing, all this article really does is help you connect with Twitter, you will have to find something to do with this connection. It should also give you a light understanding of REST API calls as well as some insight on the OAuth authentication process. There will be future articles to help you tweet from your application or get data from Twitter to display.
To find out more about the technologies in this article, check out the following links.
Hammock – http://hammock.codeplex.com/
OAuth – http://oauth.net/
Twitter API – http://apiwiki.twitter.com/
MVC and Table Inheritance: Part 1
PART 1: Setting up the database and Entity Framework Model
Okay, so say you need to create an internal IIS hosted web application that acts as a portal for managing internal training courses. You could do a simple ASP.NET web forms app…. but what’s the fun in that?!? Besides, you know that you’re going to need to expand this thing regularly to handle different course types and provide different layers of permission depending on the user. Well, as it happens, ASP.NET MVC is a really nice way to address such a situation (especially if you’re already familiar with using Java and Struts).
Before we get started you’ll need to get the usual downloads from Microsoft found here: http://www.asp.net/mvc/
Create ASP.NET MVC Project
Then you’ll need to open either Visual Studio 2008 or the free Visual Web Developer 2008 Express and select the File->New Project menu item.  This will bring up the “New Project” dialog. To create a new ASP.NET MVC application, we’ll select the “Web” node on the left-hand side of the dialog and then choose the ASP.NET MVC Web Application template and enter the following:
- Name: TrainingPortalMVC
- Location: C:\Development
- Solution: Create new Solution
- Solution Name: TrainingPortalMVC
- Create directory for solution: checked
SQL 2005 Database Tables
To setup your MVC project so it can use the Microsoft Entity Framework:
- Right-click the App_Data folder in the Solution Explorer window and select the menu option Add, New Item.
- From the Add New Item dialog box, select SQL Server Database, give the database the name TrainingPortalDB.mdf, and click the Add button.
- Double-click the TrainingPortalDB.mdf file to open the Server Explorer/Database Explorer window.
- Click on the Database Diagrams folder and say yes to create a new diagram
- Setup your tables to look like this:
Create the Entity Framework Model
Steps
- Right-click the TrainingPortalMVC project.
- Select in the menu Add New Item
- Select from the Templates: ADO.NET Entity Data Model
- Enter the name TrainingPortalEDM.edmx then click Add
- Choose the Generate from database then click Next>
- For the data connection, select TrainingMvc.mdf make sure the checkbox is checked and the connection settings is TrainingMvcEntities then click Next>
- Check all tables in the database except for the sysdiagrams (dbo) one and make sure the Model Namespace is TrainingMvcModel. Click Finish
Suggested Modifications
- Open the ModelBrowser panel in Visual Studio 2008, and expand the EntityContainer->EntitySets and add “Set†to the end of your Entity Sets….. Trust me, it will make things much less confusing later…
When you’re done you should have something like this:
This is the end of Part 1…… Calm down, I know you can’t possibly wait for more answers, but a girl’s gotta have a little mystery to keep things interesting. Good luck and hopefully this will help you shed another angle of light to get a better idea of how you want to approach this type of application until I can finish procrastinating…. I mean preparing Part 2…..
ASP.NET MVC: Attributes and Semi Dynamic Check for Request Parameters
If I were self involved I would say something silly like IN THIS AWESOME POST but I’m not. However in this post that is awesome I gave some examples of how to use attributes to set defaults or just check to see if an incoming id could be matched to a record somewhere… Sorry lost my track of thought. Watching the begining of Transformers… You know the part where it could have been good.
Anyway, I figured I’d add another debatable use for an attribute, the CheckForGivenRequest one. Basically in the other post I had something that was specific it was checking for, this is used if you are checking for a request parameter but you don’t want to make an attribute for each and every one of them.
//This is so you can use it many times on the same method //I know, I know... duh [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class CheckForGivenRequestAttribute : ActionFilterAttribute { //The constructor to set what should be looked for //Default amount is what it should be set if not there public CheckForGivenRequestAttribute(String requestParameterName, Object defaultAmount) { DefaultAmount = defaultAmount; RequestParameterName = requestParameterName; } public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); //Check the extra request parameters (ie &someId=1) for if it exists //If it doesn't exist, then add it if (!filterContext.ActionParameters.ContainsKey(RequestParameterName)) { filterContext.ActionParameters.Add(RequestParameterName, null); } //If it's null set to the default filterContext.ActionParameters[RequestParameterName] = filterContext.ActionParameters[RequestParameterName] ?? DefaultAmount; } //Just the properties, nothing to see here. Go away... private Object DefaultAmount { get; set; } private String RequestParameterName { get; set; } }
And then the use of it:
[CheckForGivenRequestAttribute("someStupidId", 1)] public ActionResult INeedAnExample(Int32 someStupidId) { ... }
Now you might ask why not make that attiribute generic to avoid boxing.
Why not make that attribute generic to avoid boxing?
Glad you asked. Turns out that you can’t make attributes generic. Aparrently it’s somwhat debatable why but not possible at the time being. Besides, the ActionParameters collection is <String, Object> anyhow, so at some point any stuct would be boxed anyhow.
On a side note, I never noticed this before, but when one of the non descript Autobots crashes near a pool, some kid is there to ask if he is the Tooth Fairy? Seriously? Are kids really that dumb? Cause every picture I’ve seen of the Tooth Fairy has been a 20 foot tall metal thing with no discernible features.
Entity Framework: Reusable Paging Method
OBSOLETE… sort of. Found an issue with this and am posting the issue today. (07/21/2009)
A while back I decided to show some paging stuff and I forgot that recently, well ok in the last few months, I actually put together a sort of generic extension method to take care of most of the paging situations I was running into. Reason being is I got tired of writing the same method over and over. I figured I’d share it in hopes that somehow, somewhere, it would keep someone’s dream alive. That and I figured I needed to make up for not posting for a while… which to some of you might have been a good thing.
Anywho, it’s not to difficult actually. Small note though, when reading the code you will see the TotalCountOfPages method and the GetRealPage method. If you can’t figure out what those are then I just don’t know what to do. (HINT: They are linked somewhere in this very post! Side note: This post is on track to match the normal self linking per post quota on atypical Codding Horror post)
public static IList<K> GetListForGrid<T, K> ( this ObjectQuery<T> query, //Extension method syntax... basically takes in any SomeEntities.SomeTableRepresentation Expression<Func<T, Boolean>> somethingEqualsSomething, //Where clause Expression<Func<T, K>> selectClause, Expression<Func<K, IComparable>> orderBy, //Turns out order by just needs anything that is IComparable Int32 pageNumber, Int32 numberToShow, out Int32 realPage, out Int32 totalCountOfPages ) { IList<K> returnValue; //Get the total count of the items. Need this to do proper paging. Int32 totalItemCount = query .Count ( somethingEqualsSomething ); totalCountOfPages = TotalCountOfPages(totalItemCount, numberToShow); realPage = GetRealPage(totalCountOfPages, pageNumber); returnValue = query .Where ( somethingEqualsSomething ) .Select ( selectClause ) .OrderBy(orderBy) .Skip(numberToShow * realPage) .Take(numberToShow) .ToList(); return returnValue; }
As you can see there are a lot of expressions going on and that’s the way this works. It takes care of the annoying stuff that you would have to copy an paste while you supply it the stuff that changes like what you want to select and what the needed items have to match to be selected. Even has something for an order by. What the usage look like?
ToolEntities.Tools.GetListForGrid ( something => something.SomethingId == passedInSomethingId, //Where clause found => found, //Select: Simple here. Usually I use classes to hold info... next post found => found.Name, //Order by pageNumber, amountToShow, out realPage, out totalCountOfPages );
Really simple, eh?
Why totalCountOfPages and RealPage out? Well the whole idea is that this infomation is valuable to the picker control you will be constructing outside this method call. RealPage is nice for showing what page the pager is on and how to figure out what the previous and next pages will be. TotalCountOfPages is useful for the last page possible. Now the nice thing about the RealPage method is that it won’t give you a non existent page. It will only give you the best possible page if the pageNumber parameter is over the possible amount of pages.
Also do notice that this is an extention method meant to be used with the Entity Framework’s built in system of handling the Table representations say ToolEntities.Tools.(Method will show up here in intellisense). This makes it cleaner to me than having to pass in the actual current context. As in:
GetListForGrid(ToolEntities.Something, …) vs ToolEntites.Something.GetListForGrid(…)
In the end, either way is fine.
Linq Join Extension Method and How to Use It…
I don’t like using the query syntax when it comes to Linq to AnythingButTheKitchenSink . Not sure why. Mostly, I guess, is that I seem to have a liking for Funcs and Actions to the point of stupidity and although you can work them into the query syntax, it just doesn’t look right.
Now with most of the Linq methods like Where or First, it’s simple once you understand lamdba expressions:
.SomeMethod(someField => someField.Property == value);
Now what about join?
So inner selector with an outer selector and a selector selects a selecting selector. Right got it.
Well let’s try to break it down. First part is
this IEnumerable<TOuter>
So being that this is an extension method meaning this is the collection you are using this method on.
IEnumerable<TInner> inner
So second field must be the list you want to join to. Ok so far.
Func<TOuter, TKey> outerKeySelector
Now this is where it gets a little odd looking. We know we have Outer and Inner lists so there needs to be a way to join on something. Say Outer is User and Inner is UserAddress. Most likely you will have a UserID on both lists. If not, you do now. So basically what this part of the method is saying is “Give me the stupid key on the Outer (User) list that I should care about.”
, user => user.UserID,
Next part:
Func<TInner, TKey> innerKeySelector
Pretty much the same thing, except now it needs the key from the Innerlist (UserAddress):
, address => address.UserID,
Now for the fun part:
Func<TOuter, TInner, TResult> resultSelector
Sa…say what? Ok this may look weird at first but you’ll hate yourself for not seeing it. It’s just asking you what to select from the two lists as some kind of hybrid object. See, you have to remember that with these linq methods, each method will produce a list. You can’t just chain them together and have it remember every list you’ve made:
user.Where(user => user.UserID > 1) // gives me a list of users .Select(user => new { user.UserName, user.UserAddress, user.UserID } //Gives me new items with user name, address, and user id
From this simple method chain, the end list is NOT the same as the one you started with or the one produced by the where method.
The last part of the Join method needs you to tell it what it’s going to produce from this join. Now it probably could just guess and include both lists, but that could be seen as sloppy and ultimately this gives you the choice of what exactly needs to be taken after the join. So:
, (user, address) => new { user, address});
So in this case, the newly created and joined list with be a list of items that have a user and address attached to it much like if you had a list of:
class UserAddressHybrid() { public User user { get; set; } public UserAddress userAddress { get; set; } }
So in other words, WHAT DO YOU WANT YOUR RESULTS TO LOOK LIKE?
In full it would look something like:
user.Join(address => address.User.UserID, //IEnumerable<TInner> inner user => user.UserID, //Func<TOuter, TKey> outerKeySelector address => address.UserID, //Func<TInner, TKey> innerKeySelector (user, address) => new { user, address}); //Func<TOuter, TInner, TResult> resultSelector
Not so hard anymore, is it? You can start kicking yourself now.
ConfigurationManager And AppSettings… A Wrapper Class Story
You can file this under “Do I really need this?” but for now I kind of like it. That, however, may change in the next hour.
The idea is simple, create a class that uses the ConfigurationManager AppSettings NameValueCollection (Triple Combo!) but only presents properties that represent the keys in the .config file. This way there is no guessing of how the key is spelled or that that type returned is converted to something it should be. (Say you have a numeric value in the .config file) Now this doesn’t seem like a big deal, but I’m not happy with something that is just simple like:
public String SomeKey { get { return System.Configuration.ConfigurationManager.AppSettings["SomeKey"]; } }
Oh no, that’s just not good enough. Call it divine intervention. Call it spontaneous brilliance. Call it whatever the guy that invented the corn dog had. But what I came up with is far better. (And by better I mean more complex)
Remember, the idea isn’t to have to grab just the value from System.Configuration.ConfigurationManager.AppSettings but also to have it be typed on the way back. Now we know this to be true: I am awesome. What we also know to be true is that the value held in the appSettings area of the .config file is going to correspond to a value type but is going to be read in as a string. If you’ve read some of my posts (Which I assume you haven’t), you might have stumbled upon this little gem and know that I already have something to convert from a string to pretty much any value type. (Those having a TryParse method) So the converting part is already done, but what about the getting?
protected static T? GetValueFromConfiguration<T>(String key) where T : struct { T? returnValue = null; if (System.Configuration.ConfigurationManager.AppSettings[key] != null) { returnValue = System.Configuration.ConfigurationManager.AppSettings[key] .ConvertTo<T>(); //MY AWSOME CONVERTTO METHOD!!11 } return returnValue; }
Ok so you can see, this is really simple. I check to see if the key exists, get the value from the .config file, and convert to whatever I said it should. In use this would be:
public static DateTime? TestDate { get { return GetValueFromConfiguration<DateTime>("TestDate"); } }
Now you might have noticed something about this… yes besides the fact that it’s Mentos fresh. First, the method returns nullable versions. The reason for doing this is you really don’t know what the value will be in the .config file. Say this was an integer and you returned just a normal integer. (Non nullable) What would you set the value to? Sure you could do minimum value but COULD mean that there was a value in the .config file. This is more of a design choice though.
Second is that the method doesn’t cover strings. This is an ouch due to how nullables and strings work. You can’t return a nullable string since string doesn’t fit in the non nullable value category. This is a real pain but easily overcome with a non generic overload:
protected static String GetValueFromConfiguration(String key) { String returnValue = null; if (System.Configuration.ConfigurationManager.AppSettings[key] != null) { returnValue = System.Configuration .ConfigurationManager.AppSettings[key]; } return returnValue; }
See? Easy way to side step the problem. There might be a better way to handle that, but not sure at this point. Something to revisit I suppose. Oh and here’s the whole class for the hell of it:
public class BaseConfigurationManager { private const String SOME_KEY = "SomeKey"; protected static T? GetValueFromConfiguration<T>(String key) where T : struct { T? returnValue = null; if (System.Configuration.ConfigurationManager.AppSettings[key] != null) { returnValue = System.Configuration.ConfigurationManager.AppSettings[key] .ConvertTo<T>(); } return returnValue; } protected static String GetValueFromConfiguration(String key) { String returnValue = null; if (System.Configuration.ConfigurationManager.AppSettings[key] != null) { returnValue = System.Configuration.ConfigurationManager.AppSettings[key]; } return returnValue; } public static String SomeKey { get { return GetValueFromConfiguration(SOME_KEY); } } }
Oddly enough I spelled “spontaneous brilliance” correctly the first time around but thought “numeric” had a silent ‘b’. Go figure. Should have finished middle school.
I are tupid
This may be novel or really dumb, but I like it. Say you want to convert a Dictionary to a List of KeyValuePairs that are sorted by something within the dictionary Key or Value. Don’t ask why, just go with it. You could do this:
Where someDictionary is Dictionary<Type, string> :
List<KeyValuePair<Type, String>> dataSource = new List<KeyValuePair<Type, String>>(someDictionary); dataSource.Sort(new SomeComparer<KeyValuePair<Type, String>>("Value", true));
To:
var query = from keyValuePair in someDictionary orderby keyValuePair.Value select new KeyValuePair<Type, String>(keyValuePair.Key, keyValuePair.Value); SomeMethod(query.ToList());
If nothing else, you don’t have to create or implement a System.Collections.IComparer class to use the .Sort method. That seems worth it. That and I think it just plain looks better, but that just me. If I am completely wrong here, refer to the title of this post. Just a thought really.