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

One of the great MVC3 benefits is how easy it is to create helpers to inject HTML into your views.

After reading this post, I decided I would use Bart Czernicki’s example to create an MVC3 helper ‘cshtml razor engine style’.

You can place the following code in your App_Code folder (in a cshtml file).
I use a file called ‘Helpers’ and place multiple helpers in the same file. You could also create multiple files there to namespace your helpers if you have a bunch.

 @helper SilverLightHostControl(
            string silverlightXapFileLocation, // URI Location of the Silverlight XAP file
            string minimumRuntimeVersion = "4.0.50826.0",
            string objectContainerWidth = "100%",
            string objectContainerHeight = "100%",
            string onErrorJavaScriptFunctionName = "onSilverlightError",
            string divObjectTagId = "silverlightControlHost",
            string iFrameStyle = "visibility:hidden;height:0px;width:0px;border:0px"
            ){
    <div id="@divObjectTagId">
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="@objectContainerWidth" height="@objectContainerHeight">
            <param name="source" value="@silverlightXapFileLocation"/>
            <param name="minRuntimeVersion" value="@minimumRuntimeVersion" />
            <param name="onError" value="@onErrorJavaScriptFunctionName" />
            <param name="background" value="white" />
            <param name="autoUpgrade" value="true" />
            <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
            <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
            </a>
        </object>
     </div>
} 

To use the helper in your view, call it like this -
@Helpers.SilverLightHostControl(“/ClientBin/SilverlightSurface.xap”)

For help integrating a Silverlight project in MVC, check this post out -
http://www.iwantmymvc.com/using-silverlight-with-mvc-and-json

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 Stated 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”);

While following the scrolling tutorial for the XNA Platformer Starter Kit (3.1), I ran into an issue with the Level.Draw() method. This problem only occurs if you are using XNA 4.0 or higher with the tutorial.

In the tutorial (http://msdn.microsoft.com/en-us/library/dd254919(v=xnagamestudio.31).aspx) it has the line -

spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None, cameraTransform);

But this fails, as the SpriteBatch.Begin() signature and SpriteBlendMode Enum has changed in XNA 4.0.

Instead, use the following line (or pass in NULL(s) for default parameter options.

spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullCounterClockwise, null, cameraTransform);

Example Passing in NULLs -

spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null, cameraTransform);
 

Hopefully this will save someone a a few minutes! =^]

I was getting this error today when trying to use the designer view of a Windows Form with the visio active x control. I would imagine this same error could occur for any COM call.

Warning 45 Unspecified error (Exception from HRESULT: 0×80004005 (E_FAIL))

Or you may see an error like -

Error HRESULT E_FAIL has been returned from a call to a COM component

This could be a DLL error in some cases, but in this case, it was a conflict with an extension or extension framework for Visual Studio. After disabling the ‘Productivity Power Tools’ extension and restarting VS, the problem disappeared.

It’s confusing because there was no problem in the last several weeks I have been working with this. I had already tried cleaning the solution and restarting the computer but it had no effect. After it started working again, I re-enabled the ‘Productivity Power Tools’ extension to try and recreate the issue, but was unsuccessful.

At this point I cannot say exactly what caused it, but disabling extensions is a good starting point to troubleshooting VS issues.

Connecting to an Oracle database without installing an Oracle client software package on the server/client deployment environment:

Some application deployments to clients or servers require database connections to Oracle instances. What happens when the deployment environment doesn’t have the Oracle client software loaded? What if the server configurations are not accessible, or it takes an act of congress to install anything to the environment?

In this example I am adding  ‘instant client’ support to a .net application using the ODP.NET driver but other drivers can leverage the instant client. Also, I am using the latest ODP.NET driver for the .NET 4 framework, as it supports the Entity framework =)

Required software -

  • Oracle Instant Client
  • Oracle ODP.NET (or your preferred Oracles driver that is supported by Instant Client)

http://www.oracle.com/technetwork/indexes/downloads/index.html

In your .net application, add the following 5 DLLs (from the Oracle download) to the root directory of your project and configure the properties of each to ‘Copy if newer’.

  • ODP.NET Drivers
    • OraOps11w.dll
    • Oracle.DataAccess.dll (if this is in your ref folder, set the property to ‘Copy Locally’
  • Instant Client Files (Depending on the version you downloaded, you only need one set)
    • Basic
      • oci.dll
      • orannzsbb11.dll
      • oraociei11.dll (111M)
    • Light
      • oci.dll
      • orannzsbb11.dll
      • oraociicus11.dll (~31M)

 If you are using Entities or need access to the factory in ODP.NET, you’ll need to register the provider in the web.config (*check the version of your driver to be sure it matches) -

<system.data>
<DbProviderFactories>
<add name="Oracle Data Provider for .NET"  
invariant="Oracle.DataAccess.Client" 
description="Oracle Data Provider for .NET" 
type="Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess, Version=4.112.2.30, PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>
</system.data>

 When you build/deploy your application, the 5 DLLs should be in the web app bin folder, or if you are building a client app – they should be in the same folder as the exe.

References -
Good tutorial with screen shots (http://alderprogs.blogspot.com/2009/04/deploying-odpnet-with-oracle-instant.html)
Oracle’s Developer Guide (http://download.oracle.com/docs/html/E10927_01/InstallODP.htm)

Sometimes when you are developing/debugging an application you may want a different behavior than the release/retail build. The conditional attribute in .NET let’s you do this.

Let us suppose that we have a method that loads data into an object from a remote source like a database. While debugging, you may need to restart the application many times to test different methods or changes. If it takes more than a couple of seconds to load your data, you may want to temporarily cache this data. Since your application needs real-time data in the production environment, the conditional attribute is an easy way to tell the compiler to only call our cache loader while in the DEBUG configuration.

This article is not about how to cache data, but rather how to define a method that is only called when using the debug configuration. In my experience, cached data represents a good opportunity to use the conditional attribute. There are many other situations where this would be helpful.

In this example method, I have applied the the conditional attribute, [Conditional("DEBUG")], so that the data is only cached when ‘DEBUG’ is defined. When running the app in Visual Studio, ‘Debug’ can be selected in the active configuration list. This will define debug during compilation for you.

///
/// This method is only called when DEBUG is defined
///
[Conditional("DEBUG")]
private void CacheIfDebug()
{
if (File.Exists(@"C:\cachedPSDFileData.xml"))
{
entireFileTree = XElement.Load(@"C:\cachedPSDFileData.xml");
}
else
{
setEntireFileTree();
entireFileTree.Save(@"C:\cachedPSDFileData.xml");
}
}

In the example below, when using the ‘Debug’ configuration, both methods will execute. When using ‘Release’ configuration, only the second method will be called. Since the ‘CacheIfDebug’ method has been decorated with the conditional attribute, the compiler removes references to it. For this reason, methods decorated with the conditional attribute must be ‘void’ return type.

private void DoSomething()
{
CacheIfDebug();
DoSomethingElse();
}

Using the conditional attribute makes it easy to debug and deploy without changing your code for each environment.
For more information about the conditional attribute check out these links.

http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx

http://community.bartdesmet.net/blogs/bart/archive/2006/08/30/4368.aspx