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
 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
 02 Mar 2009 @ 10:29 PM 

If I were to walk into the best buy in my home town, it would look just the same as it did 10 years ago. The format they use to sell their products, the format that made them the current top electronics retail chain, hasn’t changed in all this time. At least a third of their store is devoted to  aisles and aisles of CD’s, DVD’s and software. Does this seem right when apple has since taken over the music market with iTunes and movies and software are quickly becoming the realm of digital delivery as well. Perhaps they should begin phasing out these sections, reduce the size of the store and staff, and concentrate in other areas. That leaves retailers to focus on hardware.

However, with internet stores selling products at better prices (which allows them to shop at home, save gas, and avoid traffic), it makes customers less motivated to buy from a store. That doesn’t make for a good story trying to generate revenue as a retailer. Being able to demo a product before buying it, having a real person identify the solution that fits your specific needs, and getting the item instantly are the only reasons to walk into a store now. Of those three, only one requires you purchase the item at the store.  This is going to force retailers to now start charging for what was previously just a bonus and the right way to do business. Good customer service is going to come at a price.

Luckily, (because we know they didn’t plan this ahead) Best Buy has Geek Squad to capitalize on the other two, selling services. Best Buy currently sells Geek Squad services to install any product, or teach the customer how to work anything in the store. But these services are very expensive and basic, the same knowledge can be obtained through reading the manual. What you pay for is one on one time with someone answering your questions instead of a book. What Best Buy (or another retail chain looking to profit in this area) could do is sell time with specialists to talk to the customer about the products they are interested in. Now I know, they do this for free, but customers would pay knowing they have the employee’s undivided attention. Now since the store is selling this service, they don’t have to force the sale on the customer, they already got the sale.

Ok, we know they’ll still press the sale; its what they do. But, some customers will still walk out and buy the product online with their new knowledge, but at least the store would be able to capitalize a little bit on the sale.

Posted By: Boyd
Last Edit: 10 Mar 2009 @ 11:05 PM

EmailPermalinkComments Off
Tags
Categories: Business Logic
 27 Feb 2009 @ 9:51 PM 

Now Google is leading the coup d’état against Microsoft.

P.S. Next time I might talk about how Microsoft has a two mobile OS’s. One of them is good but not successful, and the other is successful but not good.

Posted By: Boyd
Last Edit: 28 Feb 2009 @ 09:29 PM

EmailPermalinkComments Off
Tags
Categories: Business Logic

 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.