Joseph Michael Pesch
VP Programming

Using HTTPRuntime.Cache in Non-Web Application

by 31. August 2010 23:32

Sample Code:

using System;

using System.Web;

using System.Web.Caching;

using System.Threading;

 

namespace HTTPCacheSample

{

  classProgram

  {

 

    #region HTTP Runtime Cache

 

    privatestaticHttpRuntime httpRuntime;

    privatestaticvoid EnsureHttpRuntime()

    {

      System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString()

        + ": EnsureRuntime...");

      if (null == httpRuntime)

      {

        // Create an Http Content to give us access to the cache.

        httpRuntime = newHttpRuntime();

        System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString()

          + ": null httpRuntime... creating new instance");

      }

    }

    publicstaticCache Cache

    {

      get

      {

        EnsureHttpRuntime();

        System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString()

          + ": return HttpRuntime.Cache...");

        returnHttpRuntime.Cache;

      }

    }

 

    #endregion

 

    staticvoid Main(string[] args)

    {

      Cache.Add("TestCache", "This is a test @" + DateTime.Now.ToString()

        , null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration

        , CacheItemPriority.High, null);

      for (int i = 0; i <= 10; i++)

      {

        ThreadStart threadDelegate = newThreadStart(TestIt);

        Thread newThread = newThread(threadDelegate);

        newThread.Start();

      }

      Console.Title = "HTTPCacheSample";      Console.ReadLine();

    }

 

    staticvoid TestIt()

    {

      Console.WriteLine(Cache["TestCache"].ToString());

    }

 

  }

}

Console Output:

Diagnostics Output:

8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: null httpRuntime... creating new instance
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: EnsureRuntime...
The thread '<No Name>' (0x119c) has exited with code 0 (0x0).
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
The thread '<No Name>' (0x4ac) has exited with code 0 (0x0).
The thread '<No Name>' (0x21c0) has exited with code 0 (0x0).
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
The thread '<No Name>' (0xedc) has exited with code 0 (0x0).
The thread '<No Name>' (0x1a88) has exited with code 0 (0x0).
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
The thread '<No Name>' (0x1e04) has exited with code 0 (0x0).
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
The thread '<No Name>' (0x21a8) has exited with code 0 (0x0).
The thread '<No Name>' (0x20dc) has exited with code 0 (0x0).
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
The thread '<No Name>' (0x74) has exited with code 0 (0x0).
The thread '<No Name>' (0x1cb4) has exited with code 0 (0x0).
The thread '<No Name>' (0x1da4) has exited with code 0 (0x0).

Tags:

ASP.Net | C#

Override Application Settings C#

by 31. August 2010 17:18

When you create/edit application settings via the projects properties window in Visual Studio (as shown in screen shot below), it will create app/web.config entries (as shown below in sample .config entry below).  However, if you change those entries in the .config file on a deployed app/web instance, you may notice the updated .config values are not actually being used by the application/web when it runs.  In order to have the application/web use the values from your .config file you can write a custom handler (as shown in the sample code below).

Screen shot of properties dialog:

Sample of .config values entered via the propeties dialog:

<applicationSettings> 

  <MyApplication.Properties.Settings> 

    <settingname="MyUserSetting"serializeAs="String">

      <value>white</value>

    </setting>

  </ MyApplication.Properties.Settings>

</applicationSettings>

Sample of code to override the property:

<appSettings>

  <add key="MyackgroundColor"value="white"/>

</appSettings>

 

 

using System;

using System.Configuration;

using System.Drawing;

 

publicclass MyUserSettings : ApplicationSettingsBase

{

  [ApplicationScopedSetting()]

  [DefaultSettingValue("white")]

  public Color BackgroundColor //Note: property name (i.e. BackgroundColor) is arbitrary

  {

    get

    {

      return ((Color)ConfigurationManager.AppSettings["MyBackgroundColor"]);

    }

    set

    {

      this["BackgroundColor"] = (Color)value;

    }

  }

}

 

 

Tags:

ASP.Net | C#

This Setup Requires the .Net Framework Version 4.0

by 30. August 2010 17:10

Attempting to run MSI to deploy website targeted to .Net Framework 3.5 I received this error message: "This setup requires the .net framework version 4.0".  Two steps were required to resolve this:

1) On the setup project properties, change the ASPNETVersion drop-down from: 4.0.30319.0 to: 2.0.50727.0 (version may vary slightly)

2) Right-click on the setup project and select View > Launch Conditions, then click the .NET Framework launch condition and change the Version drop-down from .NET Framework 4 to .NET Framework 3.5

 

Tags:

ASP.Net

JavaScript Check for Undefined Variable (null value)

by 25. August 2010 15:51

if (typeof (myVar) != "undefined" && myVar != null) {

  alert('myVar is defined');

}

Tags:

JavaScript

MS CRM Custom ASPX Page Error: "Input string was not in a correct format."

by 25. August 2010 14:52

When using a custom page in MS CRM, postback calls may fail with this error: "Input string was not in a correct format.".  This is because by default the CRM web.config file will have the following entry:

<pages buffer="true" enableSessionState="false" enableViewState="false" validateRequest="false" />

To fix the issue, either change the enableViewState entry in web.config (from false to true); or, add EnableViewState directive to the ASPX page (as shown below):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyCustomPage.aspx.cs"

  Inherits="MyCustomizations.MyCustomPage" EnableViewState="true" %>

 

Tags:

MS CRM

SQL Convert Milliseconds into "HH:NN:SS" Format

by 20. August 2010 20:21

select

[Duration] as OriginalDuration,

case

  when isnumeric([Duration]) = 1 then

       convert(varchar(25), dateadd(ms, convert(int, [Duration]), '1/1/1900'), 108)

  else '0' + [Duration] end

  as StandardizedDuration

from FiveNine.CallDetails

-- Only sample records with non-zero values

where [Duration] <> '0' and [Duration] <> '0:00:00'

Tags:

SQL Server

SQL Script to Generate Table Inserts

by 20. August 2010 15:19

 

Stored procedure that will generate table inserts: sp_generate_inserts.zip (5.05 kb)

Tags:

SQL Server

JavaScript/CSS Collapsable Regions

by 20. August 2010 15:13

VisualStudio 2010 JavaScript Outlining: Visual Studio 2010 editor extension for JavaScript code blocks and custom regions outlining
http://jsoutlining.codeplex.com/

Alternate method is to use Macro Code:

OptionExplicitOn

OptionStrictOn

 

Imports System

Imports EnvDTE

Imports EnvDTE80

Imports EnvDTE90

Imports System.Diagnostics

Imports System.Collections.Generic

 

PublicModule JsModules

 

  Sub OutlineRegions()

 

    Dim selection As EnvDTE.TextSelection = CType(DTE.ActiveDocument.Selection, EnvDTE.TextSelection)

 

    Const REGION_START AsString = "//#region"

    Const REGION_END AsString = "//#endregion"

 

    selection.SelectAll()

    Dim text AsString = selection.Text

    selection.StartOfDocument(True)

 

    Dim startIndex AsInteger

    Dim endIndex AsInteger

    Dim lastIndex AsInteger = 0

    Dim startRegions AsNew Stack(OfInteger)

 

    Do

      startIndex = text.IndexOf(REGION_START, lastIndex)

      endIndex = text.IndexOf(REGION_END, lastIndex)

 

      If startIndex = -1 AndAlso endIndex = -1 Then

        ExitDo

      EndIf

 

      If startIndex <> -1 AndAlso startIndex < endIndex Then

        startRegions.Push(startIndex)

        lastIndex = startIndex + 1

      Else

        ' Outline region ...

        Dim tempStartIndex AsInteger = CInt(startRegions.Pop())

        selection.MoveToLineAndOffset(CalcLineNumber(text, tempStartIndex), CalcLineOffset(text, tempStartIndex))

        selection.MoveToLineAndOffset(CalcLineNumber(text, endIndex) + 1, 1, True)

        selection.OutlineSection()

 

        lastIndex = endIndex + 1

      EndIf

    Loop

 

    selection.StartOfDocument()

  EndSub

 

  PrivateFunction CalcLineNumber(ByVal text AsString, ByVal index AsInteger) AsInteger

    Dim lineNumber AsInteger = 1

    Dim i AsInteger = 0

 

    While i < index

      If text.Chars(i) = vbLf Then

        lineNumber += 1

        i += 1

      EndIf

 

      If text.Chars(i) = vbCr Then

        lineNumber += 1

        i += 1

        If text.Chars(i) = vbLf Then

          i += 1 'Swallow the next vbLf

        EndIf

      EndIf

 

      i += 1

    EndWhile

 

    Return lineNumber

  EndFunction

 

  PrivateFunction CalcLineOffset(ByVal text AsString, ByVal index AsInteger) AsInteger

    Dim offset AsInteger = 1

    Dim i AsInteger = index - 1

 

    'Count backwards from //#region to the previous line counting the white spaces

    Dim whiteSpaces = 1

    While i >= 0

      Dim chr AsChar = text.Chars(i)

      If chr = vbCr Or chr = vbLf Then

        whiteSpaces = offset

        ExitWhile

      EndIf

      i -= 1

      offset += 1

    EndWhile

 

    'Count forwards from //#region to the end of the region line

    i = index

    offset = 0

    Do

      Dim chr AsChar = text.Chars(i)

      If chr = vbCr Or chr = vbLf Then

        Return whiteSpaces + offset

      EndIf

      offset += 1

      i += 1

    Loop

 

    Return whiteSpaces

  EndFunction

 

EndModule

 

 

See this URL for full posting on Macro code: http://stackoverflow.com/questions/1921628/how-to-implement-regions-code-collapse-in-javascript

Tags:

[None]

Web Site Installation Error: "Could not open key software\microsoft\asp.net\4.0.30319.0"

by 17. August 2010 20:22

Attempting to install website with MSI built in Visual Studio 2010 targeted to ASP.Net v 3.5 I received the following error: "Could not open key software\microsoft\asp.net\4.0.30319.0".  This was due to the fact that although I had set the website target framework to 3.5 the setup project had a property setting for ASPNetVersion 4 (see attached screen shot), changed that setting to 2.0... and the error went away.

Tags:

[None]

jQuery Fixing Flicker Issue with .slideUp()

by 16. August 2010 05:03

Sometimes using the .slideUp() method results in a flicker effect right near the end of the animation.  Two basic resolutions are as follows:

 

 

 

 

Option 1) Add this doctype tag to the html page: 

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

 

Option 2) Set a timeout just short of the .slideUp() animiation length and .stop() the animation and .hide() the element:

 

//Start the slideUp effect lasting 500ms

$('#element').slideUp(500);

 

//Abort the effect just before it finishes and force hide()

//I had to play with the timeout interval until I found one that

// looked exactly right. 400ms worked for me.

setTimeout(function () {

  $('#element').stop(true, true).hide();

}, 400);

 

 

Tags:

JQuery

jQuery

by 14. August 2010 22:02
<scripttype="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>

Tags:

[None]

SQL Select to Find Space Used for each Table

by 13. August 2010 17:08

create table #tbl

(

  [name] varchar(150)

, [rows] int

, [reserved] varchar(25)

, [data] varchar(25)

, [index_size] varchar(25)

, [unused] varchar(25)

)

declare @tbl varchar(100)

declare cur cursor for

select s.name + '.' + o.name from sys.objects o

join sys.schemas s on o.schema_id = s.schema_id

where type = 'U'

open cur

while 1=1 begin

  fetch next from cur into @tbl

  if @@fetch_status <> 0 break

  insert into #tbl exec sp_spaceused@tbl

end

close cur

deallocate cur

select

  name

, rows

, convert(int, replace(reserved, ' KB', '')) reserved_kb

, convert(int, replace(data, ' KB', '')) data_kb

,(convert(float, replace(data, ' KB', ''))/1024*100000)/100000 data_mb

,(convert(float, replace(data, ' KB', ''))/1048576*100000)/100000 data_gb

, convert(int, replace(index_size, ' KB', '')) index_size_kb

, convert(int, replace(unused, ' KB', '')) unused_kb

from #tbl

order by 4 desc

 

 

 

 

Tags:

SQL Server

JavaScript Add Function to Page Dynamically and Determine if Function Exists in Page

by 3. August 2010 23:49

// inject script file into page...

var jQueryScript = document.createElement('script');

jQueryScript.language = 'javascript';

jQueryScript.src = '/ISV/scripts/jquery-1.4.2.min.js';

// setup the event callback...

jQueryScript.onreadystatechange = function () {

  if (event.srcElement.readyState == "complete"

   || event.srcElement.readyState == "loaded")

  // call jQueryReady function only if it is declared in the page...

    if (eval("typeof jQueryReady == 'function'")) { jQueryReady(); }

}

// finally, attach the script file to the page...

document.getElementsByTagName('head')[0].appendChild(jQueryScript);

 

 

Tags:

[None]

SSIS Issue with Importing Excel Files

by 3. August 2010 20:02

Mahesh needs to give me the error...

Tags:

[None]

Website Templates

by 3. August 2010 00:24

Tags:

[None]

Photoshop Copy Layer Styles from One Layer to Another

by 2. August 2010 23:33

Copy layer styles between layers

  1. From the Layers panel, select the layer containing the style you want to copy.
  2. Choose Layer > Layer Style > Copy Layer Style.
  3. Select the destination layer from the panel, and choose Layer > Layer Style > Paste Layer Style.

    The pasted layer style replaces the existing layer style on the destination layer or layers.

Copy layer styles between layers by dragging

Do one of the following:

  • In the Layers panel, Alt-drag (Windows) or Option-drag (Mac OS) a single layer effect from one layer to another to duplicate the layer effect, or drag the Effects bar from one layer to another to duplicate the layer style.

  • Drag one or more layer effects from the Layers panel to the image to apply the resulting layer style to the highest layer in the Layers panel that contains pixels at the drop point.

 

Tags:

[None]