Joseph Michael Pesch
VP Programming

JavaScript Testing Tools

by 25. September 2014 06:35

Tags:

JavaScript

AdventureWorks Sample Database

by 23. September 2014 08:26

Download the 2012 SQL DB version of Microsoft AdventureWorks Sample Database here:


http://msftdbprodsamples.codeplex.com/downloads/get/165399

 

Tags:

SQL Server

Parse JSON in TSQL

by 11. July 2014 06:44

Parsing JSON using TSQL.

/*
  Repost from: https://www.simple-talk.com/sql/t-sql-programming/consuming-json-strings-in-sql-server/
*/

CREATE FUNCTION dbo.parseJSON(@JSON NVARCHAR(MAX))
RETURNS @hierarchy TABLE
  (
   element_id INT IDENTITY(1, 1) NOT NULL,/* internal surrogate primary key gives the order of parsing and the list order */
   sequenceNo [int] NULL, /* the place in the sequence for the element */
   parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */
   Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */
   NAME NVARCHAR(2000),/* the name of the object */
   StringValue NVARCHAR(MAX)NOT NULL,/*the string representation of the value of the element. */
   ValueType VARCHAR(10) NOT null/* the declared type of the value represented as a string in StringValue*/
  )
AS
BEGIN
  DECLARE
    @FirstObject INT, --the index of the first open bracket found in the JSON string
    @OpenDelimiter INT,--the index of the next open bracket found in the JSON string
    @NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string
    @NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string
    @Type NVARCHAR(10),--whether it denotes an object or an array
    @NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'
    @Contents NVARCHAR(MAX),--the unparsed contents of the bracketed expression
    @Start INT, --index of the start of the token that you are parsing
    @end INT,--index of the end of the token that you are parsing
    @param INT,--the parameter at the end of the next Object/Array token
    @EndOfName INT,--the index of the start of the parameter at end of Object/Array token
    @token NVARCHAR(200),--either a string or object
    @value NVARCHAR(MAX),-- the value as a string
    @SequenceNo int, -- the sequence number within a list
    @name NVARCHAR(200),--the name as a string
    @parent_ID INT,--the next parent ID to allocate
    @lenJSON INT,--the current length of the JSON String
    @characters NCHAR(36),--used to convert hex to decimal
    @result BIGINT,--the value of the hex symbol being parsed
    @index SMALLINT,--used for parsing the hex value
    @Escape INT --the index of the next escape character
  DECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */
    (
     String_ID INT IDENTITY(1, 1),
     StringValue NVARCHAR(MAX)
    )
  SELECT--initialise the characters to convert hex to ascii
    @characters='0123456789abcdefghijklmnopqrstuvwxyz',
    @SequenceNo=0,--set the sequence no. to something sensible.
  /* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */
    @parent_ID=0;
  WHILE 1=1 --forever until there is nothing more to do
    BEGIN
      SELECT
        @start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string
      IF @start=0 BREAK--no more so drop through the WHILE loop
      IF SUBSTRING(@json, @start+1, 1)='"'
        BEGIN --Delimited Name
          SET @start=@Start+1;
          SET @end=PATINDEX('%[^\]["]%',RIGHT(@json, LEN(@json+'|')-@start)collate SQL_Latin1_General_CP850_Bin);
        END
      IF @end=0 --no end delimiter to last string
        BREAK --no more
      SELECT @token=SUBSTRING(@json, @start+1, @end-1)
      --now put in the escaped control characters
      SELECT @token=REPLACE(@token, FROMString, TOString)
      FROM
        (SELECT
          '\"' AS FromString,'"' AS ToString
         UNION ALL SELECT'\\', '\'
         UNION ALL SELECT'\/', '/'
         UNION ALL SELECT'\b', CHAR(08)
         UNION ALL SELECT'\f', CHAR(12)
         UNION ALL SELECT'\n', CHAR(10)
         UNION ALL SELECT'\r', CHAR(13)
         UNION ALL SELECT'\t', CHAR(09)
        ) substitutions
      SELECT @result=0, @escape=1
  --Begin to take out any hex escape codes
      WHILE @escape>0
        BEGIN
          SELECT @index=0,
          --find the next hex escape sequence
          @escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin)
          IF @escape>0 --if there is one
            BEGIN
              WHILE @index<4 --there are always four digits to a \x sequence  
                BEGIN
                  SELECT --determine its value
                    @result=@result+POWER(16, @index)
                    *(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1),
                                @characters)-1), @index=@index+1 ;
                END
                -- and replace the hex sequence by its unicode value
              SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result))
            END
        END
      --now store the string away
      INSERT INTO @Strings (StringValue) SELECT @token
      -- and replace the string with a token
      SELECT @JSON=STUFF(@json, @start, @end+1,
                    '@string'+CONVERT(NVARCHAR(5),@@identity))
    END
  -- all strings are now removed. Now we find the first leaf. 
  WHILE 1=1  --forever until there is nothing more to do
  BEGIN
  SELECT @parent_ID=@parent_ID+1
  --find the first object or list by looking for the open bracket
  SELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or array
  IF @FirstObject = 0 BREAK
  IF (SUBSTRING(@json, @FirstObject, 1)='{')
    SELECT @NextCloseDelimiterChar='}', @type='object'
  ELSE
    SELECT @NextCloseDelimiterChar=']', @type='array'
  SELECT @OpenDelimiter=@firstObject
  WHILE 1=1 --find the innermost object or list...
    BEGIN
      SELECT
        @lenJSON=LEN(@JSON+'|')-1
  --find the matching close-delimiter proceeding after the open-delimiter
      SELECT
        @NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json,
                                      @OpenDelimiter+1)
  --is there an intervening open-delimiter of either type
      SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%',
             RIGHT(@json, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object
      IF @NextOpenDelimiter=0
        BREAK
      SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter
      IF @NextCloseDelimiter<@NextOpenDelimiter
        BREAK
      IF SUBSTRING(@json, @NextOpenDelimiter, 1)='{'
        SELECT @NextCloseDelimiterChar='}', @type='object'
      ELSE
        SELECT @NextCloseDelimiterChar=']', @type='array'
      SELECT @OpenDelimiter=@NextOpenDelimiter
    END
  ---and parse out the list or name/value pairs
  SELECT
    @contents=SUBSTRING(@json, @OpenDelimiter+1,
                        @NextCloseDelimiter-@OpenDelimiter-1)
  SELECT
    @JSON=STUFF(@json, @OpenDelimiter,
                @NextCloseDelimiter-@OpenDelimiter+1,
                '@'+@type+CONVERT(NVARCHAR(5), @parent_ID))
  WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))<>0
    BEGIN
      IF @Type='Object'--it will be a 0-n list containing a string followed by a string, number,boolean, or null
        BEGIN
          SELECT
            @SequenceNo=0,@end=CHARINDEX(':',' '+@contents)--if there is anything, it will be a string-based name.
          SELECT  @start=PATINDEX('%[^A-Za-z@][@]%',' '+@contents collate SQL_Latin1_General_CP850_Bin)--AAAAAAAA
          SELECT @token=SUBSTRING(' '+@contents, @start+1, @End-@Start-1),
            @endofname=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin),
            @param=RIGHT(@token,LEN(@token)-@endofname+1)
          SELECT
            @token=LEFT(@token, @endofname-1),
            @Contents=RIGHT(' '+@contents,LEN(' '+@contents+'|')-@end-1)
          SELECT  @name=stringvalue FROM @strings
            WHERE string_id=@param --fetch the name
        END
      ELSE
        SELECT @Name=null,@SequenceNo=@SequenceNo+1
      SELECT
        @end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null
      IF @end=0
        SELECT  @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ' collate SQL_Latin1_General_CP850_Bin)
          +1
       SELECT
        @start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e]%',' '+@contents collate SQL_Latin1_General_CP850_Bin)
      --select @start,@end, LEN(@contents+'|'), @contents 
      SELECT
        @Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)),
        @Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end)
      IF SUBSTRING(@value, 1, 7)='@object'
        INSERT INTO @hierarchy
          (NAME, SequenceNo, parent_ID, StringValue,Object_ID, ValueType)
          SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 8, 5),
            SUBSTRING(@value, 8, 5), 'object'
      ELSE
        IF SUBSTRING(@value, 1, 6)='@array'
          INSERT INTO @hierarchy
            (NAME, SequenceNo, parent_ID, StringValue,Object_ID, ValueType)
            SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 7, 5),
              SUBSTRING(@value, 7, 5), 'array'
        ELSE
          IF SUBSTRING(@value, 1, 7)='@string'
            INSERT INTO @hierarchy
              (NAME, SequenceNo, parent_ID, StringValue, ValueType)
              SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string'
              FROM @strings
              WHERE string_id=SUBSTRING(@value, 8, 5)
          ELSE
            IF @value IN ('true','false')
              INSERT INTO @hierarchy
                (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean'
            ELSE
              IF @value='null'
                INSERT INTO @hierarchy
                  (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                  SELECT @name, @SequenceNo, @parent_ID, @value, 'null'
              ELSE
                IF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)>0
                  INSERT INTO @hierarchy
                    (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                    SELECT @name, @SequenceNo, @parent_ID, @value, 'real'
                ELSE
                  INSERT INTO @hierarchy
                    (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                    SELECT @name, @SequenceNo, @parent_ID, @value, 'int'
      if @Contents=' 'Select @SequenceNo=0
    END
  END
INSERT INTO @hierarchy (NAME, SequenceNo, parent_ID, StringValue,Object_ID, ValueType)
  SELECT '-',1,NULL, '', @parent_id-1, @type
--
   RETURN
END
GO

-- Create the data type
IF EXISTS (SELECT * FROM sys.types WHERE name LIKE 'Hierarchy')
  DROP TYPE dbo.Hierarchy
go
CREATE TYPE dbo.Hierarchy AS TABLE
(
   element_id INT NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */
   sequenceNo [int] NULL, /* the place in the sequence for the element */
   parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */
   [Object_ID] INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */
   NAME NVARCHAR(2000),/* the name of the object, null if it hasn't got one */
   StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */
   ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/
    PRIMARY KEY (element_id)
)

Tags:

SQL Server

Forcing HTTPS Over HTTP

by 7. July 2014 15:32

The <rewrite> section below will force HTTPS over HTTP:

  <system.webServer>
    <modules>
      <remove name="FormsAuthenticationModule" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <rewrite>
      <rules>
        <rule name="Redirect to https">
          <match url="(.*)"/>
          <conditions>
            <add input="{HTTPS}" pattern="Off"/>
            <add input="{REQUEST_METHOD}" pattern="^get$|^head$" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"/>
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

Tags:

ASP.Net

ASP.Net MVC Bind Boolean to DropDownList Using @Html.DropDownListFor

by 25. June 2014 07:41

I was having difficulty binding a bool property to a DropDownList using the @Html.DropDownListFor() method.  What ended up working well was to do the following:

 

Add this to the View Controller class:

private void Select_YN_Rebind()
{
  List<SelectListItem> Select_YN = new List<SelectListItem>();
  Select_YN.Add(new SelectListItem
  {
    Text = "No",
    Value = bool.FalseString
  });
  Select_YN.Add(new SelectListItem
  {
    Text = "Yes",
    Value = bool.TrueString
  });
  ViewData["Select_YN"] = Select_YN;
}


Add call to the new method in the View Controller Create method (or whatever other method is appropriate) before returning the view:

public ActionResult Create()
{
  Select_YN_Rebind();
  return View();
}

Call the @Html.DropDownListFor() as shown below:

 @Html.DropDownListFor(model => model.YourBoolPropertyHere
, (IEnumerable<SelectListItem>)ViewData["Select_YN"])

 

Tags:

ASP.Net | MVC

ASP.Net MVC 5 Issue Validating Numbers (Decimal) when Number Contains Commas

by 20. June 2014 11:37

ASP.Net MVC 5 number (decimal) validation failing when user entered data contains commas.  To get around this issue I created a custom

Create the following object and bind it in the Global.asax as shown below.

GLOBAL.ASAX

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());

NEW .CS FILE

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyApp.Models.Binders
{
  public class DecimalModelBinder : IModelBinder
  {
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
      ValueProviderResult valueResult = bindingContext.ValueProvider
          .GetValue(bindingContext.ModelName);
      ModelState modelState = new ModelState { Value = valueResult };
      object actualValue = null;
      try
      {
        //Check if this is a nullable decimal and a null or empty string has been passed
        var isNullableAndNull = (bindingContext.ModelMetadata.IsNullableValueType &&
                                 string.IsNullOrEmpty(valueResult.AttemptedValue));

        //If not nullable and null then we should try and parse the decimal
        if (!isNullableAndNull)
        {
          actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
        }
      }
      catch (FormatException e)
      {
        modelState.Errors.Add(e);
      }

      bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
      return actualValue;
    }
  }
}

Tags:

ASP.Net

ASP.Net MVC 5 Issue Validating Numbers (Decimal) when Number Contains Commas

by 20. June 2014 11:37

ASP.Net MVC 5 number (decimal) validation failing when user entered data contains commas.  To get around this issue I created a custom

Create the following object and bind it in the Global.asax as shown below.  NOTE: For javascript client side validations create a new *.js file and make sure to include it AFTER the jquery.validate* in the BundleConfig.cs.

JAVASCRIPT OVERRIDE

$.validator.methods.range = function (value, element, param) {
  var globalizedValue = value.replace(",", ".");
  return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]);
}
$.validator.methods.number = function (value, element) {
  return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value);
};

GLOBAL.ASAX ADDITION

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());

NEW .CS FILE

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyApp.Models.Binders
{
  public class DecimalModelBinder : IModelBinder
  {
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
      ValueProviderResult valueResult = bindingContext.ValueProvider
          .GetValue(bindingContext.ModelName);
      ModelState modelState = new ModelState { Value = valueResult };
      object actualValue = null;
      try
      {
        //Check if this is a nullable decimal and a null or empty string has been passed
        var isNullableAndNull = (bindingContext.ModelMetadata.IsNullableValueType &&
                                 string.IsNullOrEmpty(valueResult.AttemptedValue));

        //If not nullable and null then we should try and parse the decimal
        if (!isNullableAndNull)
        {
          actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
        }
      }
      catch (FormatException e)
      {
        modelState.Errors.Add(e);
      }

      bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
      return actualValue;
    }
  }
}

Tags:

ASP.Net | MVC

MVC and/or Web API Url Routes Resulting in Page Not Found (http 404 error)

by 16. May 2014 08:39

I was running an MVC/API site on my local development machine using Visual Studio 2013 and when I deployed the site to a development server all the URL routes resulted in page not found (404 error).  To resolve I added the following to the the configuration file.

<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*."
verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule"
scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll"
preCondition="classicMode,runtimeVersionv4.0,bitness32"
responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*."
verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule"
scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"
preCondition="classicMode,runtimeVersionv4.0,bitness64"
responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*."
verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" /> </handlers>
</system.webServer>


Tags: ,

C#

Migrating SQL Server Database from Newer version (SQL 2012) to Older Version (SQL 2008 r2)

by 16. May 2014 07:08

I was trying to backup and restore a SQL 2012 database to a SQL 2008r2 server; however, that is not supported (you can only go from previous versions to newer version and not the other way). An alternative method is to use the SQL "Tasks > Copy Database" option when right-clicking on the source database.  Steps to use this method:

  • Right click on source database and select "Tasks > Copy Database"
  • Select source server
  • Select target server
    • Note: If using the "Use Windows Authentication" option make sure to add the necessary login to the source database.  (typically it would be in the form of DOMAIN\MACHINENAME$).
  • On the next screen you will have the option for either "Use the detach and attach method"; or, "Use the SQL Management Object method".  You must use the second option as the detach/attach method will fail similar to a backup/restore (i.e. cannot go from higher version to lower version).
  • Select source database
  • Select destination database
  • Provide package name
  • Schedule the package
  • Finished

At this point there will be a new SQL Agent Job on the target server with the name defined above.  Make sure the target database does not exist before running the job (there is an option to setup the job to overwrite the database if you prefer when setting up the initial job).

 

Tags:

SQL Server

C# Windows Form TreeView Drag/Drop Move and Copy Nodes, Move Nodes Up/Down and Expand on Hover

by 25. April 2014 08:13

The below code is sample of TreeView drag/drop events that supports the following:

  • Move a TreeNode by dragging and dropping with the left mouse button
  • Copy a TreeNode by dragging and dropping with the right mouse button
  • Move a TreeNode up one node by double-clicking it with the left mouse button
  • Move a TreeNode down one node by double-clicking it with the right mouse button
#region Treeview Drag/Drop Events

private void TestIt()
{
  this.MyTreeView.AllowDrop = true;
  // Add sample nodes
  TreeNode node;
  for (int x = 0; x < 5; ++x)
  {
    // Add the root node
    node = this.MyTreeView.Nodes.Add(String.Format("Node {0}", x * 4));
    for (int y = 1; y < 4; ++y)
    {
      // Add a child node to the previously added node.
      node = node.Nodes.Add(String.Format("Node{0}", x * 4 + y));
    }
  }
}
private void MyTreeView_ItemDrag(object sender, ItemDragEventArgs e)
{
  // Move the dragged node when the left mouse button is used. 
  if (e.Button == MouseButtons.Left)
  {
    DoDragDrop(e.Item, DragDropEffects.Move);
  }
  // Copy the dragged node when the right mouse button is used. 
  else if (e.Button == MouseButtons.Right)
  {
    DoDragDrop(e.Item, DragDropEffects.Copy);
  }
}

// Set the target drop effect to the effect  
// specified in the ItemDrag event handler. 
private void MyTreeView_DragEnter(object sender, DragEventArgs e)
{
  e.Effect = e.AllowedEffect;
}

// Select the node under the mouse pointer to indicate the  
// expected drop location. 

TreeNode lastDragDestination = null;
DateTime lastDragDestinationTime;
private void MyTreeView_DragOver(object sender, DragEventArgs e)
{
  // Retrieve the client coordinates of the mouse position.
  Point targetPoint = MyTreeView.PointToClient(new Point(e.X, e.Y));

  // Select the node at the mouse position.
  MyTreeView.SelectedNode = MyTreeView.GetNodeAt(targetPoint);

  TreeNode destinationNode = null;
  //get current location
  Point pt = new Point(e.X, e.Y);
  pt = MyTreeView.PointToClient(pt);
  destinationNode = MyTreeView.GetNodeAt(pt);
  if (destinationNode == null)
  {
    return;
  }

  //if we are on a new object, reset our timer
  //otherwise check to see if enough time has passed and expand the destination node
  if (destinationNode != lastDragDestination)
  {
    lastDragDestination = destinationNode;
    lastDragDestinationTime = DateTime.Now;
  }
  else
  {
    TimeSpan hoverTime = DateTime.Now.Subtract(lastDragDestinationTime);
    if (hoverTime.TotalMilliseconds > 500)
    {
      destinationNode.Expand();
    }
  }

}

private void MyTreeView_DragDrop(object sender, DragEventArgs e)
{
  // Retrieve the client coordinates of the drop location.
  Point targetPoint = MyTreeView.PointToClient(new Point(e.X, e.Y));

  // Retrieve the node at the drop location.
  TreeNode targetNode = MyTreeView.GetNodeAt(targetPoint);

  // Retrieve the node that was dragged.
  TreeNode draggedNode = (TreeNode)e.Data.GetData(typeof(TreeNode));

  // Confirm that the node at the drop location is not  
  // the dragged node or a descendant of the dragged node. 
  if (!draggedNode.Equals(targetNode) && !ContainsNode(draggedNode, targetNode))
  {
    // If it is a move operation, remove the node from its current  
    // location and add it to the node at the drop location. 
    if (e.Effect == DragDropEffects.Move)
    {
      draggedNode.Remove();
      targetNode.Nodes.Add(draggedNode);
    }

    // If it is a copy operation, clone the dragged node  
    // and add it to the node at the drop location. 
    else if (e.Effect == DragDropEffects.Copy)
    {
      targetNode.Nodes.Add((TreeNode)draggedNode.Clone());
    }

    // Expand the node at the location  
    // to show the dropped node.
    targetNode.Expand();
  }
}

// Determine whether one node is a parent  
// or ancestor of a second node. 
private bool ContainsNode(TreeNode node1, TreeNode node2)
{
  // Check the parent node of the second node. 
  if (node2.Parent == null) return false;
  if (node2.Parent.Equals(node1)) return true;

  // If the parent node is not null or equal to the first node,  
  // call the ContainsNode method recursively using the parent of  
  // the second node. 
  return ContainsNode(node1, node2.Parent);
}

private void MyTreeView_DoubleClick(object sender, EventArgs e)
{
  // Retrieve the client coordinates of the mouse position.
  Point targetPoint = new Point(((MouseEventArgs)e).X, ((MouseEventArgs)e).Y);

  // Select the node at the mouse position.
  this.MyTreeView.SelectedNode = this.MyTreeView.GetNodeAt(targetPoint);
  if (((MouseEventArgs)e).Button.Equals(MouseButtons.Right))
    Extensions.MoveNodeDown(this.MyTreeView.SelectedNode);
  else
    Extensions.MoveNodeUp(this.MyTreeView.SelectedNode);

}

#endregion

Tags:

C#

jQuery UI Dialog Height Issue - Height Collapses when Re-Opening a Dialog

by 17. February 2014 21:36

I experienced an issue with jQuery dialog box if I opened the same dialog a second time the height would be collapsed so the content was not showing.  It seems the issue is related to allowing the jQuery dialog to open on creation (i.e. autoOpen = true, which is the default so if you leave the autoOpen parameter off the dialog creation it will autoOpen by default).  Instead, you should create the dialog (with autoOpen = false) and then explicitly open the dialog (e.g. $dlg.dialog('open'), see sample code below). 

/* Problem code */
$("#objectid").dialog({
  height: 680,
  width: 800,
  modal: true,
  resizable: false
});

/* Solution code */
var $dlg = $("#objectid");
$dlg.dialog({ autoOpen: false, height: 680, width: 800, modal: true, resizable: false }); $dlg.dialog('open');

 

 

Tags:

JQuery

SQL Select Statement to Calculate Monthly Loan Payment

by 27. January 2014 08:15

The following SQL statement will calculate a monthly loan payment (principal and interest).

select CalculatedPmt =
  cast(
    LoanAmount
      / (power(1+((NoteRate*.01)/cast(12 as float)),LoanTermMonths)-1)
      * (((NoteRate*.01)/cast(12 as float))
      * power(1+((NoteRate*.01)/cast(12 as float)),LoanTermMonths))
    as decimal(10,2))

Tags:

SQL Server

SSAS Cube Queries to Extract Cube Measures, Dimensions, Attributes, etc.

by 1. January 2014 19:50

Tags:

SSAS

C# Auto-Rotate Image Based on Camera Rotation Exif Data

by 27. December 2013 08:14

This method uses ExifExtractor code referenced below from CodeProject.com.

public static Bitmap AutoRotateImage(Bitmap bmp)
{
  // Get source from: http://www.codeproject.com/KB/graphics/exifextractor.aspx?fid=207371
  var exif = new EXIFextractor(ref bmp, "n");
  switch (int.Parse(exif["Orientation"].ToString()))
  {
    case 1:
      bmp.RotateFlip(RotateFlipType.RotateNoneFlipNone);
      break;
    case 2:
      bmp.RotateFlip(RotateFlipType.RotateNoneFlipX);
      break;
    case 3:
      bmp.RotateFlip(RotateFlipType.Rotate180FlipNone);
      break;
    case 4:
      bmp.RotateFlip(RotateFlipType.Rotate180FlipX);
      break;
    case 5:
      bmp.RotateFlip(RotateFlipType.Rotate90FlipX);
      break;
    case 6:
      bmp.RotateFlip(RotateFlipType.Rotate90FlipNone);
      break;
    case 7:
      bmp.RotateFlip(RotateFlipType.Rotate270FlipX);
      break;
    case 8:
      bmp.RotateFlip(RotateFlipType.Rotate270FlipNone);
      break;
    default:
      bmp.RotateFlip(RotateFlipType.RotateNoneFlipNone);
      break;
  }
  return bmp;
}

 

Tags:

C#

Entity Framework Error Saving - New transaction is not allowed because there are other threads running in the session

by 1. December 2013 14:12

When running inside a foreach() statement this error will occur unless you convert the Entity objects into a List.

// Original code that errors:
myFlickr = FlickrAuthentication();
using (FlickrPicsModel.FlickrPicsEntities dbx = new FlickrPicsModel.FlickrPicsEntities())
{
  foreach (FlickrPicsModel.Pic pic in dbx.Pics.Where(t => t.ProcessDate.Value >= MinDate &&
    t.FlickrPhotoId == null))
  {
    pic.FlickrPhotoId = myFlickr.UploadPicture(string.Concat(pic.FilePath, @"\", pic.FileName)
      , pic.FlickrTags, pic.FlickrTags, pic.FlickrTags + ",CS-" + pic.CheckSum.ToString());
    dbx.SaveChanges();
  }
}

// New code converting to IList:

myFlickr = FlickrAuthentication();
using (FlickrPicsModel.FlickrPicsEntities dbx = new FlickrPicsModel.FlickrPicsEntities())
{
  foreach (FlickrPicsModel.Pic pic in dbx.Pics.Where(t => t.ProcessDate.Value >= MinDate &&
    t.FlickrPhotoId == null).ToList())
  {
    pic.FlickrPhotoId = myFlickr.UploadPicture(string.Concat(pic.FilePath, @"\", pic.FileName)
      , pic.FlickrTags, pic.FlickrTags, pic.FlickrTags + ",CS-" + pic.CheckSum.ToString());
    dbx.SaveChanges();
  }
}

Error Message: New transaction is not allowed because there are other threads running in the session.

Tags:

Visual Studio Open Database Error: Failed to Generate a User Instance of SQL Server

by 29. November 2013 12:48

Running SQLExpress and trying to open database from Visual Studio.  In my case I originally had SQL 2008 and 2012 installed.  Then I added 2008R2 and deleted 2008.  After that when trying to open a database (from App_Data folder of Visual Studio project) using the Server Explorer in Visual Studio I received the following error message: "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.".  To resolve I simply deleted the following folder and then restarted Visual Studio: C:\Users\...\AppData\Local\Microsoft\Microsoft SQL Server Data

Tags:

SQL Server | Visual Studio

nuget.psm1 Cannot be Loaded Because the Execution of Scripts is Disabled on this System

by 29. November 2013 08:43

File C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft Corporation\NuGet Package Manager\2.7.40911.225\Modules\NuGet\nuget.psm1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.

Launch Powershell as admin and run this command: "Set-ExecutionPolicy RemoteSigned"

Restart Visual Studio

Tags:

Visual Studio

SharePoint Document Sets

by 27. November 2013 08:49

Tags:

Sharepoint

SharePoint Always Run Configuration Wizard on All Farm Servers After Server Patching

by 26. November 2013 13:52

After patching (SharePoint updates) you need to run the configuration wizard.  The configuration wizard has to be ran on all SP servers in the farm. There is a command line that forces the wizard to re-run in the event of an issue or failure with the wizard. 

Psconfig.exe -cmd upgrade -inplace b2b -wait -force.

Tags:

Sharepoint

Link Outlook Calendar to Sharepoint

by 26. November 2013 07:48

Tags: