Reading a String from a Stream

07.02.10

Problem: You need to read some text from a stream of some sort.

Solution: Use StreamReader class , set the postion to 0 and call ReadToEnd().

Code!

 

static string GetStringFromStream(Stream inputStream)
{
var pos = inputStream.Position;
var reader = new StreamReader(inputStream);
inputStream.Position = 0;
var text = reader.ReadToEnd();
inputStream.Position = pos;
return text;
}

My Azure Resources List

07.01.10

Just throwing out some resources I like to reference for windows azure.

Tools

Blob Storage Explorer – CloudXplorer

Web based Table Storage Explorer

Windows Azure Service Management CmdLets

Cloud Storage Studio

HedgehogDev Azure Cloud Application Monitor

Azure Tool kit for Facebook

Lokad Cloud – Cloud Platform Abstractions cool stuff like Auto Scaling.

Install Azure

Web Platform Installer

Educational

Steve Marx – Microsoft Azure Dude

Cloud Cover – Channel 9 Videos on Cloud Platform

Azure Training Kit

Azure Deployment for your Build Server

Returning Json in ASP.Net MVC

06.22.10

Problem: You want to return a Json object to your page using ASP.Net MVC.

Solution: Use JQuery.getJSON and JsonActionResult.

CODE:

View HTML

<ul id="jsonRequestFun">
</ul>
<a href="#" id="requestFun">Json is fun</a>

View Javascript

<script type="text/javascript">
$(function () {
$("#requestFun").click(function () {
$.getJSON("/home/jsonfun", null, function (data) {
$("<li>" + data.Message + "</li>").appendTo("#jsonRequestFun");
$("<li>" + data.Time + "</li>").appendTo("#jsonRequestFun");
});
});
});
</script>

Handy tool to view the request in IE is nikhilk.net Web development Helper

Once installed the tool is a bit hidden you can find it at Tools>Explorer Bars>Web Developer Helper

openDevHelper

Enable Logging to view the request.

webdevhelper

Model:

public class JsonData
{
public string Message { get; set; }

public string Time { get; set; }
}

 

Controller Action:

Beware of this little gotcha if you do not pass the AllowGet your requests will be ignored.

public ActionResult JsonFun()
{
var data = new JsonData
{
Message = "Hello World",
Time = DateTime.Now.ToShortTimeString()
};
return Json(data, JsonRequestBehavior.AllowGet);
}

MSpec + Resharper

06.08.10

1. Download MSpec

2. Download Resharper Template

3. Setup Reshaper style to work with MSpec.

resharperMspecSettings1

resharperMspecSettings2

Salesforce Destination

05.26.10

Problem: You need to submit salesforce sObjects including custom fields to many different organization’s salseforce instances.

Solution: Use the Partner WSDL, it's loosely typed and can be used with all organizations and  whatever customizations they have.

 

Code:

//Base class 
public class SalesforceBase
{
private readonly List<SalesforceCustomField> _customFields = new List<SalesforceCustomField>();
private readonly XmlDocument _document = new XmlDocument();
private readonly List<XmlElement> _elements = new List<XmlElement>();
private readonly string _type;

protected SalesforceBase(string type)
{
_type = type;
}

public string Type
{
get
{
return _type;
}
}

public IEnumerable<SalesforceCustomField> CustomFields
{
get
{
return _customFields;
}
}

public XmlElement[] Any
{
get
{
return _elements.ToArray();
}
}

public void AddCustomField(SalesforceCustomField customField)
{
UpdateElements(customField.FieldName, customField.Value);
_customFields.Add(customField);
}

protected void UpdateElements(string name, string value)
{
var element = _elements.Find(ele => ele.Name == name);
if (element != null)
{
element.InnerText = value;
}
else
{
element = _document.CreateElement(name);
element.InnerText = value;
_elements.Add(element);
}
}
}
//Implement Base
public class SalesforceContact : SalesforceBase
{
public SalesforceContact() : base("Contact") { }

private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
if (value != null)
{
UpdateElements("FirstName", value);
_firstName = value;
}
}
}
}
//Send It
SForceService.create( new sObject(){Any = contact.Any, type = contact.Type});

SVN Merge Headaches

03.05.10

Problem: You work on a team using svn source repository and you are plagued with merge conflicts.

Solution: Simply put use ignore. All team members need to have the ignore list setup so that only developer generated content is being submitted. User files and compiled project files should be omitted.

In my development environment I use Visual Studio 2008(C# mostly) and Resharper. My automated builds compile to a folder called “build.”

My ignore list:

.DS_Store _ReSharper.* Thumbs.db obj bin *.suo build *.user buildout.txt

PBA.com Rewrite From ASP Classic to ASP.Net MVC

03.03.10

PBA.com had become a maintenance issue with majority of the code base written under ASP classic by programmers who no longer worked in the organization.

Requirements:

  • Use a current language/framework that promotes best practices such as unit testing, separation of concerns, and  DRY code.
  • Framework needed to provide complete control over HTML giving Web designers easier means to create clean CSS/HTML design templates.
  • Search engine optimization friendly.
  • Business logic must be decoupled from the database.
  • Old URLs must give a 301 status code and be correctly routed to the new standard.

Technology Overview:

PBA.com was rewritten from ASP Classic to ASP.Net MVC. The MVC framework provided us with good base for the best practice we needed, improving the maintainability of the site. The MVC routing engine enabled us with a means to route old URLs to their new MVC counter part properly. For the Model in MVC we choose Nhibernate. Nhibernate proved to be both performant and flexible, giving PBA not just PBA.com  a reusable stable business logic layer.

Before:

After:

WPF – Tournament Presenter

02.22.10

Tournament Presenter is a customized score board display written for the PBA to allow onsite fans to quickly gauge the state of a bowling tournament.

Requirements:

  • The display needed to be Extendable. PBA host many different styles of tournaments, Tournament Presenter needed an easy method of adding functionality for the new tournament formats.
  • Screen Resolution independents. None of the target display  hardware  was guaranteed to  use the same resolution. Displays needed to look the same on all sizes.
  • Displays needed to look sharp be capable of animation, graphics and color.
  • Data source for displays needed to be small and work disconnected.

Technology Overview:

The displays where written in C# on .Net 3.5 platform. WPF was leverage  for rendering GUI, XML for the data source, Clickonce for publishing, NUnit for testing and MEF for Extendibility.

Tournament Presenter On ESPN

Look to the seek times at 00:22, 1:08, 3:40, 4:20, 5:40, 6:50, and 7:19 these will give a good idea of how they are used in production.
ESPN Video

User Generated Html Content

10.22.09

Problem: You need to handle user generated html content from an unknown source for display in your webapp.

Solution: Well this is alwasy a moving target due to cross site scripting, but my approach is the following.

1. I use MarkItUp to allow users an easy way to format their html.

2. After users has submitted his changes I run it through an HTML Sanitizer (Scroll to the bottom) that users a white list approach. For asp.net mvc you will need to mark your controller as [ValidateInput(false)]

2. If the Sanitization process has removed any user created content I do not save the content.  I then Return there modified content with a warning message, "Some illegal content tags where detected and removed double check your work and try again."  

3. If the content passes through the sanitization process cleanly, I save the raw html content to the database.

4. When rendering to the client I just pass the raw html out of the db to the page.

More Info:

StackOverflow.com

Safer Deletes and Updates on Live DataBase

05.21.09

Problem: You need to change production data from a database.

Solution: Use Transations.

Its always scary working with live data I found that I feel more confident when I take the following measures.

Do a Select first to check the where clause:

SELECT * FROM Foo WHERE FooID = 1000

Wrap your changes in a Transaction and roll it back if you did not get the expected result.

Begin Transaction
  DELETE FROM Foo WHERE FooID = 1000
IF @@RowCount <> 1 BEGIN
  Rollback Transaction
END
ELSE
  Commit Transaction