22 Apr 2011 @ 10:24 PM 

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;
        }
Posted By: Boyd
Last Edit: 14 Apr 2011 @ 10:27 PM

EmailPermalinkComments Off
Tags
Tags: , ,
Categories: .Net, Programming
 20 Apr 2011 @ 10:10 PM 

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.

Posted By: Boyd
Last Edit: 17 May 2011 @ 12:46 PM

EmailPermalinkComments Off
Tags
Tags: , , ,
Categories: .Net, Programming
 18 Apr 2011 @ 10:00 PM 

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.

Posted By: Boyd
Last Edit: 14 Apr 2011 @ 10:09 PM

EmailPermalinkComments Off
Tags
Tags: , , ,
Categories: .Net, Programming
 14 Apr 2011 @ 9:59 PM 

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;
                }
            }
        }
Posted By: Boyd
Last Edit: 14 Apr 2011 @ 10:31 PM

EmailPermalinkComments Off
Tags
Tags: , , ,
Categories: .Net, Programming
 06 Apr 2011 @ 10:30 PM 

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)%>
Posted By: boyd21
Last Edit: 14 Apr 2011 @ 10:28 PM

EmailPermalinkComments Off
Tags
Tags: , , , ,
Categories: .Net, Programming
 08 Dec 2010 @ 1:30 PM 

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. Which is used to cleanup up your type casting and rearranges the logic to make it easier to follow. The extension method is as follows:

        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;
Posted By: boyd21
Last Edit: 14 Apr 2011 @ 09:51 PM

EmailPermalinkComments Off
Tags
Tags: , ,
Categories: .Net, Programming
 09 Nov 2010 @ 6:21 PM 

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.

Posted By: boyd21
Last Edit: 14 Apr 2011 @ 10:33 PM

EmailPermalinkComments Off
Tags
Tags: , , ,
Categories: .Net, Programming
 21 Oct 2010 @ 10:15 AM 

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();
}
Posted By: boyd21
Last Edit: 14 Apr 2011 @ 09:54 PM

EmailPermalinkComments Off
Tags
Tags: , , ,
Categories: .Net, Programming

 Last 50 Posts
Change Theme...
  • Users » 3
  • Posts/Pages » 30
  • Comments » 0
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

GeekPub



    No Child Pages.