Joseph Michael Pesch
VP Programming

ASP.Net Compile File System Website

by 6. January 2012 15:53

Below is an example of command program to compile an ASP.Net file system web using .Net framework v4 (the rem comment lines show the value for compiling as v2 as well).

rem v2.0.50727
rem v4.0.30319
set frmwk=C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319

set src=C:\vss\MyWebSiteFolder
set dest=C:\vss\MyCompiledWebSiteFolder

del /F /Q %dest%\*.*

%frmwk%\aspnet_compiler -v /VwdSite -p %src% %dest% -c



ASP.Net .ASMX WebService Invocation Test Page Remote Access

by 18. October 2011 07:32

The ASP.Net .ASMX webservice page comes with an automatic invocation test page for each of the available operations defined in the service.  By default the invocation is limited to the service running on a local machine (e.g. if you are running the service on your local machine and browse to it you can invoke it;).  However, if the service is running on a server and you browse from your local machine you will probably see this message "The test form is only available for requests from the local machine" in the spot where the invocation button would normally be.  To enable remote invocation, make sure to add the web config section shown below.

        <add name="HttpGet"/>
        <add name="HttpPost"/>


ASP.Net | Web Service

ASP.Net Security Issue FormsAuthentication.Authenticate Always Returns false

by 14. October 2011 09:42

I was trying to create a custom authentication screen without using any of the standard ASP.Net security controls (i.e. Login control).  So, I created my custom form and was calling the System.Web.Security.FormsAuthentication.Authenticate(UserName, Password) method.  However, it was always returning false and in fact did not appear to even be hitting my SQL database (which contained the security) as the failed login attempts, etc. were all unaltered.  Furthermore, I changed my connection string to be a bogus reference and the Authenticate still simple returned false (I was expecting it to error).  I then found out that the System.Web.Security.FormsAuthentication.Authenticate(UserName, Password) method is for user information stored in the web.config file.  Instead, I used the System.Web.Security.Membership.ValidateUser(UserName, Password) method which is for the user information stored in the SQL database.

NOTE: When doing this I also then set the authorization cookie by calling:

System.Web.Security.FormsAuthentication.SetAuthCookie(UserName, true);

Here is some sample code:

static public string Login(string UserName, string Password)
  if (System.Web.Security.Membership.ValidateUser(UserName, Password))
    System.Web.Security.FormsAuthentication.SetAuthCookie(UserName, true);
    return "1|" + DateTime.Now.ToString();
    return "0|Login failed!";


ASP.Net | C#

ExecuteScalar() Truncates Xml Using SQL For Xml

by 24. February 2011 07:51

Use this style as the Sql server actually returns multiple rows of the Xml in 2,033 byte chunks:

System.Xml.XmlReader rdr = cmd.ExecuteXmlReader();
while (rdr.ReadState != System.Xml.ReadState.EndOfFile)


ASP.Net | SQL Server

Asp.Net Url Rewriting Alternative .Net Framework 4.0 RouteTable

by 13. January 2011 11:50

/* Global.asax.cs */

using System;
using System.Collections;
using System.Configuration;
using System.Linq;
using System.Web.Routing;
namespace JMP.UrlReWrite
  public class Global_ASAX : System.Web.HttpApplication
    protected void Application_Start()
    public static void RegisterRoutes(RouteCollection routes)
      Hashtable tbl = (Hashtable)ConfigurationManager.GetSection("RouteTable");
      foreach (DictionaryEntry de in tbl)
        routes.MapPageRoute((de.Key.ToString().Split('/').Count() == 1) 
          ? de.Key.ToString() : Guid.NewGuid().ToString()
          , de.Key.ToString(), de.Value.ToString());

/* Default.aspx.cs */

using System;

namespace JMP.UrlRewrite
  public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
      if (Page.RouteData.Values.ContainsKey("module"))
        switch (Page.RouteData.Values["module"].ToString())
          case "aboutus": Response.RedirectToRoute("about"); break;

/* web.config */

<?xml version="1.0" encoding="UTF-8"?>
    <section name="RouteTable" type="System.Configuration.DictionarySectionHandler" />
    <add key="home" value="~/default.aspx" />
    <add key="home/{module}" value="~/default.aspx" />
    <add key="about" value="~/aboutus.aspx" />
    <!-- aboutus is being mapped in default.aspx.cs just to illustrate reading the parameters -->
    <!-- test url: ~/home/aboutus -->
    <add key="contact" value="~/contactus.aspx" />
    <add key="contactus" value="~/contactus.aspx" />
        verb="*" path="UrlRouting.axd"
        type="System.Web.HttpForbiddenHandler, System.Web,  
          Version=, Culture=neutral,  
    <validation validateIntegratedModeConfiguration="false"></validation>
    <modules runAllManagedModulesForAllRequests="true">
     <remove name="UrlRoutingModule"/>
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    <customErrors mode="Off" />
    <compilation debug="true" targetFramework="4.0">
    <httpRuntime maxRequestLength="2000000" />
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
        <add namespace="System.Collections.Generic" />
        <add namespace="System.IO" />




Model View View Model (MVVM) Silverlight Sample

by 9. January 2011 10:21


ASP.Net | Silverlight

Simple Web Serivce Call (without Registering Service) Using HttpWebRequest Method

by 22. December 2010 08:13


<%@ WebService Language="C#" Class="SimpleWebService" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
public class SimpleWebService  : System.Web.Services.WebService {
  public string WsTestMethod(long TestId, string TestData)
    return string.Join(" ""You sent TestId:", TestId.ToString(), "; TestData:", TestData);




<%@ Page Language="C#" %>

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Text" %>
<script runat="server">
  protected string RootUrl
      string query = (Request.QueryString == null) ? "" : "?" + Request.QueryString.ToString();
      return Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, string.Empty).Replace(query, string.Empty);
  protected void SubmitButton_Click(object sender, EventArgs e)
    string soap =
    @"<?xml version=""1.0"" encoding=""utf-8""?>
      <soap:Envelope xmlns:xsi="""" 
        <WsTestMethod xmlns="""">
          <TestId>" + this.TestId.Text + @"</TestId>
          <TestData>" + this.TestData.Text + @"</TestData>

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(
      string.Join("", RootUrl, ResolveUrl("~/SimpleWebService.asmx")));
    req.ContentType = "text/xml;charset=\"utf-8\"";
    req.Accept = "text/xml";
    req.Method = "POST";

    Stream str = req.GetRequestStream();
    using (StreamWriter wri = new StreamWriter(str)) wri.Write(soap);

    WebResponse res = req.GetResponse();
    str = res.GetResponseStream();
    this.WsResults.Text = StreamToString(str);


  private string StreamToString(Stream str)
    using (BinaryReader rdr = new BinaryReader(str))
      using (MemoryStream mem = new MemoryStream())
        byte[] buf = new byte[256];
        int bt;
        int bts = 0;
        while ((bt = rdr.Read(buf, 0, 256)) > 0)
          mem.Write(buf, 0, bt);
          bts += bt;
        mem.Position = 0;
        byte[] bytes = new byte[bts];
        mem.Read(bytes, 0, bytes.Length);
        return Encoding.ASCII.GetString(bytes);
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
  <form id="form1" runat="server">
    <asp:TextBox ID="TestId" Text="12345" runat="server"></asp:TextBox>
    <asp:TextBox ID="TestData" Text="Simple Web Service" runat="server"></asp:TextBox>
    <asp:Button ID="SubmitButton" OnClick="SubmitButton_Click" Text="Run Web Service"
      runat="server" />
    <asp:Literal ID="WsResults" runat="server"></asp:Literal>



ASP.Net | C# | Web Service

Invalid postback or callback argument ASP.Net

by 4. November 2010 15:29

Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

This can happen if you are binding a GridView control on page load unconditionally (i.e. it should only be bound when !Page.IsPostBack).



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





    #region HTTP Runtime Cache


    privatestaticHttpRuntime httpRuntime;

    privatestaticvoid EnsureHttpRuntime()



        + ": EnsureRuntime...");

      if (null == httpRuntime)


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

        httpRuntime = newHttpRuntime();


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



    publicstaticCache Cache






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







    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);



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



    staticvoid TestIt()







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).


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:






  </ MyApplication.Properties.Settings>


Sample of code to override the property:


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




using System;

using System.Configuration;

using System.Drawing;


publicclass MyUserSettings : ApplicationSettingsBase




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




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




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







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




Open Source PDF Generator iTextSharp

by 23. July 2010 17:19

iTextSharp-SampleC#WebSite.zipx (2.49 mb) (1.19 mb)

Sample code to populate form fields in template and save as new document (via C# web page):

using System;

using System.IO;

using iTextSharp.text.pdf;


publicpartialclassFillFormFields : System.Web.UI.Page


  protectedvoid Page_Load(object sender, EventArgs e)





  protectedvoid GeneratePDF()


    // Setup the output file

    string pdfOutputFilePath = @"Output\FillFormFields-"

      + DateTime.Now.ToString()

      .Replace("/", "_")

      .Replace(":", "_")

      .Replace(" ", "_")

      + ".pdf";

    FileStream pdfOutputFile

      = newFileStream(Server.MapPath(pdfOutputFilePath)

        , FileMode.Create, FileAccess.ReadWrite);

    // Load the template file

    PdfReader pdfReader = newPdfReader(Server.MapPath(@"Templates\FillFormFields.pdf"));

    PdfStamper pdfStamper = null;

    pdfStamper = newPdfStamper(pdfReader, pdfOutputFile);

    // Get the form fields object

    AcroFields pdfForm = pdfStamper.AcroFields;

    // Fill the form fields with data

    pdfForm.SetField("Lead.LastAction.Date", DateTime.Now.ToString("MMMM dd, yyyy"));

    // Close the documents

    pdfStamper.FormFlattening = true;









ASP.Net | C#

A potentially dangerous Request.Form value was detected from the client

by 3. July 2010 17:30

This post is not about how to properly deal with this issue, it is solely about how to circumvent the error if you are inclined to do so.

Add ValidateRequest="false" attribute to the @Page directive of the page in question.  NOTE: If running .Net framework 4 you may also need to add <httpRuntimerequestValidationMode="2.0" /> to the <system.websection of the Web.config file.




Linq To SQL Error: Cannot access a disposed object.

by 17. March 2010 14:06

Cannot access a disposed object. Object name: 'DataContext accessed after Dispose.'.  This can happen if you send a Linq query result entity out of a procedure as shown below.  The issues is that the inner procedure has not actually evaluated the query (i.e. results have not been retrieved from the SQL server, just the construct for the query exists).  When you leave the inner procedure and attempt to access the data within the outer procedure the database context is gone (since it was wrapped in a using statement).  Only at the point when you attempt to access the data members will the actual query results be requested from the SQL server and at that point there is no database context under which to execute the query.  You may get the process to work by removing the using statement; however, that is not a correct practice.  The better solution is to return an IEnumerable list using the .ToList() method on the result entity you are returning.  This will force the query to execute and the full result set will be populated into the returned list.

Outer Procedure Code:
   IEnumerable<BidMortgage.BMObject.LowestBid> bids = BidMortgage.BMObject.GetLowestBids();

   /* Error here if not using .ToList<>() */
   foreach (BidMortgage.BMObject.LowestBid bid in bids)


Inner Procedure Code:

public class LowestBid


   public LowestBid()



   public int LoanTypeID { get; set; }

   public string LoanTypeName { get; set; }

   public decimal CalculatedAPR { get; set; }

   public decimal InterestRate { get; set; }




public static IEnumerable<LowestBid> GetLowestBids()


  DataTable tbl = new DataTable();



    using (BidMortgage.BidMortgageDataContext db = new BidMortgageDataContext())

    return (from row in db.LoanRequestBids

    group row by row.tbl_LoanRequest.LoanTypeID

    into g

    select new LowestBid

    { LoanTypeID = g.Key

      , LoanTypeName = (from itm in db.ListValues_MortgageTypes

                        where itm.TypeValue == g.Key

                        select itm.TypeName).SingleOrDefault()

      , CalculatedAPR = g.Min(t => t.CalculatedAPR)

      , InterestRate = (from itm in db.LoanRequestBids

                        where itm.CalculatedAPR == g.Min(t => t.CalculatedAPR)

                        && itm.tbl_LoanRequest.LoanTypeID == g.Key

                        select itm.InterestRate).SingleOrDefault()


     If you don't use the .ToList<LowestBid>() and just return the select entity you will
     receive this error when attempting to access the data outside of this using statement:
     Cannot access a disposed object. Object name: 'DataContext accessed after Dispose.'.


  catch (Exception)


    return null;





ASP.Net | C# | LINQ to SQL

LINQ to SQL with WCF and Silverlight

by 7. February 2010 19:27

Tags: ,

ASP.Net | LINQ to SQL | Silverlight

Binary Data Serialization LINQ to SQL via Web Service

by 7. February 2010 18:17

In summary, one easy fix is manually change the LINQ data type from Binary (System.Data.Linq.Binary) to byte[] (System.Byte[])

Tags: ,


ASP.Net Read HTML Content from URL

by 5. February 2010 04:49

public static string GetHTMLFromURL(string URL)
  // Download page content   
  WebClient MyWebClient = new WebClient();   
  Byte[] PageHTMLBytes;   
  PageHTMLBytes = MyWebClient.DownloadData(URL);    
  // Convert result from byte array to string   
  UTF8Encoding oUTF8 = new UTF8Encoding();   
  return oUTF8.GetString(PageHTMLBytes); 

Tags: ,


ASP.Net Webservice via WebRequest with SOAP Message

by 27. January 2010 23:08

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebServiceSample
    class Program
        static void Main(string[] args)
            System.Net.WebRequest req = System.Net.WebRequest.Create("");
            req.Method = "POST";

            string cre = String.Format("{0}:{1}", "", "MyPasswordHere");
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(cre);
            string base64 = Convert.ToBase64String(bytes);
            req.PreAuthenticate = true;
            req.Headers.Add("Authorization", "basic " + base64);

            StringBuilder SOAPRequestBody = new StringBuilder();
            SOAPRequestBody.Append("<?xml version=\"1.0\"?>");
            SOAPRequestBody.Append("<S:Envelope xmlns:S=\"\">");
            SOAPRequestBody.Append("<ns2:getListInfo xmlns:ns2=\"\">");

            req.ContentType = "application/soap+xml; charset=utf-8";
            req.ContentLength = SOAPRequestBody.Length;
            System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(req.GetRequestStream());
            System.IO.StreamReader streamReader = new System.IO.StreamReader(req.GetResponse().GetResponseStream());
            string strResponse = "";
            while (!streamReader.EndOfStream)
                strResponse += streamReader.ReadLine();

            System.Net.WebResponse resp = req.GetResponse();



Tags: ,


Email Current HTML Page with ASP.Net

by 24. January 2010 04:57

  /// <summary>
  /// Overridden to handle Confirmation of the order by
  /// capturing the HTTP output and emailing it.
  /// </summary>
  /// <param name="writer"></param>
  protected override void Render(HtmlTextWriter writer)
    // *** Write the HTML into this string builder
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    HtmlTextWriter hWriter = new HtmlTextWriter(sw);
    // *** store to a string
    string PageResult = sb.ToString();
    // *** Write it back to the server
    // *** Do something with the PageResult here like email it...

Tags: ,

ASP.Net | C#

Workflow Foundation Error with Distributed Transaction Coordinator

by 7. August 2009 20:26

System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Workflow.Runtime.Hosting.PersistenceException: Communication with the underlying transaction manager has failed. ---> System.Transactions.TransactionManagerCommunicationException: Communication with the underlying transaction manager has failed. ---> System.Runtime.InteropServices.COMException (0x80004005): Error HRESULT E_FAIL has been returned from a call to a COM component.
  at System.Transactions.Oletx.IDtcProxyShimFactory.ReceiveTransaction(UInt32 propgationTokenSize, Byte[] propgationToken, IntPtr managedIdentifier, Guid& transactionIdentifier, OletxTransactionIsolationLevel& isolationLevel, ITransactionShim& transactionShim)
  at System.Transactions.TransactionInterop.GetOletxTransactionFromTransmitterPropigationToken(Byte[] propagationToken)
  --- End of inner exception stack trace ---
  at System.Workflow.Runtime.Hosting.SqlWorkflowPersistenceService.System.Workflow.Runtime.IPendingWork.Commit(Transaction transaction, ICollection items)
  at System.Workflow.Runtime.WorkBatch.PendingWorkCollection.Commit(Transaction transaction)
  at System.Workflow.Runtime.WorkBatch.Commit(Transaction transaction)
  at System.Workflow.Runtime.VolatileResourceManager.Commit()
  at System.Workflow.Runtime.WorkflowExecutor.DoResourceManagerCommit()
  at System.Workflow.Runtime.Hosting.WorkflowCommitWorkBatchService.CommitWorkBatch(CommitWorkBatchCallback commitWorkBatchCallback)
  at System.Workflow.Runtime.Hosting.DefaultWorkflowCommitWorkBatchService.CommitWorkBatch(CommitWorkBatchCallback commitWorkBatchCallback)
  at System.Workflow.Runtime.WorkflowExecutor.CommitTransaction(Activity activityContext)
  at System.Workflow.Runtime.WorkflowExecutor.Persist(Activity dynamicActivity, Boolean unlock, Boolean needsCompensation)
  --- End of inner exception stack trace ---
  at System.Workflow.Runtime.WorkflowExecutor.Persist(Activity dynamicActivity, Boolean unlock, Boolean needsCompensation)
  at System.Workflow.Runtime.WorkflowExecutor.PerformUnloading(Boolean handleExceptions)
  at System.Workflow.Runtime.WorkflowExecutor.Unload()
  at System.Workflow.Runtime.WorkflowInstance.Unload()
  at BidMortgageWFWebService.StateMachineWF.NewSubmission(Guid LoanRequestID, Nullable`1 BiddingTimespan)
  at BidMortgageWFWebService.StateMachineWF.NewSubmissionWithBiddingTimeSpan(Guid LoanRequestID, Int32 Days, Int32 Hours, Int32 Minutes, Int32 Seconds)
  --- End of inner exception stack trace ---

To solve the error above, make sure the ports highlighted below are open (bi-directional) between the web and sql servers.

RPC server programs typically use dynamic port mappings to avoid conflicts with programs and protocols registered in the range of well-known TCP ports. RPC server programs associate their universally unique identifier (UUID) with a dynamic port and register the combination with the RPC EPM. The EPM provides a single point of contact for RPC clients. The RPC clients contact the EPM and use the server program’s UUID to determine the port being used by the server program. The following table indicates the network ports normally used by RPC.

Network Port Assignments for RPC 

Service Name UDP TCP
HTTP 80, 443, 593 80, 443, 593
Named Pipes 445 445
RPC Endpoint Mapper 135 135
RPC Server Programs <Dynamically assigned> 1024-5000 <Dynamically assigned> 1024-5000

Prior to the above error the errors below were occuring due to the lack of configuration settings shown below.

Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration for MSDTC using the Component Services Administrative tool.

NOTE: When enabling settings shown below on the web server only (i.e. before performing same setting on sql server) I got the following error:

The partner transaction manager has disabled its support for remote/network transactions.

Steps to change settings

On Windows Server 2003 SP1 and Windows XP SP2:

1.     Click Start, click Run, and type dcomcnfg to launch the Component Services Management console.

2.     Click to expand Component Services and click to expand Computers.

3.     Right-click My Computer, and click Properties.

4.     Click the MSDTC tab of the My Computer Properties dialog and click the Security Configuration button to display the Security Configuration dialog box.

On Windows Server 2008 and Windows Vista:

1.     Click Start, click Run, and type dcomcnfg to launch the Component Services Management console.

2.     Click to expand Component Services and click to expand Computers.

3.     Click to expand My Computer, click to expand Distributed Transaction Coordinator, right-click Local DTC, and click Properties.

4.    Click the Security tab of the Local DTC Properties dialog. 





The following is from this link: 

You can configure DTC to communicate through firewalls, including network address translation firewalls.

DTC uses Remote Procedure Call (RPC) dynamic port allocation. By default, RPC dynamic port allocation randomly selects port numbers above 1024. By modifying the registry, you can control which ports RPC dynamically allocates for incoming communication. You can then configure your firewall to confine incoming external communication to only those ports and port 135 (the RPC Endpoint Mapper port).

You must provide one incoming dynamic port for DTC. You may need to provide additional incoming dynamic ports for other subsystems that rely on RPC.

The registry keys and values described in this article do not appear in the registry by default; you must add them by using Registry Editor.

Important This section, method, or task contains steps that tell you how to modify the registry. However, serious problems might occur if you modify the registry incorrectly. Therefore, make sure that you follow these steps carefully. For added protection, back up the registry before you modify it. Then, you can restore the registry if a problem occurs. For more information about how to back up and restore the registry, click the following article number to view the article in the Microsoft Knowledge Base:

322756  ( ) How to back up and restore the registry in Windows

Follow these steps to control RPC dynamic port allocation. You will have to do this on both computers. Note also that the firewall mustbe open in both directions for the specified ports:

  1. To start Registry Editor, click Start, click Run, type regedt32, and then click OK.

    You must use Regedt32.exe, rather than Regedit.exe, because Regedit.exe does not support the REG_MULTI_SZ data type that is required for the Ports value.
  2. In Registry Editor, click HKEY_LOCAL_MACHINE in the Local Machine window.
  3. Expand the tree by double-clicking the folders named in the following path:
  4. Click the RPC folder, and then click Add Key on the Edit menu.
  5. In the Add Key dialog box, in the Key Name box, type Internet, and then click OK.
  6. Click the Internet folder, and then click Add Value on the Edit menu.
  7. In the Add Value dialog box, in the Value Name box, type Ports.
  8. In the Data Type box, select REG_MULTI_SZ, and then click OK.
  9. In the Multi-String Editor dialog box, in the Data box, specify the port or ports you want RPC to use for dynamic port allocation, and then click OK.

    Each string value you type specifies either a single port or an inclusive range of ports. For example, to open port 5000, specify "5000" without the quotation marks. To open ports 5000 to 5020 inclusive, specify "5000-5020" without the quotation marks. You can specify multiple ports or ports ranges by specifying one port or port range per line. All ports must be in the range of 1024 to 65535. If any port is outside this range or if any string is invalid, RPC will treat the entire configuration as invalid.

    Microsoft recommends that you open up ports from 5000 and up, and that you open a minimum of 15 to 20 ports.
  10. Follow steps 6 through 9 to add another key for Internet, by using the following values:
    Value: PortsInternetAvailable
    Data Type: REG_SZ
    Data: Y
    This signifies that the ports listed under the Ports value are to be made Internet-available.
  11. Follow steps 6 through 9 to add another key for Internet, by using the following values:
    Value: UseInternetPorts
    Data Type: REG_SZ
    Data: Y
    This signifies that RPC should dynamically assign ports from the list of Internet ports.
  12. Configure your firewall to allow incoming access to the specified dynamic ports and to port 135 (the RPC Endpoint Mapper port).
  13. Restart the computer. When RPC restarts, it will assign incoming ports dynamically, based on the registry values that you have specified. For example, to open ports 5000 through 5020 inclusive, create the following named values:
    Ports : REG_MULTI-SZ : 5000-5020
    PortsInternetAvailable : REG_SZ : Y
    UseInternetPorts : REG_SZ : Y

DTC also requires that you are able to resolve computer names by way of NetBIOS or DNS. You can test whether or not NetBIOS can resolve the names by using ping and the server name. The client computer must be able to resolve the name of the server, and the server must be be able to resolve the name of the client. If NetBIOS cannot resolve the names, you can add entries to the LMHOSTS files on the computers.

For more information, click the following article number to view the article in the Microsoft Knowledge Base:

217351  ( ) DCOM port range configuration problems

For more information about LMHOSTS files, click the following article number to view the article in the Microsoft Knowledge Base:

102725  ( ) LMHOSTS file information and predefined keywords

Tags: ,

ASP.Net | Windows Communication Foundation