Category Archives: ASP.NET

ASP.NET Web Server Here Context Option

open.asp

You can download here the updated registry entry for opening the ASP.NET Development Web Server using context menu in Explorer. The path has been updated to use Visual Studio 2015’s development web server.

This is used to quickly open a web server in a directory. After merging the registry, just do the following:

  1. Open explorer and navigate to the target directory
  2. Right click and select the ASP.NET Web Server Here option

I have not tested this in Windows 10.

Reference: http://haacked.com/archive/2009/10/27/aspnet4-webserver-here-shell-extension.aspx/

ASP.NET Webforms, WebMethod, JSON, and Jquery

Using JSON Serializers such as Newtonsoft’s JSON library is not needed in later versions of ASP.NET.

Instead, if you’re sending a JSON object via AJAX, the webforms framework will attempt to automatically deserialize the object into the type passed into the parameter and serialize the object when it is being returned to the page.

Example:

ASPX Page – Binding a button that submits a JSON Object

<script type="text/javascript">
   
    $(document).ready(function () {

        $('#<%=ButtonSubmit.ClientID%>').click(function () {
            var InputObj = {
                "InputObj": {
                    "IsAvailable": 0,
                    "Input": $('#<%=TextInput.ClientID%>').val()
                }
            }

            $.ajax({
                type: 'POST',
                url: '/Templates/UI/Views/MobileLocator.aspx/CheckZip',
                data: JSON.stringify(InputObj),
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                async: true,
                cache: false,
                success: function (obj) {
                    if (obj.d.IsAvailable === '1') {                       
                        $('#divyes').reveal();
                    }
                    else {
                        $('#divno').reveal();
                    }                    
                }

            });

            return false;
        });
    });
</script>

CodeBehind – Static WebMethod

        [WebMethod(BufferResponse=false)]
        public static FormInputObj CheckZip(FormInputObj InputObj)
        {            
                                                  
                if (InputObj != null && !string.IsNullOrEmpty(InputObj.Input))
                {
                    bool iIsAvailable = false;
                   
                    InputObj.IsAvailable = iIsAvailable ? "1" : "0";

                    return InputObj;
                }
            

            return new FormInputObj { IsAvailable = "0" };
        }

    [Serializable]
    public class FormInputObj
    {        
        public string Input { get; set; }        
        public string IsAvailable { get; set; }
    }

The only things to note are the following:

When serializing the object into JSON format using Jquery, make sure the parameter’s name is the parent object. Example:

var InputObj = {
                "InputObj": {
                    "IsAvailable": 0,
                    "Input": $('#<%=TextInput.ClientID%>').val()
                }
            }

The “InputObj” matches the parameter name in the codebehind. This is needed or else ASP.NET will return an error. You must also call

JSON.stringify(InputObj)

when creating the parameters for data key in the $.ajax method.

When reading the returned object in the Jquery success event, you must reference the ‘.d’ in the returned object before calling the property of the strongly typed object.

 if (obj.d.IsAvailable === '1')

Most Q&A topics on Stackoverflow regarding this are outdated. Ignore any articles circa 2013 or earlier regarding this topic.

Reference:

http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/

Razor Generator – Generated class name is different than file name

I’ve been using Razor Templates to generate text blobs. For some reason, my razor templates stopped generating namespaces based on the file path and added underscores into the class name. I did the following to fix this issue.

Add this to the top of the cshtml file:

GeneratePrettyNames: true
GenerateAbsolutePathLinePragmas: true

So the top of the file might look similar to this declaration:

@* Generator : Template TypeVisibility : Internal GeneratePrettyNames: true
    GenerateAbsolutePathLinePragmas: true *@

Reference:  Codeplex Link

C#, XML, XML Prefixes, and Signing XML Documents with Prefixes

For those tasked with integrating an API from a company that starts with an R and ends with a one. Here are some links that may prove useful:

Digitally Signing an XML Document and Verifying the Signature

Here’s a PDF of the article, in case it ever get’s taken down.

I didn’t use C# to create the XML document. Instead, I used a Razor template to generate the XML.

How did I sign an XML document with an XML prefix?

Reference this Stack Overflow thread. Check the answer submitted by George Dima. [Thank you George.]  Reference in case it ever gets taken down.

I didn’t realize that you can’t sign an XML document with a prefix in .NET using the objects provided as is. It took me awhile to figure out that this was causing a validation issue with the XML signature.

How do I Http Post in C#?

Reference the code here or just download it here.

There’s an easier way using the WebClient object, but if you can’t use the latest version of the .NET framework, the above will work fine in all cases.

 

 

ASP.NET Parts of Absolute Path

// Gets the base url in the following format: 
// "http(s)://domain(:port)/AppPath"
HttpContext.Current.Request.Url.Scheme+"://"
+HttpContext.Current.Request.Url.Authority
+HttpContext.Current.Request.ApplicationPath;

Source

.NET Framework: Re-registering key files for signing assemblies

After reinstalling Visual Studio and trying to resign an assembly with a key, I got the following error:

Cannot import the following key file: .pfx. The key file may be password protected. To correct this, try to import the certificate again or manually install the certificate to the Strong Name CSP with the following key container name:

To fix open the directory in the Visual Studio command prompt with the pfx file and run the following command:

 sn -i pfxfilename.pfx VS_KEY_EB611118B812345

You only have to run the command once for each unique key.

Source

Trouble Shooting MS DTC [Distributed Transaction Coordinator]

Making sure ASP.NET applications communicating with SQL Server via MS DTC can be a pain. To configure MS DTC, run the command ‘dcomcnfg’ from Start Menu => Run.

Other useful links:

In case those sites disappear, here are the PDF copies.

dtc.windows.2008 DTC_Windows_2003

Remember the NETBIOS names need to be reachable in order for MS DTC to work. To test, use the DTCPing tool. Which can be found here. This tests RPC connectivity between two machines.

You can also download the DTC tester tool, which makes an actual transaction via DTC. It can be found here: http://support.microsoft.com/kb/293799 . As noted above, to add a DSN to the system, go to System => Adminstration => ODBC.

ASP.NET: Modifying DetailsView Select and Updating Events

Recently I was tasked with encrypting/decrypting some data that could be edited using ASP.NET’s DetailsView control.  Along with the details view control, the legacy code used a SQL Data Source to select and update everything. This means the data access layer was bypassed completely, so any business logic that dealt with encryption on this page had to use a different execution path. So, how would you encrypt and decrypt data?

The problem could be divided into two tasks:

  1. Create a filter to decrypt data in any bound columns.
  2. Edit the DetailsView event, ItemUpdating and figure out which columns needed to be updated during the event.

The first task was the easier of the two, as it just involved referencing the encryption library from the code behind page and calling the function inline in the aspx page. So, the method in the code behind page would look like something like this:

protected string Decrypt(object input)
{
return EncryptionHelper.Decrypt(input.ToString());
}

While calling the decrypt function in the DetailsView child  Fields tags on the aspx page:

<asp:templatefield headertext="Decrypted Data" sortexpression="EncryptedData>
<edititemtemplate>
<asp:TextBox ID="TextBox1" runat="Server" Text='<%#Decrypt(Eval("EncryptedData"))%>' />
</edititemtemplate>
<itemtemplate>
<asp:label runat="server" text='<%# Decrypt(Eval("EncryptedData")) %>' id="Label1"></asp:label>
 </itemtemplate>
</asp:templatefield>

However, decrypting the data using a templatefield tag posed another problem, extracting new values from the ‘TextBox1’ control. This will be solved when calling the ItemUpdating event.

After setting the DetailsView’s ItemUpdating method, you will need to modify the SQL Data Source’s UpdateCommand, UpdateCommandType, and UpdateParameters. The legacy code in the SQL data source used a update statement with parameters. Normally the details view control automatically detects whether to pass a null in the parameter. Instead when  setting the UpdateParameters in the codebehind, the control will update the database with the parameter names entered. For example ‘@Parameter’, will be sent in the update to the record instead of null. To solve this, you would need to automatically detect whether a value is null and then add it to the UpdateParameters list. This was done using the ‘IsFieldNull’ method [shown below].

Initializing the SQL data source also had another problem – because certain data needed to be re-encrypted before being sent back to the database. You will need to single out any columns that need to be encrypted. On top of that, the table being updated had over 50 columns, so typing in 50+ lines just to initialize the parameters was required, but I decided to do something else instead.

The parameters being sent to the stored procedure were identically named to the column names. Using this protocol, I decided to simply grab all the field names, which were identical to the column names and add the ‘@’ character next during initialization. So, the method to get the column names looked like the following:

private List<string> GetColumnNameList()
{
List<string> Ret = new List<string>();

for (int i = 0; i < DetailsView.Rows.Count; i++)
{
if (!String.IsNullOrEmpty(DetailsView.Rows[i].Cells[0].Text))
{
Ret.Add(DetailsView.Rows[i].Cells[0].Text);
}
}
return Ret;
}

Initializing the update parameters looked like the following:

private void InitSqlDataSource()
{
SQLDataSource.UpdateCommand = "Update";
SQLDataSource.UpdateParameters.Clear();

List<string> paramList = GetColumnNameList();

foreach (string col in paramList)
{
if (!IsFieldNull(col))
{
if (col != "EncryptedData")
{
SQLDataSource.UpdateParameters.Add(col, "@" + col);
}
else
{
SQLDataSource.UpdateParameters.Add("EncrptedData",
EncryptionHeper.Encrypt(GetDecryptedValue()));
}
}
}
}

The method checks to make sure the data being sent isn’t blank or null by executing the ‘IsFieldNull’ method. This method uses the ‘ExtractValuesFromCell’ method to grab values from the DetailsView control. This method isn’t exactly well documented on MSDN, so it’s not obvious at first that the passed parameter, IOrderedDictionary dictionary, is being used as a referenced parameter, not as a copy. [another weird quirk about the .NET framework] The method, GetValues, used is identical to what is covered at the article written at David Fowler’s blog.

private bool IsFieldNull(string fieldName)
{
OrderedDictionary vals = GetValues(DetailsView) as OrderedDictionary;

if (vals[fieldName] == null)
{
return true;
}

return string.IsNullOrEmpty(vals[fieldName].ToString());
}

public IDictionary GetValues(DetailsView detailsView)
{
IOrderedDictionary values = new OrderedDictionary();

foreach (DetailsViewRow row in detailsView.Rows)
{
if (row.RowType != DataControlRowType.DataRow)
{
continue;
}

DataControlFieldCell dataCell = (DataControlFieldCell)row.Cells[0];

if (dataCell.ContainingField.ShowHeader)
{
dataCell = (DataControlFieldCell)row.Cells[1];
}

dataCell.ContainingField.ExtractValuesFromCell(values, dataCell, row.RowState, true);
}

return values;
}

ASP.NET and Retrieving Different Sections of the Current URL using Request.Url

While working on a project in ASP.NET, I needed a function that would retrieve the domain of the current url, however, I also wanted the function to also retrieve the correct ASP.NET development web server path when developing in Visual Studio. After consulting Google, I ran into this old post on Rick Strahl’s blog about the Request.Url object.

After some experimenting, I created a web page in ASP.NET 2.0 that showed what parts of the URL could be returned using different calls. Consult the following in the page load event.

    protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Request.Url.AbsolutePath= " + Request.Url.AbsoluteUri);
Response.Write("<br>");
Response.Write("Request.Url.AbsoluteUri= " + Request.Url.AbsoluteUri);
Response.Write("<br>");
Response.Write("Request.Url.GetLeftPart(UriPartial.Authority)= " + Request.Url.GetLeftPart(UriPartial.Authority));
Response.Write("<br>");
Response.Write("Request.Url.GetLeftPart(UriPartial.Path)= " + Request.Url.GetLeftPart(UriPartial.Path));
Response.Write("<br>");
Response.Write("Request.Url.GetLeftPart(UriPartial.Scheme)= " + Request.Url.GetLeftPart(UriPartial.Scheme));
Response.Write("<br>");
Response.Write("Request.RawUrl= " + Request.RawUrl);
Response.Write("<br>");
Response.Write("Request.Path= " + Request.Path);
Response.Write("<br>");
Response.Write("Request.ApplicationPath= " + Request.ApplicationPath);
Response.Write("<br>");
Response.Write("Request.ResolveUrl= " + ResolveUrl("~/dealer/default.aspx"));
Response.Write("<br>");
Response.Write("GetAuthorityApplicationPath= " + GetAuthorityApplicationPath());
}

private String GetAuthorityApplicationPath()
{
return String.Concat(Request.Url.GetLeftPart(UriPartial.Authority), Request.ApplicationPath);
}

The function GetAuthorityApplicationPath() is what I needed in the end to dynamically retrieve either the domain in a production environment or the development web server url while running Visual Studio (eg. ‘http://localhost:1234/WebDirectory’)