1/29/11

JavaScript Dates

Dates contain the number of milliseconds since 1-1-1970 00:00:00 UTC.

Date Constructor
new Date()  //returns current datetime
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond])  //optional time-params default to 0

Params: milliseconds ms since 1-1-1970 00:00:00 UTC
        dateString   string format
        year         4 digit year
        month        0-11
        day          1-31  day of the month
        hour         0-23  hour of the day
        minute       0-59  minute segment of a time reading
        second       0-59  second segment of a time reading
        millisecond  0-999 ms segment of a time reading

Static Methods
These methods return the milliseconds since 1-1-1970
Date.now()  //use for timestamps & unique IDs, todo: minimum 15 millisecond resolution on windows?
Date.parse(datestring)
Date.UTC(year, month [, date, hrs, min, sec, ms])  //universal time

d = new Date("Jan 7, 2011")               //Fri Jan 07 2011 00:00:00 GMT-0700 (Mountain Standard Time)
d.getMonth()                              //0 (0-11)
d.getDay()                                //5 (0-6) friday
d.getDate()                               //7 (1-31)
d.getFullYear()                           //2011
d.getHours()                              //0

d = new Date("Jan 07 2011 01:02:03")      //Fri Jan 07 2011 01:02:03 GMT-0700 (Mountain Standard Time)
d.getHours()                              //1
d.getMinutes()                            //2
d.getSeconds()                            //3

d = new Date("Jan 07 2011 01:02:03:456")  //Fri Jan 07 2011 01:02:03 GMT-0700 (Mountain Standard Time)
d = new Date(2011, 0, 7, 1, 2, 3, 456)
d.getMilliseconds()                       //456
d.getTime()                               //1294387323456 milliseconds since 1-1-1970
Date.parse("01-07-2011 01:02:03:456")     //1294387323456 milliseconds since 1-1-1970
Date.UTC(2011, 0, 7, 1, 2, 3, 456)        //1294362123456

formatDate(d)                             //"1-7-2011"
formatDatePad(d)                          //"01-07-2011"
formatDateTime(d)                         //"1-7-2011 1:2:3:456"
formatDateTime(addMinutes(d, 60))         //"1-7-2011 2:2:3:456"
formatDateTime(addMinutes(d, 10))         //"1-7-2011 1:12:3:456"
formatDateTime(addMinutes(d, 1440))       //"1-8-2011 1:2:3:456"

//debug
console.log(d.getMonth());console.log(d.getDate());console.log(d.getFullYear());console.log(d.getHours());console.log(d.getMinutes());console.log(d.getSeconds());console.log(d.getMilliseconds())

//equivalent date constructors, exclude times for date only, string formats can be used with Date.parse()
new Date("01-07-2011 01:02:03")
new Date(2011, 0, 7, 1, 2, 3)
new Date("Jan 07 2011 01:02:03")
new Date("Fri Jan 7 2011 1:2:3")
new Date("Fri Jan 07 2011 01:02:03 GMT-0700")

//-------------
function addMinutes(date, minutes){  //returns date
  var result = new Date(date.getTime());
  result.setMinutes(result.getMinutes() + parseInt(minutes));
  return result;
}

function formatDate(date){  //returns string
  return (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getFullYear();
}

function formatDatePad(date){  //returns string
  return (pad2(date.getMonth() + 1)) + "-" + pad2(date.getDate()) + "-" + pad2(date.getFullYear());
}

function formatDateTime(date){  //returns string
  return (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + ":" + date.getMilliseconds();
}

//http://www.electrictoolbox.com/pad-number-two-digits-javascript/
function pad2(number){  //returns string
  return (number < 10 ? "0" : "") + number;
}

Conversions
INTERVAL       MS   SECS  MINS   HOURS
1 sec        1000      1  1/60  1/3600
1 min       60000     60     1    1/60
10 min     600000    600    10   10/60
1 hour    3600000   3600    60       1
1 day    86400000  86400  1440      24  ms=24*60*60*1000

1/17/11

Powershell Appcmd IIS 7 Command Line Tool

Appcmd Objects
APPapplications
APPPOOLapplication pools
BACKUPserver configuration backups
CONFIGgeneral configuration sections
MODULEserver modules
REQUESTHTTP requests
SITEvirtual sites
TRACEworking with failed request trace logs
VDIRvirtual directories
WPworker processes

$appcmd = "c:\windows\system32\inetsrv\appcmd.exe"
&$appcmd /?  #help

#list all sites
&$appcmd list site
&$appcmd list site /xml        #use xml to get attribute names
&$appcmd list site /text:name  #use text to get attribute values

&$appcmd list site /text:name | sort  #ps sort

#list all app pools
&$appcmd list apppool

#list app pool names
&$appcmd list apppool /text:name

#list app pool .net framework version
&$appcmd list apppool /text:managedRuntimeVersion

#list all w3wp.exe worker processes, use to debug match process id to iis website
&$appcmd list wp

#list started sites, running
&$appcmd list site /state:started

#list stopped app pools
&$appcmd list apppool /state:stopped

#list all virtual directory/physical paths
&$appcmd list vdir

#list site bindings ipaddress
(&$appcmd list site prod /text:bindings).split(",")

#list response headers
&$appcmd list config prod /section:httpProtocol

#add response headers
&$appcmd set config prod /section:httpProtocol /+"customHeaders.[name='foo', value='bar']"

#delete response headers
&$appcmd set config prod /section:httpProtocol /-"customHeaders.[name='foo']"
&$appcmd set config prod /section:httpProtocol /-"customHeaders.[name='x-powered-by']"

#output site configuration text
&$appcmd list site prod /text:*

#list website virtual directory/physical path
&$appcmd list vdir prod/

#stop website
&$appcmd stop apppool prod; &$appcmd stop site prod

#start website
&$appcmd start apppool prod; &$appcmd start site prod

#stop all running sites
&$appcmd list site /state:started /xml | &$appcmd stop site /in  

#stop all running app pools
&$appcmd list apppool /state:started /xml | &$appcmd stop apppool /in

#list mime types
&$appcmd list config prod /section:system.webServer/staticContent

v11.09

1/15/11

ASP.NET MVC 3 - Project Template for Visual Studio 2010

References
Microsoft.CSharp
System
System.Core
System.Web
System.Web.Helpers
System.Web.Mvc
System.Web.Routing
System.Web.Services
System.Web.WebPages

Folders
controllers
js
models
properties
ux
views
views\home
views\shared

Files
controllers\homeController.cs
demo.csproj
demo.csproj.user
global.asax
global.asax.cs
js\alert.js
properties\assemblyInfo.cs
ux\style.css
views\_viewStart.cshtml
views\home\default.cshtml
views\shared\error.cshtml
views\shared\_layout.cshtml
views\web.config
web.config
web.debug.config
web.release.config

controllers\homeController.cs
using System.Web.Mvc;

namespace Demo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Default()
        {
            ViewBag.Message = "ViewBag.Message, set in HomeController";

            return View();
        }
    }
}

demo.csproj
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion></ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{A8C1B3E9-6897-4456-A450-2662343B9E6F}</ProjectGuid>
    <ProjectTypeGuids>{E53F8FEA-EAE0-44A6-8774-FFD645390401};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>properties</AppDesignerFolder>
    <RootNamespace>Demo</RootNamespace>
    <AssemblyName>demo</AssemblyName>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
    <MvcBuildViews>false</MvcBuildViews>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <PublishDatabases>false</PublishDatabases>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Web" />
    <Reference Include="System.Web.Helpers" />
    <Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
    <Reference Include="System.Web.Routing" />
    <Reference Include="System.Web.Services" />
    <Reference Include="System.Web.WebPages" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="global.asax.cs">
      <DependentUpon>global.asax</DependentUpon>
    </Compile>
    <Compile Include="properties\assemblyInfo.cs" />
    <Compile Include="controllers\homeController.cs" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="global.asax" />
    <Content Include="js\alert.js" />
    <Content Include="ux\style.css" />
    <Content Include="views\_viewStart.cshtml" />
    <Content Include="views\home\default.cshtml" />
    <Content Include="views\shared\_layout.cshtml" />
    <Content Include="views\shared\error.cshtml" />
    <Content Include="views\web.config" />
    <Content Include="web.config" />
    <Content Include="web.Debug.config">
      <DependentUpon>web.config</DependentUpon>
    </Content>
    <Content Include="web.Release.config">
      <DependentUpon>web.config</DependentUpon>
    </Content>
  </ItemGroup>
  <ItemGroup>
    <Folder Include="models\" />
  </ItemGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target> -->
  <Target Name="MvcBuildViews" AfterTargets="AfterBuild" Condition="'$(MvcBuildViews)'=='true'">
    <AspNetCompiler VirtualPath="temp" PhysicalPath="$(WebProjectOutputDir)" />
  </Target>
  <ProjectExtensions>
    <VisualStudio>
      <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
        <WebProjectProperties>
          <UseIIS>False</UseIIS>
          <AutoAssignPort>True</AutoAssignPort>
          <DevelopmentServerPort>1234</DevelopmentServerPort>
          <DevelopmentServerVPath>/</DevelopmentServerVPath>
          <IISUrl></IISUrl>
          <NTLMAuthentication>False</NTLMAuthentication>
          <UseCustomServer>True</UseCustomServer>
          <CustomServerUrl>http://dev.mvcdemo.com/</CustomServerUrl>
          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
        </WebProjectProperties>
      </FlavorProperties>
    </VisualStudio>
  </ProjectExtensions>
</Project>

demo.csproj.user
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <ProjectView>ShowAllFiles</ProjectView>
  </PropertyGroup>
  <ProjectExtensions>
    <VisualStudio>
      <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
        <WebProjectProperties>
          <StartPageUrl></StartPageUrl>
          <StartAction>NoStartPage</StartAction>
          <AspNetDebugging>True</AspNetDebugging>
          <SilverlightDebugging>False</SilverlightDebugging>
          <NativeDebugging>False</NativeDebugging>
          <SQLDebugging>False</SQLDebugging>
          <ExternalProgram></ExternalProgram>
          <StartExternalURL></StartExternalURL>
          <StartCmdLineArguments></StartCmdLineArguments>
          <StartWorkingDirectory></StartWorkingDirectory>
          <EnableENC>False</EnableENC>
          <AlwaysStartWebServerOnDebug>True</AlwaysStartWebServerOnDebug>
        </WebProjectProperties>
      </FlavorProperties>
    </VisualStudio>
  </ProjectExtensions>
</Project>

global.asax
<%@ Application Codebehind="global.asax.cs" Inherits="Demo.MvcApplication" Language="C#" %>

global.asax.cs
using System.Web.Mvc;
using System.Web.Routing;

namespace Demo
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "default",                     // Route name
                "{controller}/{action}/{id}",  // URL with parameters
                new { controller = "Home",     // Parameter defaults
                      action     = "Default", 
                      id         = UrlParameter.Optional }
            );
        }

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
}

js\alert.js
//<script src="/js/alert.js" type="text/javascript"></script>
alert("/js/alert.js");

properties\assemblyInfo.cs
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("MVC Demo")]
[assembly: AssemblyCompany("Expression Software")]
[assembly: ComVisible(false)]
[assembly: Guid("28bf9b70-c4f2-4007-986f-5598dd52dfa8")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

ux\style.css
body{
background:#000;
color:#fff;
font-family:Verdana, Arial, Helvetica, Sans-Serif;
}

views\_viewStart.cshtml
@*file: \views\_viewStart.cshtml
  desc: common view code, executed at the start of View render
*@

@{
    //set default layout
    Layout = "~/views/shared/_layout.cshtml";
}

views\home\default.cshtml
@{
    ViewBag.PageTitle = null;  //breakpoint
    ViewBag.PageTitle += "MVC Demo";
}

@*html body - view source for line breaks & whitespace*@
<h1>@ViewBag.PageTitle</h1>
ViewBag.PageTitle: @ViewBag.PageTitle<br />
ViewBag.Message: @ViewBag.Message

views\shared\error.cshtml
@{
    Layout = null;
}
<!doctype html>
<html>
<head>
  <title>Error</title>
  <meta charset=utf-8>
</head>
<body>
  error...
</body>
</html>

views\shared\_layout.cshtml
<!doctype html>
<html>
<head>
  <title>@ViewBag.PageTitle - Expression Software</title>
  <meta charset=utf-8>
  <link href="/ux/style.css" rel="stylesheet" type="text/css" />
  <!--<script src="/js/alert.js" type="text/javascript"></script>-->
</head>
<body>
  @RenderBody()

  <br />------------------------<br />
  @DateTime.Now.ToString("MM-dd-yy HH:mm:ss:fff")

  <br />------------------------
  @foreach(var x in new [] {0,1,2})
  {
      ;<br />@x;  //use leading semicolon to prevent generating extra, collapsed, whitespace
  }
</body>
</html>

views\web.config
<?xml version="1.0"?>
<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler" />
    </httpHandlers>

    <!-- Enabling request validation in view pages would cause validation to occur after the input has already been processed by the controller.
         By default MVC performs request validation before a controller processes the input. 
         To change this behavior apply the ValidateInputAttribute to a controller or action. -->
    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <controls>
        <add tagPrefix="mvc" namespace="System.Web.Mvc" assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="BlockViewHandler" />
      <add name="BlockViewHandler" 
           path="*" verb="*"
           preCondition="integratedMode" 
           type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
</configuration>

web.config
<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="ClientValidationEnabled" value="true"/> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>

    <authentication mode="None" />

    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages"/>
      </namespaces>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

web.debug.config
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
</configuration>

web.release.config
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.web>
    <compilation xdt:Transform="RemoveAttributes(debug)" />
  </system.web>
</configuration>



1/12/11

Using External JavaScript Files with Google Analytics

For basic page tracking, put the code in an external file.

Then you can use this
<script src="/js/googleAnalytics.js" type="text/javascript"></script>

instead of
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _gaq.push(['_trackPageview']);
  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>

Add to files, right before the closing head tag.


googleAnalytics.js
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();