Posts Tagged ‘linkedin’

(using MVC4 beta)

In some cases it is not easy to alter the header values to negotiate the content type returned from WEBAPI.

There is a QueryStringMapper object you can add to the Media Type Formatter objects that allow you to use a query string to negotiate the content format.

In the example below,  I am adding a query string parameter ‘format’ to the mapping. When ‘format’ == ‘xml’, the content type is ‘text/xml’ and the XmlMediaTypeFormatter is used.

I run this in the ‘Application_Start’ method of the Global.asax 

            foreach (var item in GlobalConfiguration.Configuration.Formatters)
            {
                if (typeof(XmlMediaTypeFormatter) == item.GetType())
                {
                    item.AddQueryStringMapping("format", "xml", "text/xml");
                }
            }

Example api call – http://localhost/api/foo?format=xml

Here is an example of aggregation using LINQ to a collection –

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GroupByExampleLinq
{
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string AccountNumber { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Example();
            Console.ReadKey();
        }

        static void Example()
        {
            // Creating new List of Person
            List personCollection = new List()
            {
                //Adding a new Person
                new Person(){
                    AccountNumber = "123123 634566",
                    Email = "qwerty@qwerty.com",
                    FirstName = "John",
                    LastName = "Doe"
                },
                //Adding a new Person
                new Person(){
                    AccountNumber = "123123 678879",
                    Email = "qwerty@qwerty.com",
                    FirstName = "John",
                    LastName = "Doe"
                },
                //Adding a new Person
                new Person(){
                    AccountNumber = "123123 122134",
                    Email = "qwerty@qwerty.com",
                    FirstName = "John",
                    LastName = "Doe"
                },
                //Adding a new Person
                new Person(){
                    AccountNumber = "123123 890980",
                    Email = "asdf@asdf.com",
                    FirstName = "Jane",
                    LastName = "Doe"
                }
            };

            // Using LINQ to query the collection and group them by the email address
            var personQuery = from p in personCollection
                              group p by p.Email into g
                              select new { Email = g.Key, Accounts = g };

            // Output the email address and the count of records for each group
            foreach (var item in personQuery)
            {
                Console.WriteLine("{0} has {1} accounts.", item.Email, item.Accounts.Count());
            }
        }
    }
}

I use this function to send debugging information to the console in Firefox and IEDeveloper.

Using a query string parameter [debug=1] to enable logging, to save some cycles when its not needed.

I am sure there are better ways to write this…


// Logging Function
function log(msg){
if(!getParameterByName("debug") == 1) { return; }
if (window.console && console.log) {
console.log(msg); // Valid in Firebug and IEDeveloper
}
}

To get the query string parameter, I am using a snippet found on the net a while back. I would give credit, but I have no idea where the original source was.


function getParameterByName( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}

I have recently seen an issue that popped up in a couple different projects I have worked on.

When using a wizard inside Visual Studio, the available datasets list has been empty. I was able to solve this once after exhausting other build/rebuild techniques by creating a new project, then copying all the source files from the orginal project.

I’m really not sure where the orginal error was in the project, but the same thing happened today in a different project. Rather than creating a new project, I read in this post you could create an ‘index.aspx’ and recompile – it worked!

I’m not sure if this is a bug, but if you get the scenario where your business objects are not available as options in a VS wizard, try adding an index.aspx and let me know if it works…

I’m using the first Umbraco 5 (Jupiter) RTM on a new project.

One of the requirements of this project is to aggregate RSS feeds, so I built a simple plugin leveraging the System.Xml.Linq objects.

To make the plugin, I created a new MVC 3 project in visual studio to build and test the functionality.
I would have added the Umbraco test site to my solution and setup post build commands to copy the files from my project to Umbraco folders, but for some reason I was not able to run the Umbraco site from Visual Studio. I think its a system problem though.

I’ve also used the HTML Agility pack to parse the feed descriptions and remove bad markup.

Here is the  code to grab the RSS Feed and parse it with the HTMLAgilityPack –


    public static class Reader
    {
         public static IEnumerable GetRssFeed(string feedUrl, bool trimDescription = true)
         {
             XDocument feedXml = XDocument.Load(feedUrl);
             XNamespace dc = "http://purl.org/dc/elements/1.1/";
             string exp = @"^.{1,500}";
             if (trimDescription == false)
                 exp = ".*";
             var feeds = from feed in feedXml.Descendants("item")
                         select new Rss
                         {
                             Title = feed.Element("title").Value,
                             Link = feed.Element("link").Value,
                             Description = Regex.Match(ParsedDoc(feed.Element("description").Value).DocumentNode.InnerText, exp).Value,
                             PubDate = feed.Element("pubDate").Value,
                             Creator = feed.Element(dc + "creator").Value
                         };
             return feeds;
         }

         public static HtmlAgilityPack.HtmlDocument ParsedDoc(string source)
         {
             HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
             doc.OptionWriteEmptyNodes = true;
             doc.OptionFixNestedTags = true;
             doc.LoadHtml(source);
             return doc;
         }


    }

 

And the RSS class…

 


    public class Rss : IComparable
    {
        public string Link { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public DateTime PubDateDate { get; set; }
        public string Creator { get; set; }


        public string PubDate 
        {
            get
            {
                return _pubDate;
            }
            set
            {
                _pubDate = value;
                DateTime pubDateDate = DateTime.MinValue;
                DateTime.TryParse(value, out pubDateDate);
                PubDateDate = pubDateDate;
            }
        }
        private string _pubDate;

        // Implement the default CompareTo method with the PubDate
        // as the parameter. 
        //
        public int CompareTo(Rss other)
        {
            // If other is not a valid object reference, this instance is greater.
            if (other == null) return 1;
            return PubDateDate.CompareTo(other.PubDateDate);
        }


    }

In Umbraco, I created a folder in the plugins directory following the Dev Dataset examples.
I placed the HTMLAgilityPack DLL and XML, and my DLL in this folder to allow the CSHTML to call the classes.

I created 2 new document types in Umbraco for an ‘RSS List’ and ‘RSS Feed Item’. On the RSS List template, I grab all the children of that node (which are of type ‘RSS Feed Item’) and grab the properties from them using the DynamicModel.

In the Umbraco RSS List template…


@inherits Umbraco.Cms.Web.RenderViewPage

@functions {
    //Add public properties here to create Macro Parameters

    protected List<Zeroth.Umbraco.RSSReader.Rss> aggregatedFeed = new List<Zeroth.Umbraco.RSSReader.Rss>();
}

@{
    foreach (var child in DynamicModel.Children)
    {
        aggregatedFeed.AddRange(Zeroth.Umbraco.RSSReader.Reader.GetRssFeed(child.url, true));
    }
    aggregatedFeed.Sort();
    aggregatedFeed.Reverse();
}

<h2>@DynamicModel.CurrentPage.Name</h2>

<div class="rssList">
@foreach (var child in aggregatedFeed)
{
    <div class="rssItem">
        <div class="rssLink">
            <a href="@child.Link" target="_blank">@Html.Encode(child.Title)</a>
        </div>
        <div class="rssByLine">
            <span class="rssPubDate">@child.PubDate.Replace("+0000", "")</span><span> | </span><span class="rssCreator">@child.Creator</span>
        </div>
        <div class="rssDescription">
            @( new HtmlString(child.Description) )
        </div>
    </div>
}
</div>

I just picked up a GHI Panda II for some development with the .NET Micro Framework. Very excited about tinkering in the embedded world.

Today I was challenged with creating an authenticated, cross-domain, WCF service that returns JSONP.

 Using the ‘out of the box’ WCF configurations this is not possible.  If you attempt to use authentication with an endpoint that allows cross-site scripting, you will recieve an error message like this –

Cross domain javascript callback is not supported in authenticated services

To get around this restriction (It’s not a bug) we can use a custom encoder factory/binding/etc…

In my application, I am using the sample JSONP library that was provided by Miscrosoft.
http://msdn.microsoft.com/en-us/library/cc716898(v=VS.90).aspx

Then added the appropriate authentication requirement in the web config.

<customBinding>
<binding name=”jsonpBinding”>
<jsonpMessageEncoding/>
<httpTransport manualAddressing=”true” authenticationScheme=”Negotiate” />
</binding>
</customBinding>

 

If anyone needs help with this, First try to implement the JSONP library from Microsoft and let me know if you get stuck. I’ll try to help you configure your app.

http://msdn.microsoft.com/en-us/library/cc716898(v=VS.90).aspx

In this example I am using –

  • SharePoint MOSS 2007
  • JQuery 1.5.2 min

 A colleague asked me for a way to spruce up his SharePoint survey page with images, so I put together the following script. It is generic and re-usable so you might even wrap it into a js file to share between sites.

Check out the CSS tutorials here  and the selector tutorial on the JQuery site  to learn more how the selectors work.

Examples –
$(‘body) selects the body element
$(‘.ms-formbodysurvey span.ms-RadioText’) selects all span elements with the class ‘ms-RadioText’ that are a descendent of an element with the class ‘ms-formbodysurvey’.

I’ve added the comments inside the code to explain what is happening. You’ll need to update the paths to your JQuery library, option text, and image paths. You can use the ‘ToolPaneView=2’ hack to put your NewForm.aspx page into edit mode. Then add a ‘Content Editor’ webpart to place the following code in.

Also, you might want to add a bit of CSS to style the position, margin, or padding of the images.

<!-- Including the JQuery library in the page.      This provides the element selector function $() --> 
<script type="text/javascript" src="/sites/scripts/jquery-1.5.2.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
  // Handler for .ready() called when the document is loaded.
  // We call the following function to iterate through each option
  IterateThroughOptions();
});

function IterateThroughOptions(){
  // This selects all elements that match the expression 
  // '.each' performs the defined function on each of the matched elements 
  $('.ms-formbodysurvey span.ms-RadioText').each(function(){
      // The span element contains an attribute called Title that we store in a variable called optionText 
      // This is the text that is displayed next to the radio button 
      var optionText = $(this).attr('Title');
      // Pass the optionText value to our function 'GetImgUrl'
      var imgUrl = GetImgUrl(optionText);
      // Append a new element (img) to our span element 
      $(this).append('<img src="' + imgUrl + '" />');
    });
}
function GetImgUrl(optionText){
  // Check the option text and return the correct URL 
  if(optionText === "Chargers")
    { return "/sites/NFL_Images/Chargers.jpg"; }
  if(optionText === "Cowboys")
    { return "/sites/NFL_Images/Cowboys.jpg"; }
  if(optionText === "Dolphins")
    { return "/sites/NFL_Images/Dolphins.jpg"; }
// Add more 'IF' statements to match the rest of the option text 
// If there are no matches, use this default image path  
return "/sites/NFL_Images/helmet50.gif";
}
</script>
An Americans For Fair Taxation slogan

Image via Wikipedia

            It is important to implement a fair taxation system that promotes economic growth without creating disincentives for saving, investing, working, or spending. Our current system of taxing income, capital gains, gifts, payroll, exports and many other sources of money create disincentives for individuals and organizations to grow and expand. A ‘fair’ system would evenly distribute taxation but not be regressive. In this sense of the word, ‘regressive’ means to put a larger tax burden on the low income, poor, or impoverished households. A fair consumption tax system appropriately called The Fair Tax is a form of a national retail sales tax that delivers a revenue neutral implementation without creating the disincentives of an income tax while creating more incentive to save and invest money in the United States of America.

            It is known that if you remove incentives/rewards for negative behavior, you will typically experience a decrease in the occurrence of that behavior. While reinforcing desired behaviors with rewards will generally produce more of the behavior. By removing rewards for negative behavior such as tax evasion through legal or illegal loopholes, you will likely see less of the behavior. With our current income taxation, a hardworking honest taxpayer is ‘rewarded’ by being required to pay more taxes. What kind of motivation does this give people to work hard and pay taxes? The current income tax works against economic growth by penalizing desired behavior, tempting the ‘would be’ honest hardworking citizens into tax evasion and removing the motivation to work harder.  It is also common that people would like to ‘do the right thing’, but the sheer complexity of the current tax code prohibits some from doing their taxes correctly. In this case we can simplify the tax code to remove the impediment for the desired behavior. Buccholtz has a similar thought that consumption (sales) taxes grow the economy, and when you penalize productive behavior (taxing income), you get less of it (Buccholtz 2008). By removing the punishments for working hard, removing the rewards for cheating the system, and make it more simple to do the right thing, we can create the motivation necessary to promote economic growth.

            The Fair Tax (Americans for fair taxation 2009) is a nonpartisan form of a national retail sales tax that promotes economic growth by removing the disincentives to invest, save, and work harder while evenly distributing the tax burden and relieving the low income, poor, and impoverished citizens of taxation. The Fair Tax moves from taxing income to a system of taxing consumption. It is generally agreed that an ‘income tax’ taxes what an individual contributes to the economy where a ‘consumption tax’ taxes what an individual takes from the economy. This form of consumption tax would completely replace all forms of the income tax including payroll tax, Medicare tax, Social Security tax, and capital gains tax (Fair Tax Official You Tube Channel 2010). Since this plan is ‘revenue neutral’, meaning it will still collect the same amount of taxes, Medicare, Social Security, and the other federal social programs will still be funded. Since the taxes would be collected at the register there would be an initial tax of 23% to maintain revenue neutrality. With a tax increase on products, lower income families would normally be burdened more with this system, but the Fair Tax has some progressive measures that relieve the tax burden from these households. The Fair Tax is able to relieve the tax burden on the poor, while broadening the tax base and creating incentives to invest, save, and work harder, resulting in economic growth.

 With a consumption tax, the tax base (the number of people paying taxes) is broadened substantially. Particularly with the Fair Tax the base is broadened, the low income families are relieved of taxes, and the amount of tax is based on the amount of money being spent on non-necessity items making this a progressive tax system. Since taxes are collected at the register, this means people who normally would evade income taxation such as drug dealers, illegal aliens, workers being paid ‘under the table’, and even tourists would be forced to pay taxes. This would be difficult for low income families that may be paying $0 taxes in the current system but a progressive measure is in place to remove this burden. Low income families spend a larger percentage of their income on necessities and may have little left for consumption of ‘extras’ like new electronics or other items that aren’t necessary. The wealthy spend far more on frivolous expenditures such as vacationing, consumer electronics, and other non-essentials. Shifting more of the tax burden on these low income or impoverished families would be regressive without a measure to counter it. This regressive taxation is alleviated by the Fair Tax prebate. The prebate is a monthly check from the government that pays your tax on necessities. For households that purchase nothing more than necessities, they would pay no taxes. The more you spend on ‘extras’, the more taxes you pay. Thus the wealthy would pay more in taxes because they consume more of society’s production. By broadening the tax base, offering the prebate, and basing taxes on consumption, the Fair Tax is the most progressive of any tax system suggested (progressive meaning ‘allowing progress’; not the socialist form of the word meaning ‘wealth redistribution’).

            Consumption taxation would boost the economy, promote saving and investing over spending that would benefit savers and investors. According to Ehrbar:

A tax is neutral (or “efficient”) if it does not alter spending habits or behavior patterns from what they would be in a tax-free world, and thus does not distort the allocation of resources. No tax is completely neutral, because taxing any activity will cause people to do less of it and more of other things. For instance, the income tax creates a “tax wedge” between the value of a person’s labor (the pretax wages employers are willing to pay) and what the person receives (after-tax income). As a consequence, people work less—and choose more leisure—than they would in a world with no taxes (Ehrbar 2008, EconLib.org).

Ehrbar continues to explain the tax wedge created by taxing capital income does enormous long term damage to the economy by taxing interest, dividends, and capital gains; penalizing thrift by taxing away part of the return to savings. This would result in less saving and investing than society would choose in a world with no taxes.

As described in chapter 10 of United States tax reform in the 21st century (Zodrow. 2002), many countries in the world have adopted a form of consumption tax. The chapter gives some insight to a historical view of modern consumption based taxation by starting with philosopher David Hume’s 1779 publication of Essays and Treatises on Several Subjects. Hume is known for his early support for a consumption based tax system. A national retail sales tax (NRST), the flat tax, the Unlimited Allowance and Savings tax (USA tax), and the Value Added Tax (VAT) are four other consumption tax alternatives similar to the Fair Tax that can be further studied in United States tax reform in the 21st century.

There are a few arguments that have emerged since the suggestion that we should replace the income tax with a consumption tax, but these arguments are easily countered. In an interview with William Gale and Len Burman (Gale 2005), Ray Suarez asks them to describe what consumption tax is and to explain the pros and cons. Despite Burman and Gale’s pessimism that a consumption based tax system would be successful, Burman raises a good question about older people’s spending and how an increase in consumption tax would be a game changer for someone making decisions by different rules for many years prior. For these older savers, playing by different rules would probably be chosen over continued taxation of their savings. Some opponents of a simple consumption tax such as the Fair Tax are resistant to any change because they are currently abusing the system or using loop holes to legally evade taxes. By moving to a more transparent system it would be more difficult for people to abuse the system. Another objection from some economists noted by Ehrber (2008) is that the greatest monetary benefits of a consumption tax would go to high-income individuals. Since the wealthy are in higher tax brackets, these high-income households would get a greater dollar benefit from deducting savings (traditional IRA) or having after-tax contributions accumulate tax-free income (Roth IRA). Additionally, high-income households have a greater opportunity to save, and thus are more likely to take advantage of tax-free capital income. Ehrber (2008) simply explains there are two counterpoints to that argument. “First, those who pay the most in taxes inevitably will get the greatest dollar benefit from tax reductions. Second, the economic benefits from greater saving—more innovation and greater GDP growth—would be distributed to everyone in the form of a faster increase in real incomes, including wages.” Although there are some arguments against a consumption tax, there are even stronger counter arguments for it.

To promote economic growth without creating disincentives for saving, investing, working, or spending, it is important to implement a fair taxation system. We need to remove our current system of creating disincentives that is, taxing income, capital gains, gifts, payroll, exports and many other sources of money. A fair and progressive (The Fair Tax) , form of a national retail sales tax that delivers a revenue neutral implementation without creating the disincentives of an income tax while creating more incentive to save and invest money, would evenly distribute taxation while reducing or removing the tax burden from the low income, poor, and impoverished households.

References

Americans for Fair Taxation (2009). About the fairtax. Retrieved from http://www.fairtax.org/site/PageServer?pagename=about_main on June 15, 2011

Buchholtz, R. (2008, February 7). Let’s talk Fair Tax talk [Letter to the editor]. The Washington Times, p. A20.

Ehrbar, Al (2008). Consumption tax, The concise encyclopedia of economics. Retrieved from http://www.econlib.org/library/Enc/ConsumptionTax.html on June 15, 2011

Fair Tax Official You Tube Channel. (2010). What is the fair tax legislation? Retrieved from http://www.youtube.com/user/FairTaxOfficial?blend=8&ob=5 on June 15, 2011

Gale, William G. & Burman, Len  (March 03, 2005). The NewsHour with Jim Lehrer,  The Pros and Cons of a Consumption Tax http://www.brookings.edu/interviews/2005/ 0303taxes_gale.aspx on June 15, 2011

Zodrow, George R. & (eds), Peter Mieszkowski. (2002). United states tax reform in the 21st century. [Books24x7 version] Retrieved from http://common.books24x7.com. proxy.devry.edu/toc.aspx?bookid=9009. on June 15, 2011


.Net Framework Logo

Image via Wikipedia

.NET extension methods are very useful. Here is one that I am using frequently in a current project –

I want to trim a string of extra spaces at the ends, then check to see if it is empty. If it is empty I want to assign a default value.

With .NET extension methods, it makes it easy to create a peice of reusable code that can be called like any method.

    public static class StringExtensions
    {
        /// <summary>
        /// If the current string (trimmed) is empty then return the default string
        /// </summary>
        /// <param name=”currentString”>The current string value</param>
        /// <param name=”defaultString”>The string to return if the current string is empty</param>
        /// <returns></returns>
        public static string DefaultIfEmpty(this string currentString, string defaultString)
        {
            if (currentString.Trim() == string.Empty)
            {
                return defaultString;
            }
            else
            {
                return currentString.Trim();
            }
        }
    }

The preceding word ‘this’ in the parameter declaration means that you can call this method on any string.

Example using the new extension –

string myString = ” “;

myString.DefaultIfEmpty(“I was empty”);