Apply this attribute to a method to force that method to be synchronous. Be careful as this does not sync it the call on a per request basis. So if you have thousands of requests for this method at the same time, they’ll all be waiting.
public class LockAttribute : ActionFilterAttribute
{
private static readonly object _firstLock = new object();
private static readonly object _lockObj = new object();
private static bool isLocked = false;
private bool hasLock = false;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
lock (_firstLock)
{
if (isLocked)
{
System.Threading.Monitor.Enter(_lockObj);
isLocked = hasLock = true;
}
else
{
isLocked = hasLock = System.Threading.Monitor.TryEnter(_lockObj);
}
}
base.OnActionExecuting(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
if(hasLock)
System.Threading.Monitor.Exit(_lockObj);
base.OnResultExecuted(filterContext);
}
}
Here is a static class used to get the name of one of the properties on your class.
public static class MemberName<T>
{
public static string Of(Expression<Func<T, object>> expression)
{
MemberExpression memberExpression;
if (expression.Body.NodeType == ExpressionType.Convert)
memberExpression = expression.Body.To<UnaryExpression>().Operand.To<MemberExpression>();
else
memberExpression = expression.Body.To<MemberExpression>();
return memberExpression.Member.Name;
}
}
You can call the class as follows:
string heightPropertyName = MemberName<Person>.Of(x => x.Height);
This allows us to stop using ‘magic’ strings that are not tightly coupled with the actual property. If you change the name of your property, using this class you can always get the new string value of that property. This is most useful when you’re databinding, or passing the name of the property to nhibernate.
This code uses an extension method call To
public static T To<T>(this object obj)
{
return (T)obj;
}
Without the extension method line 8 becomes the following:
memberExpression = (MemberExpression)((UnaryExpression)expression.Body).Operand;
Here is a snippet for rendering a partial view to a string. After you make a string from the view, you can pass the html as a json result. This let’s you have more control over the actions you can take in your javascript when you receive your response.
public string RenderPartialToString(string controlName, ViewDataDictionary viewDataDictionary)
{
var viewContext = new ViewContext();
var urlHelper = new UrlHelper(this.ControllerContext.RequestContext);
var viewPage = new ViewPage
{
ViewData = viewDataDictionary,
ViewContext = viewContext,
Url = urlHelper,
};
var control = viewPage.LoadControl(controlName);
viewPage.Controls.Add(control);
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
using (var tw = new HtmlTextWriter(sw))
{
viewPage.RenderControl(tw);
}
return sb.ToString();
}
What’s important here is that I pass in the viewdatadictionary. I do this so that I can build the modelstate before passing it in to be rendered. In my particular use case I already had a form that was rendering a validation summary and I needed to keep this functionality. So I add my model errors to the new view data dictionary, and the erros render on the partial view. I then return a json result with a false success and the rendered html.
Here’s is an example of the controller action.
public ActionResult VerifyThisCode(string code)
{
var dataDictionary = new ViewDataDictionary();
if(!ValidateCode(code, datadictionary))
{
return Json(new { success = "false", view = RenderPartialToString("~/Views/Verify/BadCode.ascx", datadictionary) });
}
if(NotLoggedIn())
{
dataDictionary.ModelState.AddModelError("NotLoggedIn", "Please, log in or sign up to redeem this code.");
dataDictionary.Model = Request.UrlReferrer.AbsolutePath.ToString();
return Json(new { success = "false", view = RenderPartialToString("~/Views/Shared/LoginSignup.ascx", dataDictionary) });
}
Code validCode = _codeRepository.GetCode(code);
dataDictionary.Model = Code;
return Json(new { success = "true", view = RenderPartialToString("~/Views/Verify/GoodCode.ascx", dataDictionary) });
}
I can change what model I set on the data dictionary depending on which view I want to use. Or set none at all. Now finally the javascript that uses this.
$('#validateCode').click(function(event) {
event.preventDefault();
$.ajax({
url: path + 'Verify/VerifyThisCode',
data: $('#code').val(),
success: function(data) {
$('#codeContent').html('');
$('#codeContent').append(data.view);
$('#codeRedeemed').fadeIn();
if (data.success == 'true') {
RefreshMySelectionOfCodes();
}
}
});
});
What this does is show a modal dialog with my partial view rendered into it. But only in the event of a success do I refresh the selection of codes.
Here are a couple real handy enum exntensions to have around. This first one returns all the vaues of the enum in a list. This is perfect for generating dropdown lists or selections. The important aspect to note here is that the list will always contain the latest additions to the enum. So you don’t have to go back and rewrite your dropdowns for the enum, it does it for you.
public static IEnumerable<T> GetEnumValues<T>(this Enum obj)
{
IList<T> values = new List<T>();
foreach (var val in Enum.GetValues(typeof(T)).Cast<T>())
{
values.Add(val);
}
return values;
}
This next one turns the enum value into a more readable form. Automatically parsing out camel casing into spaces. This particular regex statement requires a preceeding and following lower case letter to space. The regex is followed by simple extension methods, for both string replacement and enum replacement.
private const string RegExEnglishPattern = "(?<!^)([A-Z][a-z]|(?<=[a-z])[A-Z])";
/// <summary>
/// Correctly spaces the enumeration value to make it english-like.
/// </summary>
/// <param name="e">The enumeration.</param>
/// <returns>The english-like form of the enumeration value.</returns>
public static string ToEnglish(this Enum e)
{
return Regex.Replace(e.ToString(), RegExEnglishPattern, " $1");
}
public static string ToEnglish(this string value)
{
return Regex.Replace(value, RegExEnglishPattern, " $1", RegexOptions.Compiled).Trim();
}
So I had a silly idea to create a game for the Android operating system. It started out innocently enough, but my developer instincts took over and I just had to have the saving/loading of a player done before moving on with the rest of the game. The only problem was I could not figure out why Android would throw a fit whenever I tried to create a file. I looked everywhere online and no one could shed an insight to my NullPointerException. Feel free to skip my rant and read the last paragraph for the solution.
I spent more weeks on this than I care to admit. To my defense I didn’t work that much since my frustrations prevented me being able to deal with it for too long at one time or in back to back days. Indeed it was most frustrating, the log was not detailed enough, the stack trace offered no further assistance and without more details I could not provide a better search query to google to find my answers.
Luckily my determination and my belief that when something isn’t working when it should; it’s not me, it’s them. I have witnessed many of my peers utter disbelief that software and framework vendors can do no wrong. They believe wholeheartedly that they simply are not programming correctly; and that I am arrogant for believing it’s not me, it’s them. My arrogance is not unfounded; I happen to be proved right all too often. I would rather not, however; as I would rather have tools that just work. But I digress, let me get to my point.
I was tryign to create a simple .xml file so that I could serialize an object to the file system for storage. I figured an easy task for saving and storing player data. Much simpler than the SQLlite database alternative. I created a FileService for my game. I have been a .net developer for 2 years now and I have grown accustomed to splitting out my classes as often as possible. Seperating my code into logical objects to keep my code clean and organised.
My fileservice sole purpose was to create files, save players to them, check if files already exist, and return a list of all players. I could not do any of these. It seems the file system java developers perfer is a clusterfuck of directories. That’s just a quirk and not the real issue. The real issue is that my FileService could not create a file. An exception is throw with a nullpointer exception. best I could find out was that the operation failed; well no shit. There was no end to the combinations I tried to create a damn file and none of them worked and none of them gave me anymore detailed information.
I pulled up the API demo, and ran it. Success. Wait, what? It worked fine and my code was just like theirs; until it finally hit me that I had a seperate class doing the File IO operations. So on a hunch I placed my file creation in the main class and presto! I can create FILES! I don’t know why but it works, it does and I’m finally able to press on. Organization be damned, I just want to get this program started before I quit it. Up next, figuring out to check if a file exists. Did I say the directories were a clusterfuck? Where, oh where did my new file go …
Open your xps file or generate it to a memory stream.
private MemoryStream XPSFile;
private const string pack = "pack://temp.xps";
private Uri uri = new Uri(pack);
var pkg = Package.Open(XPSFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
PackageStore.AddPackage(uri, pkg);
var doc = new XpsDocument(pkg, CompressionOption.SuperFast, pack);
Now you have an xps document in memory. You can set it to view in the document viewer, or print it off, or what else you can think of.
This is a simple extension method that can be added to retrieve a bitmap of any control. It can be as specific as a text box, or image viewer, or as general as your entire application.
public static Bitmap GetImage(this Control obj)
{
obj.CreateGraphics();
var bmp = new Bitmap(obj.Width, obj.Height);
obj.DrawToBitmap(bmp, new Rectangle(0, 0, obj.Width, obj.Height));
return bmp;
}
You can easily find the differences between datasets, dataviews, data tables or any collection using Linq and Enumerables. This is useful if you just want to view the changes that have been made, or if you want to determine if the two datasets match each other, say for testing purposes.
Our first example is a simple list. First convert both lists to enumerables. Then intersect the two.
Enumerable<SomeObject> diff = List<SomeObject>.AsEnumerable().Intersect(List<SomeObject>.AsEnumerable());
Our diff enumerable will contain all the elements that are different. If you already have enumerables, then this is as simple as calling intersect. Any elements in the diff list will be the elements that do not occur in both lists.
Assert.IsTrue(diff.Count() == 0);
If we have a count greater than zero, then our two lists do not contain the same elements. So if our resulting count is zero, our two enumerables are equal.
In order to do the same with datasets, dataviews and data tables we’ll first need to reference the DataTable Extensions methods library. This will open up extension methods to convert data tables to enumerables. Once we get our enumerable, we simply call intersect in the same manner as before.
var resultsDiff = DataSet.Tables[0].AsEnumerable().Intersect(DataSet.Tables[0].AsEnumerable());
Assert.IsTrue(resultsDiff.Count() == 0);
If you’re working with datasets or dataviews, you need to get to the underlying data table in order to use the extension method to convert it into an enumerable.

Categories
Tag Cloud
Blog RSS
Comments RSS
Last 50 Posts
Back
Void « Default
Life
Earth
Wind
Water
Fire
Light 