This is a simple and straightforward method I put in my base repositories to retrieve the row count of the results from an nhibernate criteria query.
protected int GetResultsCount(ICriteria criteria)
{
criteria.SetProjection(Projections.RowCount());
var eventsCount = criteria.UniqueResult<int>();
return eventsCount;
}
I wrote this RssReader to use in a dot net nuke site, but quickly found uses for it in a lot of other sites. This reader parses the rss stream to an xml document, then reads the nodes specified and returns a collection of rss items. This oen is easily customizable with whatever you want to bring back from the rss feed. Names definitely change per rss feed, so custimzation is likely, however the properties used here are extremely common so that much should be available.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Xml;
using System.Linq;
namespace RssTabDisplay
{
public static class RssReader
{
/// <summary>
/// Retrieves the remote RSS feed and parses it.
/// </summary>
public static IEnumerable<RssItem> GetFeed(string feedUrl)
{
//check to see if the FeedURL is empty
if (String.IsNullOrEmpty(feedUrl))
return new Collection<RssItem>();
// Add try catch block here in case the url
// goes down. Log and Handle the error in the method preferred.
// Return the exception, null or an empty collection
//start the parsing process
using (XmlReader reader = XmlReader.Create(feedUrl))
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
//parse the items of the feed
return ParseRssItems(xmlDoc);
}
}
/// <summary>
/// Retrieves the remote RSS feed and parses it.
/// </summary>
public static IEnumerable<RssItem> GetFeed(string feedUrl, int itemCount)
{
return GetFeed(feedUrl, 0, itemCount);
}
/// <summary>
/// Retrieves the remote RSS feed and parses it.
/// </summary>
public static IEnumerable<RssItem> GetFeed(string feedUrl, int startAt, int itemCount)
{
return GetFeed(feedUrl).Skip(startAt).Take(itemCount);
}
/// <summary>
/// Parses the xml document in order to retrieve the RSS items.
/// </summary>
private static IEnumerable<RssItem> ParseRssItems(XmlDocument xmlDoc)
{
Collection<RssItem> rssItems = new Collection<RssItem>();
XmlNodeList nodes = xmlDoc.SelectNodes("rss/channel/item");
var items = from XmlNode node in nodes
select new RssItem()
{
Title =node.SelectSingleNode("title") != null ? node.SelectSingleNode("title").InnerText : "(No title)",
Description = node.SelectSingleNode("description") != null ? node.SelectSingleNode("description").InnerText : "(none)",
Link =node.SelectSingleNode("link") != null ? node.SelectSingleNode("link").InnerText : "N/A",
Date = node.SelectSingleNode("pubDate") != null ? node.SelectSingleNode("pubDate").InnerText : "N/A",
Thumbnail = node.SelectSingleNode("thumb") != null ? node.SelectSingleNode("thumb").InnerText : "",
// To add more properties, another another node call here
};
return items;
}
/// <summary>
/// A structure to hold the RSS Feed items
/// </summary>
[Serializable]
public class RssItem
{
/// <summary>
/// The publishing date.
/// </summary>
public string Date { get; set; }
/// <summary>
/// The title of the feed
/// </summary>
public string Title { get; set; }
/// <summary>
/// A description of the content (or the feed itself)
/// </summary>
public string Description { get; set; }
/// <summary>
/// The link to the feed
/// </summary>
public string Link { get; set; }
public string Thumbnail { get; set; }
// Add more properties here if necessary
}
}
}
I left the try catch block off the when instantiating the xml document. It does have the ability to throw an exception if the url is invalid. You may want the exception, or you may want to simply return an empty collection. Depends on your implementation. Be careful, you don’t want a faulty rss feed to throw an exception and ruin other pages.
Here’s a collection of xml extensions I wrote to help make using and navigating xml documents a lot easier.
public static XmlNode FindNode(this XmlDocument doc, string nodeName)
{
if (doc == null)
return null;
XmlNode node = doc.DocumentElement;
return node.FindNode(nodeName);
}
public static XmlNode FindNode(this XmlNode parentNode, string name)
{
if (parentNode == null)
return null;
foreach (XmlNode node in parentNode.ChildNodes)
{
if (node.Name == name)
return node;
XmlNode foundNode = FindNode(node, name);
if (foundNode != null)
return foundNode;
}
return null;
}
FindNode is a method I use a lot when I’m working with 3rd party api’s. It’s a recursive method that traverses the xml document looking for the first node matching the name specified. This way I can ignore a lot of levels of the document to find the property I’m looking for. For example I’ll skip parent objects to get to the children, hold onto the first node and search for a property on it. If I don’t find what I’m looking for I try the next sibling.
/// Reads an xml file and serializes it to the object specified
public static T FromXmlFile<T>(this string path)
{
T result;
using (TextReader textReader = new StreamReader(path))
{
var xmlSerializer = new XmlSerializer(typeof(T));
result = (T)xmlSerializer.Deserialize(textReader);
textReader.Close();
}
return result;
}
//Serializes the class into an xml file that can be retrieved later.
public static void ToXmlFile<T>(this T obj, string path)
{
using (TextWriter textWriter = !File.Exists(path) ? File.CreateText(path) : new StreamWriter(path))
{
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(textWriter, obj);
textWriter.Close();
}
}
These two methods I will use to store and retrieve a class from an XML file. It’s good for quick and dirty storage.
Here is a quick extension method to sort a collection by a given property specified though generics. The extension method then uses a hashset to determine duplicates. This is excellent when paired with unique ids.
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
{
HashSet<TKey> knownKeys = new HashSet<TKey>();
foreach (T element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
Databinding is a huge part of any MVC or MVVM pattern. Usually this requires using a string representation of a property name in order to determine how a model is bound to its control. Using strings to control this databinding raises a couple key issues.
1.) Refactoring said property will not automatically update the control, nor will you be informed you’re ‘breaking’ the databind by renaming or removing a property.
2.) Finding usages of said property will also not inform you of the databinding. So if you’re wondering how/if a property is used, you might not find out about it until you break it.
These are headaches I prefer to avoid. It’s extra work to back out of changes, and it is also extra work to find and update these string references. I prefer to work less and accomplish more, which is why I looked into Linq for an answer to these issues.
Linq allows us to get the name of a property through an actual use of the property. So when I use resharper or visual studio to look up references, I can see the databinding.
/// <summary>
/// Determines the member name of a field or property in the form of a string, given a
/// strongly-typed expression.
/// </summary>
/// <typeparam name="T">The type of the class containing the field or property.</typeparam>
/// <param name="obj">The object containing the field or property.</param>
/// <param name="expression">The expression that identifies the field or property.</param>
/// <returns>The member name in the form of a string.</returns>
public static string MemberName<T>(this T obj, 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;
}
Usage:
<%= Html.TextBox(Model.MemberName(x => x.Name)%>
Here is a quick general purpose nhibernate criteria call to retrieve a list of results where the id is in a list. It is written as a generic method that I placed in my base repository and can use it for all of my domain objects. So T resolves to the type of domain object you are retrieving.
public IEnumerable<T> Get(IEnumerable<IdType> ids)
{
var criteria = Session.CreateCriteria<T>()
.Add(Restrictions.In("Id", ids.ToArray()));
return criteria.List<T>();
}
The sql this generates is essentially:
select * from DomainObjectTable
where id in('id1', 'id2', ...)
Here’s two quick methods to get the latitude and longitude of an address. Google takes any address in and tries to find the most appropriate location, regardless of typos. Google also gives you several locations to choose from, say a more northerly point vs a more westerly one.
public bool GetCoordinates(string address, out float latitude, out float longitude)
{
XmlDocument xml = new XmlDocument();
xml.Load(string.Format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=false", address));
XmlNode node = xml.DocumentElement;
if (node.Name != "location")
node = FindXmlNode(node, "location");
XmlNode latNode = FindXmlNode(node, "lat");
XmlNode lngNode = FindXmlNode(node, "lng");
if (latNode != null && lngNode != null)
{
bool success;
success = float.TryParse(latNode.InnerText, out latitude);
success = float.TryParse(lngNode.InnerText, out longitude);
return success;
}
else
{
latitude = longitude = 0;
return false;
}
}
public XmlNode FindXmlNode(XmlNode parentNode, string name)
{
foreach (XmlNode node in parentNode.ChildNodes)
{
if (node.Name == name)
return node;
XmlNode foundNode = FindXmlNode(node, name);
if (foundNode != null)
return foundNode;
}
return null;
}
I had a problem today where I needed to prevent mulitple mouse clicks from happen and making duplicate submit requests to the server. Since I don’t like reinventing the wheel, even though I usually do, I search online for examples of what other people were doing in my case. I knew I couldn’t be the only person to come across this issue. However, all solutions I found involved javascript. They offered solutions to disable submit buttons after being clicked and replacing the button with a waiting gif or other icon; or placing a splash page over the entire page to disable any further actions. While I could have accepted this solution and moved on, I wanted to ensure that my application was not processing two requests at the same time.
Thus I went about creating my own solution to lock down the thread per user. Which lead me to the actionfilterattribute class, and using the system.threading.monitor class to mange locks. I had to allow different users to continue processing, while stopping a duplicate form submission from a single user. In the end I did not have the time to figure out how to lock down multiple form submits from the generic principal.
There’s probably room for improvement in this class but I didn’t have to time to figure it out since it is working as is. When there is no user logged in we don’t have a shared object. Otherwise, if they are logged in, we have to find the instance of that user that we locked on, and wait for that lock to release.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Security.Principal;
namespace MyAttributes
{
/// <summary>
/// This class locks a method according to the logged in user.
/// If this is applied to a method with no logged in user, locking will not occur.
/// </summary>
public class LockAttribute : ActionFilterAttribute
{
private static readonly object _firstLock = new object();
private static List<IPrincipal> userLocks = new List<IPrincipal>();
private static Dictionary<IPrincipal, int> lockCounts = new Dictionary<IPrincipal, int>();
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// If the user is logged in, we have to track the locking objects.
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
int thisLock;
IPrincipal lockObj = filterContext.HttpContext.User;
// Lock down our list of locking objects so it's modified synchronously.
lock (_firstLock)
{
// If our lock does not contain our user, add it.
if (!userLocks.Contains(filterContext.HttpContext.User))
{
userLocks.Add(filterContext.HttpContext.User);
lockCounts.Add(filterContext.HttpContext.User, 0);
}
// Get the locking object.
thisLock = userLocks.IndexOf(filterContext.HttpContext.User);
lockObj = userLocks[thisLock];
// Increment the lock count.
lockCounts[lockObj]++;
}
System.Threading.Monitor.Enter(lockObj);
}
base.OnActionExecuting(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
int thisLock = -1;
IPrincipal lockObj = filterContext.HttpContext.User;
// Clean up our lock; but wait until another lock has finished.
lock (_firstLock)
{
if (userLocks.Contains(filterContext.HttpContext.User))
thisLock = userLocks.IndexOf(filterContext.HttpContext.User);
if(thisLock >= 0)
lockObj = userLocks[thisLock];
// Increment the lock count.
if(lockCounts.ContainsKey(lockObj))
lockCounts[lockObj]--;
if (lockCounts.ContainsKey(lockObj) && lockCounts[lockObj] <= 0)
{
lockCounts.Remove(lockObj);
if(userLocks.Contains(filterContext.HttpContext.User))
userLocks.Remove(filterContext.HttpContext.User);
}
}
System.Threading.Monitor.Exit(lockObj);
}
base.OnResultExecuted(filterContext);
}
}
}
This code is in it’s raw form to show you everything. In my project I created my own classes to handle the increment decrement of the lock counters.
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;

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