Saturday, May 27

ASP.NET Notes

Components of ASP.NET:


  1. Common Language Runtime (CLR)
  2. .NET Framework Class Library
  3. Common Language Specifications
  4. Common Type System
  5. Metadata and Assemblies
    1. Metadata is the binary information describing the program which is either stored in a PE file or in memory. Assembly is a logical unit consisting of the assembly manifest, type metadata, IL code, and resources such as images.
  6. Windows and Forms
  7. ASP.NET and ASP.NET AJAX
    1. AJAX allows page updates without reloading
  8. ADO.NET
    1. Access to databases and XML
  9. Windows Workflow Foundation (WF)
  10. Windows Presentation Foundation (WPF)
  11. Windows Communication Foundation (WCF)
  12. Windows Cardspace
  13. LINQ
ASP.NET Life Cycle specifies how:
  • ASP.NET processes pages to produce dynamic output
  • The application and its pages are instantiated and processed.
  • ASP.NET compiles the page dynamically
Life cycle can be divided into two groups:

  1. Application Life Cycle
  2. Page Life Cycle
Application Life Cycle
The application life cycle has the following states:
  • The user makes a request for accessing application resource, a page, Browser sends the request to the web server.
  • A unified pipeline receives the first request and the following events take place:
    • An object of class ApplicationManager is created.
    • An object of class HostingEnvironment is created.
    • Top level items in the application are compiled.
  • Response object are created:
    • HttpContext
    • HttpRequest
    • HttpResponse
  • An instance of HttpApplication is created and assigned to the request.
  • The request is processed by the application class. Events are parsed.
ASP.NET Page Life Cycle Phases:
  • Initialization
  • Instantiation
  • Restoration and maintenance of the state
  • Execution of the event handler codes
  • Page Rendering

Stages:

  • Page Request
  • Starting of the page lifecycle
  • Page initialization
  • Page load
  • Validation
  • Postback event handling
  • Page Rendering
  • Unload
Events:
  • PreInit - overload OnPreInit
  • Init - overload OnInit
  • InitComplete
  • Load ViewState
  • Load PostData
  • PreLoad - overload OnPreLoad
  • Load - overload OnLoad
  • LoadComplete - overload OnLoadComplete
  • PreRender
  • PreRender Complete
  • SaveState Complete - override Render
  • Unload

Friday, October 30

ld has unresolved functions in custom libraries

I ported some C code to a HPUX Itanium machine and built archive (.a) libraries with it. When I ran a makefile for test program it could not find any of the functions in the custom libraries although it could find them.

The solution is to put the object file (.o) before the libraries so the ld command has a list of functions to try and resolve in the libraries.

So instead of

ld -Llib -lcustom program.o

use

ld program.o -Llib -lcustom


Thursday, October 2

JQuery

I am reading "A Software Engineer Learns HTML5, JavaScript, and JQuery". The examples for using JQuery in Chrome under the Tools->Javascript Console did not work at first. It was a simple fix: Include a script at the top of the HTML file with

src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"

or something similar. This particular line reads the library from Google. It can also be downloaded from:

jquery.com/download

Thursday, September 4

HTML5 DOCTYPE

The DOCTYPE is an important signal to browsers and allows them to interpret the content of a document in the context of the rules associated with the doucment type. If this is omitted the browser will revert to its tradition rule set and the may produce very different results from one browser to another or even one version to another.

There is typically no version number attached to HTML in the DOCTYPE. There is also no Document Type Definition (DTD) defining the rules of the markup language. The reason for this is that HTML5 is not based on SGML like earlier version of HTML.

Although HTML5 is not based on any other standard, it is possible to write HTML5 in XML serialisation mode. The following would be the skeletion for a HTML5 page inat serializes to XML:



   






HTML documents that utilize XML mode should have a document type of application/xhtml+xml

Thursday, May 15

ExpectedException on an inner exception

How do I do this? I have a test with an expected exception, but the act is going through reflection. The code throws the exception, but reflection is changing the exception. Can I use ExpectedException on an inner exception?
[TestMethod]
[ExpectedException(typeof(System.IndexOutOfRangeException))]
public void TestTransformationNegative()
{
   // Arrange 
   int[] numbers = { 10 };
   var target = new LinqProjectionAccessor(new LinqProjection());

   // Act
   string[] numbersAsText = target.Transformation(numbers);
}
Test Name: TestTransformationNegative Test FullName: UnitTestLinq.TestLinqProjection.TestTransformationNegative Test Source: c:\Users\tjmadden\Source\Workspaces\Linq\UnitTestLinq\TestLinqProjection.cs : line 128 Test Outcome: Failed Test Duration: 0:00:00.0264312 Result Message: Test method UnitTestLinq.TestLinqProjection.TestTransformationNegative threw exception System.Reflection.TargetInvocationException, but exception System.IndexOutOfRangeException was expected. Exception message: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IndexOutOfRangeException: Index was outside the bounds of the array. Result StackTrace: at Linq.LinqProjection.<>c__DisplayClass5.b__4(Int32 n) in c:\Users\tjmadden\Source\Workspaces\Linq\Linq\LinqProjection.cs:line 147 at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext() at System.Linq.Buffer`1..ctor(IEnumerable`1 source) at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source) at Linq.LinqProjection.Transformation(Int32[] numbers) in c:\Users\tjmadden\Source\Workspaces\Linq\Linq\LinqProjection.cs:line 149 --- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) at UnitTestLinq.Accessors.AccessorReflection.RunMethod(Type objectType, String methodName, Object objectInstance, Object[] objectParameters) in c:\Users\tjmadden\Source\Workspaces\Linq\UnitTestLinq\Accessors\AccessorReflection.cs:line 51 at UnitTestLinq.Accessors.AccessorBase`1.RunMethod(String methodName, Object[] parameters) in c:\Users\tjmadden\Source\Workspaces\Linq\UnitTestLinq\Accessors\AccessorBase.cs:line 35 at UnitTestLinq.Accessors.LinqProjectionAccessor.Transformation(Int32[] numbers) in c:\Users\tjmadden\Source\Workspaces\Linq\UnitTestLinq\Accessors\LinqProjectionAccessors.cs:line 54 at UnitTestLinq.TestLinqProjection.TestTransformationNegative() in c:\Users\tjmadden\Source\Workspaces\Linq\UnitTestLinq\TestLinqProjection.cs:line 134

Wednesday, May 7

Getting StyleCop to ignore temporary files.

I use StyleCop. I like it. With Visual Studio 2013, though, I found a few problems. Number 1 is that Express does not have extensions, so you must add the StyleCop extension to the project manually.

<import project="$(MSBuildToolsPath)\Microsoft.CSharp.targets"/>
<import project="$(ProgramFiles)\MSBuild\StyleCop\v4.7\StyleCop.targets"/>

StyleCop also complains the temporary files that Visual Studio generates do not have headers. There are a few ways to have it ignore these, but I found adding this to the project file works well in the Express version of Visual Studio.
<itemgroup>
  <excludefromstylecop include="$(IntermediateOutputPath)\**\*.cs">
  </excludefromstylecop>
</itemgroup>

Saturday, November 23

Testing private methods via reflection


You are not supposed to test the private methods of a class, but it is occasionally useful. Microsoft used to have a private accessor type but has since deprecated it. This is the way I came up with: Put a pulic wrapper around the methods, and use reflection to call them. Not original, but it works ok.

The reflection class has one main method: RunMethod. I added (ok, started with) a ListMethod as a helper.


namespace UnitTests.Accessors
{
    using System;
    using System.Reflection;

    /// <summary>
    /// Accessor helper, uses reflection to call private methods of a class
    /// </summary>
    class AccessorReflection
    {
        /// <summary>
        /// The BindingFlags flags used to access the class methods
        /// BindingFlags.NonPublic will not return any results by itself. 
        /// As it turns out, combining it with BindingFlags.Instance does the trick.
        /// </summary>
        private const BindingFlags accessFlags =
            BindingFlags.Instance | BindingFlags.Public |
            BindingFlags.NonPublic | BindingFlags.Static;

        /// <summary>
        /// Runs the method of the class type.
        /// </summary>
        /// <param name="objectType">The class type.</param>
        /// <param name="methodName">The method to run as a string.</param>
        /// <param name="objectInstance">The object instance.</param>
        /// <param name="objectParameters">The object method parameters.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">There is no method ' +
        ///                      strMethod + ' for type ' + t.ToString() + '.</exception>
        public static object RunMethod(Type objectType, string methodName,
            object objectInstance, object[] objectParameters)
        {
            if (String.IsNullOrEmpty(methodName))
            {
                throw new
                    ArgumentException("Cannot invoke null or empty method for type " + objectType.ToString() + "'.");
            }
            MethodInfo m = objectType.GetMethod(methodName, AccessorReflection.accessFlags);
            if (m == null)
            {
                // Method does not exist
                throw new ArgumentException("There is no method '" +
                    methodName + "' for type '" + objectType.ToString() + "'.");
            }

            return m.Invoke(objectInstance, objectParameters);
        }

        /// <summary>
        /// Lists the methods of the type. Pretty much for debugging
        /// </summary>
        /// <param name="t">The class type.</param>
        public void ListMethods(Type t)
        {
            Console.WriteLine("***** Methods *****");
            MethodInfo[] methodInfo = t.GetMethods(AccessorReflection.accessFlags);
            // sort methods by name
            Array.Sort(methodInfo,
                    delegate(MethodInfo methodInfo1, MethodInfo methodInfo2)
                    { return methodInfo1.Name.CompareTo(methodInfo2.Name); });
            foreach (MethodInfo methodEntry in methodInfo)
            {
                // Get return type.
                string retVal = methodEntry.ReturnType.FullName;
                string paramInfo = "( ";

                // Get params.
                foreach (ParameterInfo parameterInfo in methodEntry.GetParameters())
                {
                    paramInfo += string.Format("{0} {1} ", parameterInfo.ParameterType, parameterInfo.Name);
                }
                paramInfo += " )";

                // Now display the basic method sig.
                Console.WriteLine("->{0} {1} {2}", retVal, methodEntry.Name, paramInfo);
            }
            Console.WriteLine();
        }

    }
}


I also added a base abstract class to call it:

namespace UnitTests.Accessors
{
    using System;

    ///
    /// Base class to access private methods for testing.
    ///
    /// Object under test
    class AccessorBase
    {
        ///
        /// Holds the reference to the object under test
        ///
        private T objectInstance;
       
        public AccessorBase(T objectInstance)
        {
            this.objectInstance = objectInstance;
        }

        ///
        /// Executes the private method of the instance
        ///
        /// Method to execute as a string
        /// Parameters for the method
        /// The result of the method execution
        public object RunMethod(string methodName, Object[] parameters)
        {
            return AccessorReflection.RunMethod(objectInstance.GetType(), methodName, this.objectInstance, parameters);
        }
    }
}

So now write an accessor class with the public wrappers. My example is dumb but it gets the point across.

class Mine
{
    private int count;

    public Mine(int count)
    {
        this.count = count;
    }

    public void publicMethodNoArgs()
    {
        this.privateMethodNoArgs();
    }

    private void privateMethodNoArgs()
    {
        int joy = 1;
        for (int x = 1; x < 5; x++)
        {
            joy += x;
        }
    }

    private void privateMethodIntArg(int joy)
    {
        Console.WriteLine("Joy before is {0}", joy);
        for (int x = 1; x < 5; x++)
        {
            joy += x;
        }

        Console.WriteLine("Joy is now {0}", joy);
    }

    private int privateMethodStringArg(string name)
    {
        int result = 1;
        return result;
    }
}


The accessor class looks like:

class Mine_Accessor : AccessorBase<Mine_Accessor>
{
    public Mine_Accessor(Mine mineInstance): base(mineInstance)
    {
    }

    public void privateMethodIntArg(int joy)
    {
        Object[] parms = {joy};

        base.RunMethod("privateMethodIntArg", parameters);
    }
}
I like to make the public wrapper look like the private method in names and parameters. If there is a return type other than void, add a return and cast the result.