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;
}
}
}
I needed to refresh a particular message every so often but I didn’t want to overload the server with requests, so I looked up clever ways of starting and stopping my ajax calls. I recall facebook only updates when you perform some action on the page. I thought an implementation similar to this would be the way to go. I probably ended up doing it the same way, but I don’t know how they accomplished their solution.
I’ll start by crediting the articles I found online that helped me achieve my solution. The first resource I found was an answer on Stack Overflow: by T.J. Crowder. I took a lot from his post, but I re worked it to an implementation I was more comfortable with, and had a better understanding of. I wanted to fire off custom events. More specifically when the user was no longer active, and becomes active; when the user becomes inactive, and any time there is activity. Although I suspect I would use the last one the least.
In order to hook up custom events and found several custom event classes created in javascript, which I would have had to use if I wasn’t going to be using jQuery. Since I am using jQuery I found an article by Jamie Thompson about jQuery’s publising/subscribing to be the answer I was looking for.
Finally the solution:
var activityHandler = (function() {
var timeout;
var active = false;
flagActivity();
function isActive() {
if (new Date() < timeout)
return true;
else
return false;
}
function start() {
stop();
flagActivity();
}
// Sets the date in the past and deactivates
function stop() {
timeout = new Date();
timeout.setSeconds(-1);
$(document).trigger('inactive', [true]);
active = false;
}
function flagActivity() {
// if previously inactive, then we have new activity
if (!active)
$(document).trigger('newactivity', [true]);
active = true;
timeout = new Date();
var seconds = timeout.getSeconds();
timeout.setSeconds(seconds + 5);
$(document).trigger('activity', [true]);
monitor();
}
// monitors the timeout while it is in progress
// The first occurence where timeout expires
// inactive is triggered and monitor stops.
function monitor() {
if (active && !isActive()) {
stop();
}
else if (active) {
var diff = timeout - new Date();
setTimeout(monitor, diff);
}
}
return {
start: start,
stop: stop,
flagActivity: flagActivity,
isActive: isActive
};
})();
Pretty straightforward object here, it sets a time a few seconds into the future to determine inactivity. It’s fairly quick, at 5 seconds; set this to whatever is desirable. There is a simple monitoring function that determines the difference between now and the next time the timer is set to expire. When the monitor notices it is active and needs to deactivate it calls stop, which triggers the inactive event. That’s all well and good, but how do we start it, and how do we flag activity from the user? For that we bind those to the mousemove or onmousemove event.
if (document.addEventListener) {
document.addEventListener('mousemove', activityHandler.flagActivity, false);
}
else if (document.attachEvent) {
document.attachEvent('onmousemove', activityHandler.flagActivity);
}
else {
document.onmousemove = activityHandler.flagActivity;
}
Which can be placed in either a document ready, or some other function you call on initialization. So anytime the user’s mouse is in the window, it will flag the activity and set the timer. Which the monitor will then watch until it needs to deactivate. Finally, here is an example of how I am using it with an ajax call.
First off I bind it to the newactivity event.
$(document).bind('newactivity', refreshStatus);
Any time there is new activity the status refreshes. remember, this only fires if the user has been away long enough to be inactive. Essentially this method is set up liek the monitor method in that it will set itself on a timer if it needs to.
function refreshStatus() {
$.get('/url/', { arg: argValue }, function(response) {
// do something with your response
$.each(response.items, function(index, value) {
$('.status' + value.itemId).html(value.status);
});
if (activityHandler.isActive())
setTimeout(refreshStatus, 5000);
});
}
Here I make an ajax call and update an element on the page, then if the activity hasn’t timed out, we requeue the method to let it refresh itself. All this was implemented to throttle the ajax calls to the server.
There’s plenty of improvements that can be made to this. The activity monitor could trigger a start event, the event for activity can probably be removed, I can’t foresee it being used as it would happen so frequently, then again, the reason we could in things like this is we can’t foresee how they’ll be used until we have a use case.
Take it, run with it, destroy it, do whatever you like with it. Hope it helps!
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)%>

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