Working with jQuery

I have now been working with jQuery for a while and found very good usage in using there specific features:

Together with MS Ajax:
Using jQuery together with MS ajax results in some $ naming conflicts, since both MS Ajax and jQuery used the $ use their default namaspace.
It can be resolved by either rename the jQuery namespace, by using . jQuery.noconflict() method or simply by using the jQuery namespace directly for all jQuery usage.

Context:
I will recommend to always specify context when doing jQuery’s.
When using jQuery from inside a MS Ajax usercontrol, it could be done e.g. specifying this.get_element() which is the controls main html element.
So getting an element within the current Ajax control could look like:
var jqElem = jQuery(”#elementid”, this.get_element());

To get, set and use attributes in jQuery could be done like this:
jQuery(”#elementid [myattr='myvalue']“, this.get_element()).attr(”title”, “myTooltip”);
removing it, doing this:
jQuery(”#elementid [myattr='myvalue']“, this.get_element()).attr(”title”);

….. more to come …..

Leave a Comment

Impressions from øredev part 1

Day 1
The conference were 5 days with the two first days set up as half day of full day training sesions. 

I attended a full day together with Juval Löwy being introduced to the basics in WCF.

Ok, and what is WCF?

WCF stands for Windows Communication Foundation and is Microsofts implementation of standards defining service interactions.

It provides interoperability, productivity and extensibility. All messages are usually SOAP messages and communications goes through a proxy.

Hosting of services are either selfhosted where the processing is made by the developer himself or by using Windows Activations Services. 

Every services has endpoint defined by an address, some defined binding and a contract. The address can be the url, tcp or other kind of address, binding is the the way of communicating and the contract is the actual interface definition.

As a WCF service you can benefit from all the services that the foundations provides by enabling these. Integration are done through interception with proxies.

 

Day 2:

The second day I took a half days training session with Stuart Halloway from Relevance, learning jQuery.

Jquery is a non-intrusive, non-obstructive standard open source javascript library. It has a lot of nice plugins available.

It is used by almost everyone these days and are to be included as a part of asp.net 4.0.

 Typical usage:

Find something and do something to it

Create something and do something to it

$==jQuery, to protect $ it´s possible to use the following pattern: 

	jQuery(function($) {
		// put jquery functions here
	})

Tip: For adhoc testing and trying your jQuery code, using the www.jsbin.com can be helpfull.

Leave a Comment

Compile and run userdefined c# code from within your app

Sometimes customers requires the ability to write small pieces of custom code that should be run from within your application. And not only that, you want to be able to get resulting variables from that user code, inside your application.
An example could be an advanced calculator, where some of the algorithms are defined by the user. Of course there could be a big security issue in letting users define code that are allowed to run within your application, but issues related to security is not discussed here.

Check this example:

First define an interface the describes the properties and methods that are accessable by the customers code:

namespace ScriptInterface {
    public interface ILiveScript {
        void Run();
        int Input { set;}
        int Output { get;}
    }
}

The interface should be defined in an assemble (here ScriptInterface.dll) seperated from the actual compiler, we come back to that later.

Then define the actual scriptcompiler class:

using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;
using Microsoft.CSharp;
using ScriptInterface;

namespace ScriptRunner {
    public class Calculator {

        internal static string scriptHeader =
            "using System;" +
            "using ScriptInterface;" +
            "namespace ScriptRunner {" +
                "class LiveScript : ILiveScript {" +
                    "private int input;" +
                    "private int output;" +
                    "public void Run() {";

        internal static string scriptFooter =
                    "}" +
                    "public int Input {" +
                        "set { input = value; }" +
                        "get { return input; }" +
                    "}" +
                    "public int Output {" +
                        "set { output = value; }" +
                        "get { return output; }" +
                    "}" +
                "}" +
            "}";

        public static ILiveScript ExecuteScript(string source) {
            string[] mergedSource = new string[] { scriptHeader + source + scriptFooter };
            CompilerResults results = CompileSource(mergedSource);
            if (!results.Errors.HasErrors) {
                return RunScript(results.CompiledAssembly);
            } else {
                throw new Exception(GenerateCompileErrorLines(results.Errors));
            }
        }

        private static string GenerateCompileErrorLines(CompilerErrorCollection errors) {
            StringBuilder sb = new StringBuilder();
            sb.Append("\r\n");
            foreach (CompilerError error in errors) {
                sb.Append(error.Line).Append(": ").Append(error.ErrorText).Append("\r\n");
            }
            return sb.ToString();
        }

        private static ILiveScript RunScript(Assembly compiledAssembly) {
            ILiveScript method = (ILiveScript)compiledAssembly.CreateInstance("ScriptRunner.LiveScript", true);
            method.Input = 7; // whatever, just an example
            try {
                method.Run();
                return method;
            } catch (Exception ex) {
                throw new Exception("Running of custom script failed.", ex);
            }
        }

        private static CompilerResults CompileSource(string[] source) {
            CodeDomProvider provider = new CSharpCodeProvider(); //or VBCodeProvider()
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("system.dll"); //includes
            cp.ReferencedAssemblies.Add("ScriptInterface.dll"); //includes our own interface!
            cp.GenerateExecutable = false; //generate executable
            return provider.CompileAssemblyFromSource(cp, source);
        }

    }
}

As you see the actual compiled usercode is a welldefined header and footer merged with the users own code. Since the merged code implements our interface, you can control which properties the usercode can access, and you can read resulting properties from that code.

So the actual usage of this, could look like this:

using System;
using ScriptInterface;
using ScriptRunner;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            ILiveScript method = Calculator.ExecuteScript("Output = Input * 2;"); // could come from args
            Console.Write("Result:" + method.Output);
        }
    }
}

Have fun with your own userenabled compiler application.

Leave a Comment

Updating an element on a form from a different thread

Sometimes its a good idea to spawn a new thread from the GUI, to do some heavy calculation or
other time consuming task, to avoid the GUI to freeze as the task is running.
When a thread has been spawned, it would often also be nice to recieve som kind of
feedback from the calculation, of progress and status.
It’s not possible for a thread that did not create the GUI to update it, therefore we have
to make a few tweaks to make progress information from the thread appear on the GUI.
Here is an example of how it could be done.

In the GUI (windows forms):

private delegate void DoRefreshProgressText(string info);
private Label progressText = new Label(); // could be e.g. a progressbar

CheckForIllegalCrossThreadCalls = false;
Calculator calculator = new Calculator();
calculator.reportInfo += new Calculator.ReportInfo(reportInfoToGUI);

void reportInfoToGUI(string infoString) {
    if (progressText.InvokeRequired) {
        DoRefreshProgressText d = new DoRefreshProgressText(reportInfoToGUI);
        Invoke(d, new object[] { infoString });
    } else {
        progressText.Text = infoString;
    }
}

In the spawned thread:

public class Calculator {
    public delegate void ReportInfo(string infoString);
    public event ReportInfo reportInfo;
    public void SomeMethodCalledByThread(string statusText) {
        if (reportInfo != null) {
            reportInfo(statusText);
        }
    }
}

Leave a Comment

Creating a instance of a type loaded from assembly

Sometimes classes are seperated i different assemblies and you need to load classes from a specific assembly. Here is a way to load a class and instanciate a variable of that type:

try {
System.Runtime.Remoting.ObjectHandle objHandle =
    System.Activator.CreateInstanceFrom(Application.StartupPath + @"\MyAssembly.exe", @"MyNameSpace." + @"MyClassName");
} catch(TypeLoadException) {
    // Problems loading class
}

if(objHandle != null) {
    MyClassName myObject = ((MyClassName) (objHandle.Unwrap()));
}

If you want to create an object instance of an object in the current assembly, simply use: System.Activator.CreateInstance() with the number of arguments needed for the types constructor.

Leave a Comment

How to determine if a type is a Nullable

Yesterday I had a problem determining whether a supplied type was of the type Nullable. Here is the solution:

Type mt = suppliedVar.GetType();

if(mt.IsGenericType && mt.GetGenericTypeDefinition() ==
   typeof(Nullable<>)) && mt.GetGenericArguments().Length>0)
  {
      if(mt.GetGenericArguments()[0].IsEnum) {
      // Type is a Nullable
   }
}

Leave a Comment

Crypting and decrypting sections in web.config

Sometimes you need to have sensitive information in your config files, information that you would like to hide from other people with access to the sourcefiles. That could be database credentials placed in the section, as in this example:


    
    
    
    

To encrypt the section use the aspnet_regiis tool provided as a part of the specific .net version. You find it in the \Windows\Microsoft.Net\Framework\v2.0.50727 directory, if you are running .net version 2.

aspnet_regiis -pe “appSettings” -app “/YourWebApp”

That will change the section in your web.config to look something like this:

    
  
   
   
    
     
     
      Rsa Key
     
     
      L9Q9ePobkZR +++ 
     
    
   
   
    Is42Ajvxkd1Ol1iILS +++ 
   
  
 
 

You can still use the standard ConfigurationSettings methods to read the values, without doing anything to your code. If you want to revert the encryption, simply use the aspnet_regiis tool with the -pd switch like this:

aspnet_regiis -pd “appSettings” -app “/YourWebApp”

Leave a Comment