Blog Archives

URL Encode in .Net

C#: (ASP .Net)

System.Web.HttpUtility.UrlEncode()

C#: (Client/Server Environment)

Uri.EscapeUriString()

References
MSDN, WebUtility Classhttp://msdn.microsoft.com/en-us/library/system.net.webutility.aspx
MSDN, Uri Classhttp://msdn.microsoft.com/en-us/library/system.uri.escapeuristring.aspx
MSDN blogs, http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx

JQuery Grid Themes

Useful links to JQuery grids utilizing (mostly) standard UI themes and/or very little code.

Google!
http://jquery-ui.googlecode.com/svn/branches/labs/grid/tests/static/grid/default.html

Datatables.Net:
http://www.datatables.net/styling/themes/smoothness

Ke-Cai:
http://www.ke-cai.net/2010/01/theme-your-table-with-jquery-ui.html

Trirand:
http://www.trirand.com/blog/jqgrid/jqgrid.html

Stackoverflow:
http://stackoverflow.com/questions/2613632/jquery-ui-themes-and-html-tables

JQuery and Partial Postbacks

I recently came across an issue where JQuery bindings no longer functioned after a partial postback and stumbled upon some code that was helpful in most cases.

Javascript (JQuery):

Sys.Application.add_load(startJQuery); 

startJQuery() { 
//do JQ here
}

And alternatively..

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(){});

This code will not always work however, as was the case in my particular scenario, so I resolved using an alternate method.

RegisterStartupScript is great functionality, and can be useful for loading javascript dynamically on an as-needed basis.

The example below, based on prior code selects the correct JS file to use, then loads it using the registerstartupscript function. This is all within a code block which calls an update panel

C#:


int scriptnumber = 1;
string FilePath = String.Format("~/Scripts/Script_{0}.js",scriptnumber.ToString());
System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(FilePath));
            jqueryfileoutput = sr.ReadToEnd();

            upnlBodyContent.Update();

            ScriptManager.RegisterStartupScript(this, this.GetType(), "scriptname",
                "<script type=\"text/javascript\">" + jqueryfileoutput.ToString().Trim() + "</script>", false);

Get IP Address of Originating Website From a Webservice

The following code was used in a .Net 3.5 web service to retrieve the IP Address of the website consuming it.

This solution may initially escape you since it might seem like the web service should run within an HTTP Context and thus utilize this object to get information from websites calling particular methods.

See MSDN reference(s) for more information.

C#:

RemoteEndpointMessageProperty clientEndpoint = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; 

clientEndpoint.Address 

References:
MSDN, http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.remoteendpointmessageproperty.aspx

Programmatically fire an event handler in ASP .NET

I recently came across a situation which any web application developer may face where an assembly reference containing the code-behind for each ASPX page was deprecated and the original source code was no longer available.

Since this code also includes event handlers, any functions that need to be intercepted or their logic modified are now inaccessible.

In many cases these event-handling functions are also declared protected, so simply calling them from the ASPX side is not possible.

To circumvent this, one of my personal favorite .NET libraries can be used to get the method using reflections and call it manually. See examples in VB and C# below.

Enjoy. ;)

VB .NET

    Private Sub btnLogin2_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnLogin2.Click
        
'ADD NEW LOGIC HERE
        
        Dim targetObject As Object = btnLogin
        
        Dim methodName As String = "OnClick"
        
        Dim mInfo As System.Reflection.MethodInfo = targetObject.GetType().GetMethod(methodName, System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.NonPublic)
        
        If mInfo Is Nothing Then
            Throw New ArgumentException("Error finding event handler:  " & methodName)
        End If
        
        mInfo.Invoke(targetObject, New Object() {e})
    End Sub

C#

private void btnLogin2_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{

//ADD NEW LOGIC HERE

	object targetObject = btnLogin;

	string methodName = "OnClick";

	System.Reflection.MethodInfo mInfo = targetObject.GetType().GetMethod(methodName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

	if (mInfo == null) {
		throw new ArgumentException("Error finding event handler:  " + methodName);
	}

	mInfo.Invoke(targetObject, new object[] { e });
}

It is generally not good security practice IMO to write code in the ASPX side of a web application. This solution will work however as a quick patch to an application in which the code-behind is not accessible and the site is not accessible by outside parties via (S)FTP.

If security is of concern, another solution which is the better option overall, would be to declare a new class for which this page would inherit from. In this class you could then define a public property which exposes the protected function to be called by other methods, and/or simply write your new functions and logic in here.

If the page is a partial class (as most ASP.NET web applications are structured), this is also possible without inheritance by declaring a new partial class which shares the same type as your page you need to modify. New logic can be added here and/or protected members can be exposed via public properties.

If either inheritance/OO approach is taken, upon deployment or build of the project, your new class will be compiled into a new assembly and now achieve desired functionality while maintaining security of the application as well.

Follow

Get every new post delivered to your Inbox.