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;
}
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

Enable Logging to view the request.
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);
}
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});
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
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
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
04.11.09
Problem: You try to open a .mdf file in visual studio and you get one of the following errors.
Connections to SQL Server files (*.mdf) require SQL Server Express 2005 to function properly. Please verify the installation of the component or download from the URL: http://go.microsoft.com/fwlink/?LinkId=49251
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.
Solution: Open Server Explorer add Data Connection. Make sure the Data Source = Microsoft SQL Server Database File (SqlClient) and browse to the .mdf file located in your source directory(There maybe on located in the bin directory but this will get copied over by what is in src on a build). Click the Advance button. In order to work I needed to switch the Data Source to .\SQLEXPRESS2005 (This will be different for each computer).
Final connection string should look something like this:
Data Source=.\SQLEXPRESS2005;AttachDbFilename=|DataDirectory|\NerdDinner.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True


04.10.09
Problem: You want to be able use the Ninject frame work with the new and shiny ASP.Net MVC framework.
Solution: Assembly: Ninject.Framework.MVC Contains an Abstract Base class you can Inherit from to do most of your heavy lifting.
Some Code
Global.asax.cs
public class MvcApplication : NinjectHttpApplication
{
private static IKernel _kernal;
protected override void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected override IKernel CreateKernel()
{
if (_kernal == null)
{
var modules = new IModule[]
{
new AutoControllerModule(Assembly.GetExecutingAssembly()),
new DemoModual()
};
_kernal = new StandardKernel(modules);
}
return _kernal;
}
}
02.17.09
Problem: After deploying your silverlight application to your Web server you get the following error.
Error: Unhandled Error in Silverlight 2 Application Code: 2104 Category: InitializeErrorMessage: Could not download the Silverlight application. Check web server settings Source File: TestPage.htmlLine: 53 Solution: The MIME types on your webserver are not setup correctly to host your silver light application. The MIME types needed are:
.xaml application/xaml+xml
.xap application/x-silverlight-app
.xbap application/x-ms-xbap
Hack: If you are like me and have your silverlight hosted on a shared hosting environment like godaddy you cannot change your MIME types. Instead change the .xap to .zip you must also change the source parameter value inside your page to match.
<object data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%">
<param name="source" value="Microsoft.Windows.Controls.Samples.zip"/>
<param name="onerror" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="2.0.31005.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
</a>
</object>
02.04.09
Problem: You need a quick and easy way to manipulate elements contained in a list.
Solution: Lambda Expression, these expressions are used in the same fashion you would use anonymous methods but are less wordy.
Anonymous methods:
employees.FindAll(delegate(employee e1)
{
return e1.Name == "Dave";
})
Lambda Expression:
employees.FindAll(e1 => e1.Name == "Dave");
employees.Sort((e1,e2) => e1.LastName.CompareTo(e2.LastName));
For more complex expression use the syntax like (params) => {statment}.
employees.Sort((e1, e2) =>
{
if (e1.LastName.CompareTo(e2.LastName) == 0)
{
return e1.FirstName.CompareTo(e2.FirstName);
}
else
{
return e1.LastName.CompareTo(e2.LastName);
}
});
For more Info: MSDN