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

 07 Apr 2011 @ 12:25 PM 

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!

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

EmailPermalinkComments Off
Tags

 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

 22 Mar 2011 @ 11:38 AM 

The requirement for me was to create an overlay that dimmed out all the content around a video. While there are plenty implementations of this I did not find any tutorials or solutions posted, which is kind of boggling to me. So I tried to follow a few similar examples and tried to modify them to meet my needs. After several hours of frustration I fell back on one of my main principles, start over and do it myself.

If you saw the rest of my blog you would know I’m a c# developer first, and do javascript/html/css when those developers are busy. So I’m not that great with jQuery/css but I can get by. I must be improving because I found the solution to be quite easier than I expected.

Here’s how I decided to do it. Make divs surround the area in question. Top, left, right and bottom. Then I need to set the sizes and placements accordingly and finally fade in the regions.

We’ll start with the html code. There’s no magic here, it’s plain and simple.

<div class='overlayWrapper'>
    <div id="overlay-top" class="overlay"></div>
    <div id="overlay-left" class="overlay"></div>
    <div id="overlay-right" class="overlay"></div>
    <div id="overlay-bottom" class="overlay"></div>
</div>

Now we’ll check out the css. Again pretty straightforward, but I’ll explain more.

.overlay
{
    background-color: #000000;
    display: none;
    margin: 0;
    opacity: 0.8;
    padding: 0;
    z-index: 150;
    position: absolute;
}
#overlay-top
{
    min-width: 920px;
    position: absolute;
    width: 100%;
    top: 0;
    left: 0;
}
#overlay-left
{
    position: absolute;
    left: 0;
}
#overlay-right
{
    float: right;
    position: absolute;
    width: 100%;
}
#overlay-bottom
{
    min-width: 920px;
    width: 100%;
    z-index: 150;
    left: 0;
    height: 100%;

First I set my class to contain the color and other shared css attributes. The rest contain certain properties relevant to their location. Top has it’s top set to 0, right is floated right, left is the only div without width set to 100%, and bottom has both width and height to 100% to cover everything.

Now let’s explore the jquery used to accomplish the spotlight effect. The idea here is to position the divs around a specified area.

function SpotlightDiv(spotlightDiv) {
    var position = $(spotlightDiv).position();
    var width = $(spotlightDiv).width();
    var height = $(spotlightDiv).height();
    ResizeOverlayWindow(position.left, position.top, width, height);
    DimOverlay();
}
function ResizeOverlayWindow(left, top, width, height) {
    $('#overlay-top').height(top);
    $('#overlay-bottom').css({ top: top + height });

    $('#overlay-left').height(height);
    $('#overlay-left').css({ width: left });

    $('#overlay-left').css({ top: top });
    $('#overlay-right').css({ top: top });

    $('#overlay-right').height(height);
    $('#overlay-right').css({ left: left + width });
}
function DimOverlay() {
    $('.overlay').each(function() {
        $(this).fadeIn(200);
    });
}
function RaiseOverlay() {
    $('.overlay').each(function() {
        $(this).fadeOut(200);
    });
}

Pretty simple, huh? Again it should be straightforward and self explanatory, but I will go into more regardless.

overlay-top
The idea here is to set the height of the top div based on the location of the item we’re spotlighting. This way it stretches from the top of the page down to the top of the div.

overlay-bottom
We set the top of the bottom overlay to be at the bottom of the spotlighted div. It then covers the rest to the bottom.

overlay-left/right
We set the top and height to align with the spotlighted div’s top/height. This aligns them horizontally across the page.

overlay-left
We set the left div’s width to align with the left edge of the spotlighted div.

overlay-right
We set the right div’s left edge to align at the right edge of the spotlighted div.

That’s it. Pretty simple. Take it and do with it what you will, there’s a lot more that can be done. You can have it follow the mouse, you can use it to show users a specific section on your site to help them find something.

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

EmailPermalinkComments Off
Tags
Tags: , ,
Categories: Html/Css, Programming

 20 Jan 2011 @ 11:07 AM 

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', ...)
Posted By: Boyd
Last Edit: 14 Apr 2011 @ 09:46 PM

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

 13 Jan 2011 @ 4:44 PM 

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

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

 13 Jan 2011 @ 3:06 PM 

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.

Posted By: boyd21
Last Edit: 14 Apr 2011 @ 09:50 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.