Joseph Michael Pesch
VP Programming

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:

C# App.Config Custom Dictionary Section to Store Simple Key/Value Pairs

by 4. November 2013 06:12

Below is a sample app.config using a custom dictionary section to store simple key/value pairs:

<configuration>
  <configSections>
    <section name="CustomDictionarySection" type="System.Configuration.DictionarySectionHandler"/>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <CustomDictionarySection>
    <add key="Key1" value="Value 1" />
    <add key="Key2" value="Value 2" />
    <add key="Key3" value="Value 3" />
  </CustomDictionarySection>
</configuration>
class Program
{
  static void Main(string[] args)
  {
    string key = "Key2";
    var section = (ConfigurationManager.GetSection("CustomDictionarySection") as System.Collections.Hashtable)
                .Cast<System.Collections.DictionaryEntry>()
                .Where(t => t.Key.ToString() == key);
    if (section.Count() > 0)
      Console.WriteLine(string.Format("Found section with key: {0} containing value: {1}", key, section.First().Value));
    else
      Console.WriteLine(string.Format("Could not find section with key: {0}", key));
    Console.Read();
  }
}

Tags:

C#

plUpload IO Error 2032

by 26. October 2013 12:58

Using plUpload I was getting IO Error 2032 on larger file uploads.  Two settings that seemed to be associated to this.  First, if I added the resize attribute (i.e. resize: { width: 1000, height: 1000, quality: 90 }, ); however, I didn't really want to resize and was concerned that could have browser dependencies that may not be well supported in all cases.  The second fix I actually opted for in this case was adding the chunk_size attribute.  The interesting issue I didn't figure out yet was adding as chunk_size: '1mb', worked even though my original attempt adding chunk_size: '64kb', failed.

Tags:

JQuery | plUpload

jQuery $(document).ready() Not Working with ASP.Net UpdatePanel PostBack

by 27. September 2013 20:21

When using jQuery and $(document).ready() event along with an ASP.Net UpdatePanel the $(document).ready() event will only fire on the initial page load and will not fire on subsequent AJAX postbacks via the UpdatePanel.  There are a couple of common solutions posted to deal with this (shown below).  My preference is the first option which seems cleaner and has proven more reliable for me.

Solution 1:  Wrap the $(document).ready() event inside a pageLoad() function since the AJAX postback will always fire the pageLoad() event function.

function pageLoad() {
  $(document).ready(function () {
    DoPageInitialization();
  });
}

Solution 2:  Add a reference to the PageRequestManager and register your function to the add_endrequest() event.

$(document).ready(function() {
  // Still needed as the PageRequestManager below only fires on the postback...
  DoPageInitialization();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
  // Secondary binding for all AJAX postbacks through the UpdatePanel
  DoPageInitialization();
});

function DoPageInitialization() {
  ... Document Ready Code Here ...
}


Here is a good post that goes into more details on both $(document).ready() and pageLoad()
http://encosia.com/document-ready-and-pageload-are-not-the-same/

Tags:

ASP.Net | JavaScript | JQuery

SharePoint WebPart Maintenance Page

by 5. September 2013 12:09

Issue with SharePoint is that the WebParts already in place on an existing page don't indicate what type of web part they actually are.  This is frustrating if it is not obvious what type of web part you are looking at.  In order to get a better view of the WebPart in question you can navigate to the WebPart Maintenance Page by entering a URL like this: http://yoursite/whatever/default.aspx?contents=1

Tags:

Sharepoint

C# Http Remote Page Post

by 30. August 2013 14:15
NameValueCollection Inputs = new NameValueCollection();
Inputs.Add("param1", "something");
Inputs.Add("param2", "somethingelse");
Http.RemotePost("http://google.com", Inputs);

using System.Collections.Specialized;
using System.Net;

public static class Http
{
  public static void RemotePost(string Url, NameValueCollection Inputs)
  {
    System.Web.HttpContext.Current.Response.Clear();
    System.Web.HttpContext.Current.Response.Write("<html><head>");
    System.Web.HttpContext.Current.Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", "form1"));
    System.Web.HttpContext.Current.Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", "form1", "post", Url));
    for (int i = 0; i < Inputs.Keys.Count; i++)
    {
      System.Web.HttpContext.Current.Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", Inputs.Keys[i], Inputs[Inputs.Keys[i]]));
    }
    System.Web.HttpContext.Current.Response.Write("</form>");
    System.Web.HttpContext.Current.Response.Write("</body></html>");
    System.Web.HttpContext.Current.Response.End();
  }
}

Tags:

C#

Sharepoint PDF Document Prompting User to Checkout when it Shouldn't

by 26. August 2013 15:54

We had issues with PDF documents on Sharepoint that were prompting the average "View Only" users to check-out the document.  If they actually attempted to check-out the document they could not; however, this was cofusing to the users.  The desired effect was to have the document open directly into the PDF viewer.  Below are some registry settings that seemed to clear this issue up in most cases.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Adobe\Adobe Acrobat\11.0\FeatureLockDown\cSharePoint]
"bDisableSharePointFeatures"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Adobe\Adobe Acrobat\10.0\FeatureLockDown\cSharePoint]
"bDisableSharePointFeatures"=dword:00000001

Tags:

Sharepoint

SQL DBCC ShrinkFile Not Working (i.e. Executes Successfully But File Does Not Shrink)

by 22. August 2013 12:41

When attempting to run "DBCC ShrinkFile" SQL command to shrink a transaction log file on a database that has replication enabled it may appear to have run successfully; however, the log file may not actually shrink.  To resolve this issue you can add a call to "EXEC sp_repldone" to allow the server to take action on the log file.  Below is a sample process that I have added to a nightly job to take place after the full DB backup executes.

use DBName;
go
alter database DBName set recovery simple;
go
exec sp_repldone @xactid = NULL, @xact_segno = NULL, @numtrans = 0, @time = 0, @reset = 1
go
dbcc SHRINKFILE (DBName_log, 1);
go
alter database DBName set recovery full;
go

Tags:

SQL Server