Friday, February 19, 2010

MVC AJAX Helper

I needed to pass in some arguments to the Create function for the other AJAX extensions and came up with this override.

Thanks to Stephen for the initial help with this article.
http://stephenwalther.com/blog/archive/2008/08/23/asp-net-mvc-tip-36-create-a-popup-calendar-helper.aspx
public static string Create(this AjaxHelper helper, string clientType, string elementId, Dictionary args)
        {
            StringBuilder argSb = new StringBuilder();
            if (args != null && args.Count > 0)
            {
                argSb.Append("{");
                foreach (string key in args.Keys)
                {
                    if (argSb.Length > 1)
                        argSb.Append(",");

                    argSb.Append("'")
                         .Append(key);
                    if (args[key].Contains("$"))
                    {
                        argSb.Append("':")
                             .Append(args[key]);
                    }
                    else
                    {
                        argSb.Append("':'")
                             .Append(args[key])
                             .Append("'");
                    }
                }
                argSb.Append("}");
            }
            //{'class':'element_wrapper'}
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("");
            return sb.ToString();
        }

            //{'class':'element_wrapper'}
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("");
            return sb.ToString();
        }

Tuesday, August 4, 2009

Probing PrivatePath

I recently dented my forehead and keyboard trying to figure out why my probing privatePath was not working. Here is my correctly configured config section.


<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="bin\subBin"/>
</assemblyBinding>
</runtime>


I was getting this error.
[InvalidOperationException: The type 'MyService.Blah', provided as the Service attribute value in the ServiceHost directive could not be found.]

I could move the culprit DLL up to my bin directory and everything would work but that isn't the way the system is designed.

Turns out what is needed is this little tidbit.

<assemblies>
<add assembly="MyService.Blah"/>
</assemblies>


Once I told .Net what to look for in the bin\subBin directory, life continued on for me and the healing process began, and a new keyboard is now on order. If there are typos, blame it on my now malfunctioning keyboard.

Sunday, February 8, 2009

LINQ - Detaching DataContext

I took the code from here by and modified it so I could just use an extension class instead of having to change the model. Besides, it is more fun to use the new features of .NET 3.5 :)

using System.Data.Linq;
using System.Data.Linq.Mapping;

public static class ExtendedDataContext
{
public static T Detach(this DataContext dc, T entity) where T : class, new()
{
if (entity == null)
return null;

//create a copy of the entity
object entityCopy = new T();

//enumerate the data member mappings for the entity type
foreach (MetaDataMember member in dc.Mapping.GetMetaType(typeof(T)).DataMembers)
{
//skip associations and deferred members
if (member.IsAssociation || member.IsDeferred)
continue;

//copy the member value
member.StorageAccessor.SetBoxedValue(ref entityCopy, member.StorageAccessor.GetBoxedValue(entity));
}

return (T)entityCopy;
}
}



Code in use
User detachedUser = ((DataContext)db).Detach(user);
db.Users.Attach(detachedUser, true);
db.SubmitChanges();

Monday, December 8, 2008

Session Facade

I have noticed some blogs about Session Facade but all have one thing missing. CleanUp()! This can be useful when you use point in time session variables and have a strict policy to clean these items up.


internal class DocSharingSessionFacade
{
private static DocSharingSessionFacade sessionFacade = null;
private static readonly string _pointInTimeUploadFileKey = "DocSharingUploadFile";

private DocSharingSessionFacade()
{
}

public static DocSharingSessionFacade Instance()
{
if (sessionFacade == null)
{
sessionFacade = new DocSharingSessionFacade();
}

return sessionFacade;
}

#region UploadFile Methods

public string UploadFile
{
get { return HttpContext.Current.Session[_pointInTimeUploadFileKey] as string; }
set {HttpContext.Current.Session[_pointInTimeUploadFileKey] = value; }
}

public void ClearUploadFile()
{
HttpContext.Current.Session.Remove(_pointInTimeUploadFileKey);
}

#endregion
}


BTW - the reason I am using Session instead of ViewState for this type of variable is that we are using MonoRail and NVelocity so do not actually have a ViewState object.

Thursday, November 20, 2008

CC.Net, MSBuild, TypeMock, NUnit and NCover Integration

Integration is painless
Through early morning fog I see
visions of the things to be
the pains that are withheld for me
I realize and I can see...

Thanks to everyone who contributed to these links.
FxCop and when to fail the build
MSBuild Tasks Docuemtation
NCover and CC.Net can be friends
CC.Net running a MSBuild Project
TypeMock, NUnit and NCover Together in MSBuild
TypeMock and MSBuild

Here is my final working copy.
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Coverage;CoverageReports;FxCop" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- Import the MSBuild Tasks -->
<Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" />
<Import Project ="C:\Program Files\Typemock\Isolator\5.1\TypeMock.MSBuild.Tasks"/>
<UsingTask TaskName="NCover" AssemblyFile="c:\NCover\Tasks\NCoverExplorer.MSBuildTasks.dll" />
<UsingTask TaskName="NCoverExplorer" AssemblyFile="c:\NCover\Tasks\NCoverExplorer.MSBuildTasks.dll" />

<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<ClassLibraryOutputDirectory>bin\$(Configuration)</ClassLibraryOutputDirectory>
<TestOutputDirectory>\localbin\Course.Web.Ui.TakeExam.Test_Library</TestOutputDirectory>
<ProjectDir>C:\Projects\Web\UI</ProjectDir >
<TestProjectDir>C:\Projects\Test</TestProjectDir >
<ProjectFile>$(ProjectDir)\Course.Web.UI.TakeExam_Site.csproj</ProjectFile >
<TestProjectFile>$(TestProjectDir)\Src\Course.Web.Ui.TakeExam.Test_Library.csproj</TestProjectFile >
<CoverageResults>C:\Program Files\CruiseControl.NET\webdashboard\results</CoverageResults>
<CoverageReports>C:\Program Files\CruiseControl.NET\webdashboard\reports</CoverageReports>
<NCoverPath>C:\Program Files\NCover</NCoverPath>
<NCoverExe>$(NCoverPath)\ncover.console.exe</NCoverExe>
<NUnitPath>C:\Program Files\NUnit 2.4.7\bin</NUnitPath>
<NUnitExe>$(NUnitPath)\nunit-console.exe</NUnitExe>
<FxCopPath>C:\Program Files\Microsoft FxCop 1.35</FxCopPath>
<FxCopRulePath>C:\Program Files\FxCop\CodingStandards\bin\Debug</FxCopRulePath>
</PropertyGroup>

<!-- Build projects by calling the Project files generated by VS -->
<Target Name="Build">
<!--<MSBuild Projects="$(ProjectFile)" />-->
<MSBuild Projects="$(TestProjectFile)" />
</Target>

<!--run FxCop-->
<ItemGroup>
<FxCopRuleAssemblies Include="$(FxCopRulePath)\CodingStandards.dll" />
</ItemGroup>
<ItemGroup>
<FxcopTargets Include="$(TestProjectDir)$(TestOutputDirectory)\Course.Web.Ui.TakeExam.dll" />
</ItemGroup>
<ItemGroup>
<FxCopDependencies Include="C:\3rdparty"/>
<FxCopDependencies Include="$(MSBuildCommunityTasksPath"/>
<FxCopDependencies Include="C:\assemblies"/>
</ItemGroup>
<PropertyGroup>
<FxCopCriticalErrors>0</FxCopCriticalErrors>
<FxCopErrors>0</FxCopErrors>
<FxCopCriticalWarnings>0</FxCopCriticalWarnings>
</PropertyGroup>

<Target Name="FxCop" DependsOnTargets="Build">
<!--<XmlRead ContinueOnError="True"
XmlFileName="$(CoverageResults)\fxcop.xml"
XPath="string(count(//Issue[@Level='CriticalError']))">
<Output TaskParameter="Value" PropertyName="FxCopCriticalErrors" />
</XmlRead>
<XmlRead ContinueOnError="True"
XmlFileName="$(CoverageResults)\fxcop.xml"
XPath="string(count(//Issue[@Level='Error']))">
<Output TaskParameter="Value" PropertyName="FxCopErrors" />
</XmlRead>
<XmlRead ContinueOnError="True"
XmlFileName="$(CoverageResults)\fxcop.xml"
XPath="string(count(//Issue[@Level='CriticalWarning']))">
<Output TaskParameter="Value" PropertyName="FxCopCriticalWarnings" />
</XmlRead>
<Error Text="FxCop encountered rule violations."
Condition="$(FxCopCriticalErrors) > 0 or $(FxCopErrors) > 0 or $(FxCopCriticalWarnings) > 0" />-->
<FxCop
TargetAssemblies="@(FxcopTargets)"
RuleLibraries="@(FxCopRuleAssemblies)"
AnalysisReportFileName="$(CoverageResults)\fxcop.xml"
DependencyDirectories="@(FxCopDependencies)"
FailOnError="False"
Verbose="True"
IncludeSummaryReport="True"
/>
</Target>

<ItemGroup>
<TestAssembly Include="$(TestProjectDir)$(TestOutputDirectory)\Course.Web.Ui.TakeExam.Test_Library.dll" />
</ItemGroup>

<!-- Run Unit tests -->
<!--The Coverage task will also run the unit tests - use this one if you only need to run the unit tests-->
<Target Name="UnitTests" DependsOnTargets="Build">
<CallTarget Targets="StartTypeMock"/>

<Exec ContinueOnError="false" Command='"$(NUnitExe)" @(TestAssembly) /include=UnitTest /out="$(CoverageResults)\TestResult.xml"'/>

<CallTarget Targets="StopTypeMock"/>
<OnError ExecuteTargets="StopTypeMock"/>
</Target>

<ItemGroup>
<CoverageAssemblies Include="$(TestProjectDir)$(TestOutputDirectory)\Course.Web.Ui.TakeExam.dll" />
</ItemGroup>

<Target Name="Coverage" DependsOnTargets="Build">
<CallTarget Targets="StartTypeMock"/>

<NCover
ToolPath="$(NCoverPath)"
CommandLineExe="$(NUnitExe)"
CommandLineArgs="@(TestAssembly) /noshadow /include=UnitTest"
WorkingDirectory="$(CoverageResults)"
CoverageFile="$(CoverageResults)\Coverage.xml"
LogFile="$(CoverageResults)\Coverage.log"
Assemblies="@(CoverageAssemblies)"
ProfileIIS="false"/>
<CallTarget Targets="StopTypeMock"/>
<OnError ExecuteTargets="StopTypeMock"/>
</Target>

<!--This will create the reports-->
<ItemGroup>
<CoverageFile Include="$(CoverageResults)\Coverage.xml" />
</ItemGroup>

<Target Name="CoverageReports" DependsOnTargets="Coverage">
<!--ToolPath property is NOT in the online documents - only in the examples-->
<NCoverExplorer
ToolPath="$(NCoverPath)"
ProjectName="Take Exam Refactor"
CoverageFiles="@(CoverageFile)"
OutputDir="$(CoverageReports)"
ReportType="ModuleClassFunctionSummary"
SatisfactoryCoverage="80"
FailMinimum="False"
XmlReportName="CoverageSummary.xml"
HtmlReportName="CoverageSummary.html" />
</Target>

<Target Name="StartTypeMock">
<TypeMockStart Link="NCover2.0" LogPath="$(CoverageResults)"/>
</Target>

<Target Name="StopTypeMock">
<TypeMockStop />
</Target>
</Project>