Blog Archives

system.windows.resourcedictionary. source threw an exception wpf c#

In general this issue is caused when a referenced resource cannot be found.

<Application x:Class="AppName.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

In my specific circumstance, as the xaml above details, this issue was caused by a reference to PresentationFramework.Aero DLL that was not contained in the output bin folder of the compiled project. Under references, setting Copy Local to true did the trick for me.

References
http://stackoverflow.com/questions/3747972/wpf-usercontrol-cannot-find-xaml-resource-in-referencing-project

WPF Quick Reference

get window handle

IntPtr windowHandle = new WindowInteropHelper(this).Handle;

bring to front

myWindow.Activate();
myWindow.TopMost = true;

common resource dictionaries for skinning (this blog)

References
wpf get window handle (stackoverflow) http://stackoverflow.com/questions/1556182/finding-the-handle-to-a-wpf-window
wpf bring to front (stackoverflow) http://stackoverflow.com/questions/257587/bring-a-window-to-the-front-in-wpf

C# Application Not Responding Issue on Long Running Threads

Undoubtedly many of you have encountered the dreaded “Application Not Responding” message, programmers and non-programmers alike.

In general, this is caused by the OS misinterpretation of long delays in form refresh, even though these can easily be caused by a long running process, or any running process longer than a couple seconds actually.

If this is happening in your application after clicking on a button or event fires, a quick solution would be the easy one-liner below:

Application.DoEvents();

However, to really understand why this happening, remember that all processes (may) contain multiple threads.

In the case of your typical quick shot solution that you put together in VS in no-time, you’re likely only using a single thread.

This thread is used not only to run the processes in your application, but also to update the form window including drawing the fields and various controls on the form.

The best solution to this would really be to create a separate thread and pass off the work of your long running function to this thread.

When the work is finished, it will update our main thread (the form thread) that it has completed which we can intercept with a delegate, and notify the user of success or failure.

See snippet below.

private BackgroundWorker hardworker; //this guys works hard!
private System.Timers.Timer lazyworker; //notice how this could also be achieved with thread/timer

protected void btnDoAlotOfWork_Click() {
//lets see who accomplishes more!
ClockInLazyWorker();
ClockInHardWorker();
}

private void ClockInLazyWorker() {
lazyworker = new System.Timers.Timer(); //not to be confused with forms timer
lazyworker.Interval = 1000; //time in milliseconds. 10 seconds is lazy for a computer!
            lazyworker.Elapsed += new System.Timers.ElapsedEventHandler(LetsGetAMoveOnIt());
}

private void ClockInHardWorker() {
hardworker= new BackgroundWorker();
            mCopier.DoWork += DoWork; //all the heavy lifting is done here
            mCopier.RunWorkerCompleted += WorkCompleted();
            mCopier.WorkerSupportsCancellation = true;
            OnError += ProblemWithWork();
}

//motivational function name made especially for our lazy worker
private void LetsGetAMoveOnIt() {
//do something that takes a long time
//if the data you operate on is the same as used by another thread or the form thread, make sure you wrap this block in a synclock or use a bool to track when work is in process
}

//created separate function for the background worker, and also to avoid synclock issues since there are two new active threads
private void DoWork() {
//if the data you operate on is the same as used by another thread or the form thread, make sure you wrap this block in a synclock or use a bool to track when work is in process. same goes for timer.
}

private void WorkCompleted() {
//all finished
}

private void ProblemWithWork() {
//hopefully not an injury on the job! that's workmans comp!
}

Alot more code than simply “Application.DoEvents”.. but do not underestimate the power of multiple threads!

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

IIS Application Pool

A great many documents, blogs and references exist on IIS which cover it comprehensively. This article simply serves to discuss one aspect – the application pool.

When configuring IIS in an environment that will contain many websites, there are a few important considerations:

Will each site potentially run different versions of .NET? Sites with different frameworks should not share the same app pool. This will cause a conflict and they will not be functional.

Is it a large web application that requires many resources? If yes, you may also want to consider creating it’s own app pool, which allows you to manage detailed information regarding how the server prioritizes the site.

Recycling

The first tab for the app pool properties displays information regarding memory resource usage. If you have multiple sites on a server which are hit very often and would like to force the amount of memory each one uses, you can create an app pool for each and manage it here.

Or if it will be split evenly among various sites, you can create “groups” of app pools with assigned memory and IIS will allocate among children accordingly.

You can also force the worker process to automatically free up memory after specified interval and/or at different times of the day.

Recycling

Recycling

Performance
The performance tab allows for CPU resource management. Certain sites may have functions that, left unchecked or still under development, can cause excessive CPU load and affect other processes running on the same server.

Max CPU usage can be assigned here setup in conjunction with events to trigger when these scenarios occur.

A remote exploit or overflow attempt of your server can also be secured here by limiting the maximum number of kernel requests.

Idle timeout can help free up CPU for a site that is not very active. Legacy sites or informational areas which are rarely visited are still using a fraction of the CPU usage, and setting an idle timeout can help release some of those resources.

Performance

Performance

Health
The health tab can help you diagnose potential issues with your site or application. By forcing certain restrictions such as maximum failures and/or maximum failures within a specific time period, as well as enabling pinging, you can check for periods of down time or help identify timeout issues a specific web service may be experiencing.

This tab works well in conjunction with third party testing tools used to benchmark and stress test your site, application or service.

Health

Health

Identity
Depending on the size and nature of your infrastructure, you may want to configure certain application pools to run under different credentials. For highly security conscious people this can theoretically reduce the likelihood of certain privilege escalation techniques that may be executed in the event of a remote application pool exploit.

Identity

Identity

Hope the above information was helpful. This was a condensed version based on a similar article I read on Windows Networking. See reference below for full article.

References
WindowsNetworking, http://www.windowsnetworking.com/articles_tutorials/Working-Application-Pools-Internet-Information-Server.html

JQuery and Frames

Although there is definitely some room for debate in the web development and design community on where the usage of frames is necessary, there are some situations where they cannot be avoided.

Manipulation of data within these frames can be confusing, and dumping frames to page content using ajax or server side code is not always possible. This is especially true if these pages contain their own sub-site navigation.

In these scenarios, JQuery helps us simplify content management within frames using a combination of the “.contents()” method and “find” functionality to locate and update elements.

If “videoframe” is the id of the iframe, the example below changes the background color of a body inside the frame to a specific color.

JS (JQuery):


$('#videoframe').contents().find("body").css("background-color", "#FFFFFF");

References:
JQuery API, http://api.jquery.com/contents

JQuery AJAX Reference

Keep in mind when using code below if requesting a page that requires login/restricted access, users login session is not carried over.

Snippet below is sample code usage illustrating two different methods of achieving similar result. See references for more info and full specifications.

Javscript (JQuery):

$.ajax({
                            url: 'http://www.websitename.com/',
                            dataType: "text",
                            type: "POST",
                            data: { city: "NewYork"},
                            error: function(err) {
                                alert("Error:" + err.toString());
                            },
                            success: function(data) {
                                //$("#JQuery_modal_p").html(data);
                                alert(data);
                            }

                        });

Javscript (JQuery):

$.ajax({
                            url: 'http://www.websitename.com/' + data1+ data2,
                            dataType: "text",
                            type: "GET",
                            data: {},
                            error: function(err) {
                                alert("Error:" + err.toString());
                            },
                            success: function(data) {
                                //$("#JQuery_modal_p").html(data);
                                alert(data);
                            }

                        });

References:
JQuery Ajax, http://api.jquery.com/jQuery.ajax/

JQuery Is Not Defined

This is a common error for users implementing JQuery UI. Usually if you see this message, this could mean a few things:

– There is a syntax issue or bad link referencing the JQuery (min/full) JS. Use your debuggers to make sure the JS is loading.

– Similar to above this could also mean the JS cannot be loaded due to being contained in a folder which the site does not have permission to.

– If you are debugging locally and referencing the JQuery JS on an external site, make sure you have internet access and that the site which you are referencing to is up.

– The arrangement of script references may be in the wrong order. JS loads on runtime, so dependencies are important in placement of the script reference on the page. JQuery UI depends on JQuery(min), so (min) must be declared first or you will encounter the error.

As always, Firebug and other web development debuggers such as the one’s built into Chrome and IE are great tools to help you identify and resolve issues such as these.

Hope this may lighten someone’s day. 🙂

    <script src="../JQuery/js/jquery-1.4.4.min.js" type="text/javascript"></script>

    <link href="../JQuery/css/smoothness/jquery-ui-1.8.7.custom.css" rel="stylesheet"
        type="text/css" />

    <script src="../JQuery/js/jquery-ui-1.8.7.custom.min.js" type="text/javascript"></script>

References:
Firebug, http://getfirebug.com/
JQuery UI, http://jqueryui.com/

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.