Quantcast
Channel: Development With A Dot
Viewing all 404 articles
Browse latest View live

Java vs C# – Part 1

$
0
0

Disclaimer: long post!

Introduction

While some of my friends and colleagues seem to think that I don’t like Java and that I am some sort of Microsoft/.NET zealot, that is actually not true! Smile with tongue out I do like Java, and I worked with it for several years.

There are several articles out there on the differences and similarities between C# and Java, but none actually satisfied me. In this new series of posts, I will try to explain these similarities and differences, as extensively and accurately as I can. I don’t want to start a religious war, but I won’t refrain from emitting judgments on what I think is best in each. I will try to cover as much as I can, but I won’t drill into APIs, instead will focus on each language’s intrinsic characteristics.

This first post will focus on high-level constructs, what I call structure: namespaces and types. I will be covering Java 8 and C# 5, the latest (as of February 2015) versions of these languages.

Similarities

Both languages (Java and C#) are case-sensitive, strictly object oriented, offering classes, enumerations and interfaces, single inheritance model and all of the types live in namespaces/packages. Also, all support attributes/annotations, methods and fields, including static ones. The base class for all types, in both cases, is called Object. Both have the same basic operators, comparable base types and exception handling mechanisms. Both start executing by a static method called main/Main.

Compiled Units

A Java class compiles to an identically-named class file; these files exist on their own, but are usually stored together inside a jar, war or ear, which are basically ZIP files with a manifest file attached to, for better manageability. These files, of course, can contain other resources, such as images or text files.

C# classes always exist in binary assemblies, which can have two basic forms (extensions):

  • dll: a library, does not run on its own;
  • exe: a stand-alone executable, which can either be a Console or a Windows Forms / Windows Presentation Foundation graphical application.

Assemblies can also include metadata and embedded resources, of any type. C#/.NET actually defines another compilation unit, the module, but typically a module matches an assembly, although it is possible to have it other way, for more advanced scenarios.

Namespaces

Both in Java and in C# we have the notion of namespaces or packages, which can be nested. In C#, the namespace declaration must wrap all of its types, and therefore we can have several namespace declarations in a source file, even nested:

namespace MyNamespace1
{
publicclass Class1
    {
    }
}
 
namespace MyNamespace2
{
publicclass Class2
    {
    }
 
namespace MyNamespace3
    {
publicclass Class3
        {
        }
    }
}

In Java, the package declaration goes on the top of a source file, meaning, it can only contain a single package:

package myPackage;
 
publicclass MyClass
{
}

There is one important difference between Java and C#: in Java, the namespace must be identical to the physical folder structure, that is, a class belonging to the a.b package must be physically located in an a\b folder; Java won’t compile it otherwise. The generated .class file must be located in the same folder, such as a\b\MyClass.class.

Java and C# can simplify accessing classes in other namespaces/packages by importing these, like we see here for Java, where we can import all types (*), or a type at a time:

//import java.lang.*;    automatically imported
import java.io.*;
import java.lang.reflect.Array;

Java imports automatically the types in the java.lang package, C# does not automatically import any namespace, and it doesn’t allow importing a single type:

using System;
using System.IO;

But it also lets us define type aliases per source file using the same syntax:

using date = System.DateTime;
 
publicclass MyClass
{
public date GetCurrentDate()
    {
//...
    }
}

Top Level Elements (Types)

Java and C# offer a very close syntax, in some cases, if we discount the different language conventions, it’s really hard to tell one from the other, but there are some important differences.

Java offers the following top level elements, besides packages:

  • Classes (including generic);
  • Interfaces (including generic);
  • Enumerations.

And C# the same plus some more:

  • Classes (including generic);
  • Interfaces (including generic);
  • Enumerations;
  • Structures;
  • Delegates (including generic).

Basic Types

The basic types in the two languages (C#/Java) are:

  • Object/Object (C# shorthand: object);
  • String/String (C# shorthand: string);
  • Byte/byte (C# shorthand: byte);
  • SByte/N/A (C# shorthand: sbyte);
  • Boolean/boolean (C# shorthand: bool);
  • Char/char (C# shorthand: char);
  • Int16/short (C# shorthand: short);
  • UInt16/N/A (C# shorthand: uint);
  • Int32/int (C# shorthand: int);
  • UInt32/N/A (C# shorthand: uint);
  • Int64/long (C# shorthand: long);
  • UInt64/N/A (C# shorthand: ulong);
  • Single/float (C# shorthand: float);
  • Double/double (C# shorthand: double);
  • Decimal/N/A (C# shorthand: decimal);
  • dynamic/N/A;
  • Arrays.

As you can see, C# offers unsigned and signed versions of all integer types and also a high-precision Decimal type. It also as a dynamic type, used for late-binding (runtime) operations without strong compile-time checks.

C# offers three kinds of arrays:

  • Single dimension: int [] numbers;
  • Multi dimension: int [,] matrix;
  • Arrays of arrays, also called, jagged arrays: int [][] matrix;

Java also has single dimension and jagged arrays, but no multi dimension ones.

C# lets us use the var keyword for declaring a variable and automatically initializing it. This is a shorthand for the initialization’s type:

var i = 10;            //int
var s = "string";      //string
var f = SomeMethod();  //method's return type, except void

In C# as in Java, we can specify suffixes for clarifying the desired type of a literal:

  • 10n: integer;
  • 10l: long;
  • 10f: float;
  • 10d: double;
  • 10u: unsigned int (C# only);
  • 10ul: unsigned long (C# only);
  • 10m: decimal (C# only).

Both lowercase or uppercase letters are allowed as the suffix.

Classes

Classes in Java and C# are allocated in the heap. A class can inherit from a single base class, if not specified, it will inherit from Object. It can implement any number of interfaces.

Structures

C# has a unified type system, meaning, primitive types (integers, floating points, booleans, etc) coexist in the same type hierarchy as composite classes. This is different in Java, where, for example, the int and Integer types are not related, even if it is possible to convert between the two. All primitive types in C# are structures, not classes, which means they are allocated in the stack instead of the heap. In Java this also occurs for primitive types, but there is no notion of explicit structures, and we can’t build our own types to be stored in the stack. A structure in C# cannot inherit from any class explicitly, but it can implement any number of interfaces, and also cannot declare a destructor/finalizer:

publicstruct MyStructure : IMyInterface
{
publicvoid MyMethod()
    {
    }
}

Structures and enumerations in C# are called value types and classes and interfaces are called reference types. Because of C#’s unified type system, a structure always implicitly inherits from System.ValueType.

Interfaces

In C#, an interface can only have:

  • Instance method declarations;
  • Instance property declarations;
  • Instance event declarations.

It can be generic or non-generic. Both classes and structures can implement interfaces. An interface can always be assigned null, it is a reference type.

In Java, things are a bit different, since they can have also have statics and (the horror!), method implementations:

  • Instance method declarations;
  • Fields (always implicitly static) with a value (constants);
  • Default methods: methods with default implementations.

They can also be generic or otherwise, and can be implemented by enumerations.

Generic Types

Generics are quite different, internally, in Java and C#. Both languages support generic classes and interfaces, but in C# they are a first-class construct, with reflection support, but in Java they cease to exist once a generic class is compiled. That is, in Java, a List<String>, at runtime, becomes just List, the generic parameter String is erased, this is in order to ensure backward compatibility with prior Java versions that didn’t have generics. This doesn’t happen in C#, and we can at runtime reflect on a generic class and its parameters.

Both languages support any number of generic parameters and constraints on them. In C# these constraints are:

  • Base class, structure or interface: forces the generic parameter to inherit or implement from a specific class, structure or interface;
  • Public non-abstract class with a public parameterless constructor: only allows generic parameters that are non-abstract (or interfaces) and have a public constructor that doesn’t take parameters;
  • Reference or value type: a generic parameter either has to be a reference (class or interface) or a value type (structure or enumeration), as specified.

An example:

publicclass GenericClassWithReferenceParameter<T> where T : class
{
}
 
publicclass GenericClassWithValueParameter<T> where T : struct
{
}
 
publicclass GenericClassWithMyClassParameter<T> where T : MyClass
{
}
 
publicclass GenericClassWithPublicParameterlessParameter<T> where T : new()
{
}
 
publicclass GenericClassWithRelatedParameters<K, V> where K : V
{
}
 
publicclass GenericClassWithManyConstraints<T> where T : IDisposable where T : new() where T : class
{
}

Java accepts the following constraints:

  • Base class: a generic parameter must inherit from a base class;
  • Implementing interface: a generic parameter must implement some interface;
  • Unbounded generic type: a generic parameter must inherit/implement some generic type.

Some examples:

publicclass GenericClassWithBaseClassParameter<T extends BaseClass>
{
}
 
publicclass GenericClassWithInterfaceParameter<T extends Interface>
{
}
 
publicclass GenericClassWithBaseMatchingParameter<T, ? super T>
{
}
 
publicclass GenericClassWithManyInterfaceParameters<T implements BaseInterface1 & BaseInterface2>
{
}
 

In Java, we can specify a generic of an unknown type:

MyInterface<?> var;

Java also has some terrible limitations:

  • There cannot be generics of primitive types, for example, MyGenericClass<int>, only of non-primitives, like MyGenericClass<Integer>;
  • There cannot be generic arrays.

Because C# supports any kinds of generic parameters, if we want to initialize explicitly some variable of a generic parameter type, we need to use the default keyword:

publicclass MyGenericClass<T>
{
publicvoid MyMethod()
    {
        T someField = default(T);
    }
}

Finally, the base class of some class inheriting from a generic type is not that generic type, but its base class, which can seem awkward. This happens in C# and in Java.

Delegates

A delegate in C# is a method signature, composed of:

  • A name;
  • A return type;
  • Parameters (number and type).

Delegates are the building blocks of events. A delegate can either point to a static, an instance or an anonymous method (lambda), provided the signature is the same:

publicdelegatedouble Operation(double v1, double v2);
 
//a delegate pointing to a static method
Operation addition = Operations.Add;
 
//a delegate pointing to an instance method
Operation subtraction = this.Subtract
 
//a delegate pointing to an anonymous method using lambdas
Operation subtraction = (a, b) =>
{
return a + b;
};

A delegate can be generic:

publicdelegatevoid Action<T>(T item);

Delegates inherit automatically from System.Delegate.

Java has no analogous construct.

Enumerations

Enumerations in Java can have members (constructors, fields and methods) and even implement interfaces, something that is not possible in C#:

publicenum MyEnumeration implements MyInterface
{
    A_VALUE(1),
    ANOTHER_VALUE(2);
 
privateint value;
 
private MyEnumeration(int value)
    {
this.value = value;
    }
 
publicstatic String fromInt(int value)
    {
if (value == A_VALUE.value) return ("A_VALUE");
elsereturn ("ANOTHER_VALUE");
    }
}

In C#, no methods or interfaces, but we can have an enumeration be implemented based on a primitive integer type, including unsigned (the default is signed int):

publicenum MyEnumeration : uint
{
    AValue = 1,
    AnotherValue = 2
}

Implicitly, all C# enumerations inherit from System.Enum.

In both cases, C# and Java, we can specify integral values for each enumeration member, and, if we don’t, members will get sequential values.

Type Visibilities

A type in Java has four possible visibilities:

  • package: only accessible by other classes in the same package (the default);
  • public: accessible by everyone.

And C# types have similar ones, plus one:

  • internal: only accessible by other classes in the same assembly (the default);
  • public: accessible by everyone.

Inheritance

In C#, the syntax for extending a class and for implementing an interface is exactly the same:

publicclass MyClass : BaseClass, IInterface
{
}

Whereas in Java there are the extends and the implements keywords, respectively, for classes and interfaces:

publicclass MyClass extends BaseClass implements Interface
{
}
 
publicinterface DerivedInterface extends BaseInterface1, BaseInterface2
{
}

Both can inherit from a single class and implement as many interfaces as desired. Also, an interface can itself inherit from several interfaces.

In C# it is possible to implement interfaces in one of two ways:

  • implicit: where the interface’s members are directly accessed through the implementing class;
  • explicit: where we have to cast the class to the explicitly implemented interface before we can use it; this is useful, among other reasons, if we want to implement several interfaces which offer identically-named members.

Let’s see how they look in C#, in this example, interface IMyInterface1 is explicitly and IMyInterface2 implicitly implemented:

publicclass MyClass : IMyInterface1, IMyInterface2
{
void IMyInterface1.MyMethod1()
    {
    }
 
publicvoid MyMethod2()
    {
    }
}

Explicitly-implemented members are always private and cannot be virtual or abstract. If we want to call a method or access a property of an explicitly implemented interface, we need to cast the instance first:

MyClass c = new MyClass();
IMyInterface1 i = (IMyInterface1) c;
i.MyMethod();

Java only has implicit interface implementations:

publicclass MyClass implements MyInterface
{
publicvoid myMethod()
    {
    }
}

Inner Classes

In Java as in C#, we can have multiple levels of nested/inner classes, structures and interfaces, but in Java they can be static or instance:

publicclass MyClass
{
publicstaticclass MyStaticInnerClass
    {
    }
 
publicclass MyInnerClass
    {
    }
}

Instance inner classes can only be instantiated when we have an instance of its containing class (do notice the awful syntax):

MyClass.MyStaticInnerClass c1 = new MyClass.MyStaticInnerClass();
 
MyClass c2 = new MyClass();
 
MyClass.MyInnerClass c3 = c2.new MyInnerClass();

In C#, any inner class can be instantiated, with or without an instance of the containing class, provided its visibility level is respected:

publicclass MyClass
{
publicclass MyInnerClass
    {
    }
}
 
MyClass.MyInnerClass c = new MyClass.MyInnerClass();

For C# the following visibility levels exist:

  • internal: only accessible by other classes in the same assembly (the default);
  • protected: only accessible by descending classes;
  • protected internal: derived classes or classes from the same assembly;
  • private: only accessible by the declaring class;
  • public: accessible by everyone.

Whereas for Java:

  • package: only accessible by other classes in the same package (the default);
  • protected: only accessible by descending classes;
  • private: only accessible by the declaring class;
  • public: accessible by everyone.

Abstract Classes

In Java as in C# we have abstract classes, and the syntax is exactly the same:

publicabstractclass MyClass
{
publicabstractvoid myMethod();
}

C# structures cannot be abstract.

Sealed Classes

Both frameworks allow a class to be marked as sealed/final, meaning, it cannot be inherited from:

publicsealedclass MyClass
{
//a C# sealed class
}
publicfinalclass MyClass
{
//a Java final class
}

C# structures are always implicitly sealed.

Static Classes

In C# we can have static classes, which are roughly equivalent to being at the same time abstract and sealed. Static classes only allow static members (properties, methods, fields and events):

publicstaticclass MyClass
{
publicstaticvoid MyMethod()
    {
    }
 
publicstaticstring MyField;
 
publicstaticint MyProperty { get; set; }
 
publicstaticevent EventHandler MyEvent;
}

Java does not have the concept of static classes.

Nullable Types

Because it is allocated in the stack, a variable of a structure or enumeration type always has a value, so, it cannot be null, but we can use a handy syntax to turn it into a nullable type, which can itself be made null:

int ? nullableInteger = null;
nullableInteger = 1;
 
if (nullableInteger.HasValue)    //if (nullableInteger != null)
{
int integer = nullableInteger.Value;    //int integer = nullableInteger
}

In Java, primitive values can never be null, we need to resort to their corresponding wrapper classes:

Integer nullableInteger = null;
nullableInteger = new Integer(1);

Classes and interfaces in C# (reference types) are always nullable, meaning, can always be assigned null.

Partial Classes

C# allows marking a class as partial, meaning, its contents may spread through several different source files; the actual compile-time class will be built from all of these files. This is very useful when we have automatically generated files that we don’t want to change, but rather complement:

//in file MyClass.Generated.cs
publicpartialclass MyClass
{
publicvoid OneMethod()
    {
    }
}
 
//in file MyClass.cs
publicpartialclass MyClass
{
publicvoid AnotherMethod()
    {
    }
}

Anonymous Classes

Java has anonymous classes: we can create anonymous classes that implement some interface or extend some class, by implementing all of its abstract methods:

this.addEventListener(new ListenerInterface
{
publicvoid onEvent(Object source, Event arg)
    {
    }
});

Anonymous classes in C# do not contain explicitly defined methods, only read-only properties; two anonymous classes are considered of the same type if their members are declared in the same order and with the same types:

var i1 = new { A = 10, B = "" };
var i2 = new { A = 1000, B = "string" };
 
//these two classes have the same type
i1 = i2;

In order to support anonymous classes, C# introduced the var keyword, which allows us to have a variable infer its type automatically. An anonymous type is created when a variable is created without a static type.

Type Members

In .NET we have the following type members:

  • Constructors (static and instance);
  • Destructors;
  • Methods (static and instance);
  • Fields (static and instance);
  • Properties (static and instance);
  • Events (static and instance);
  • Overridden operators and type conversions (discussed on the next post).

Java only has:

  • Constructors (static and instance);
  • Constructor blocks;
  • Destructors;
  • Methods (static and instance);
  • Fields (static and instance).

Static Constructors

Static constructors or class initializers are basically the same in C# and Java, but have a slightly different syntax, here is the Java one:

publicclass MyClass
{
static
    {
//do something the first time the class is used
    }
}

And the C# syntax:

publicclass MyClass
{
static MyClass()
    {
//do something the first time the class is used
    }
}

Java offers another weird thing: constructor blocks. You can have any number of them, and their code will be included automatically into all of the class’ constructors:

publicclass MyClass
{
    {
        System.out.println("First constructor block, called before constructor");
    }
 
public MyClass()
    {
        System.out.println("MyClass()");
    }
 
    {
        System.out.println("Second constructor block, called before constructor but after first constructor block");
    }    
}

Destructors

In C# a destructor, or finalizer, is just a shorthand syntax to the Finalize method. This method is called by the Garbage Collector when an instance is about to be freed. Java has an identical method, called finalize, which serves a similar purpose. Strictly speaking, none of these methods is actually a destructor, but they are sometimes called that.

In C#, we can use the C++ syntax instead of overriding Finalize:

publicclass MyClass
{
    ~MyClass()
    {
//object is being freed
    }
}

Static Members

Unlike C#, Java allows referencing static members through an instance variable, for example:

publicclass MyClass
{
publicstaticvoid doSomething()
    {
    }
}
 
MyClass c = new MyClass();
c.doSomething();

Properties

Properties are a useful C# construct, which allows a cleaner syntax to changing fields:

publicclass MyClass
{
publicint MyProperty { get; set; }
}
 
MyClass c = new MyClass();
c.MyProperty++;

We can have auto-implemented properties (such as in this example) or properties with an explicit backing field:

publicclass MyClass
{
privateint myField;
 
publicint MyProperty
    {
        get
        {
returnthis.myField;
        }
        set
        {
this.myField = value;
        }
    }
}

The Java equivalent can only be achieved with methods:

publicclass MyClass
{
privateint myProperty;
 
publicvoid setMyProperty(int value) { this.myProperty = value; }
publicint getMyProperty() { returnthis.myProperty; }
}
 
MyClass c = new MyClass();
c.setMyProperty(c.getMyProperty() + 1);

In C# we can also define indexed properties for classes, interfaces and structures, like in this example using an integer index:

publicclass MyCollection
{
private Object [] list = new Object[100];
 
public Object this[int index]
    {
        get
        {
returnthis.list[index];
        }
        set
        {
this.list[index] = value;
        }
    }
}

We are not limited to integer indexes, any type can be used as the key to an indexed property.

Finally, properties can have different visibility levels for the getter and setter methods, and can even have just one of them (usually just a setter does not make much sense):

publicint InternalProperty
{
    get;
private set;
}
 
publicstring GetOnlyProperty
{
    get
    {
returnthis.InternalProperty.ToString();
    }
}

Events

Events are C#’s implementation of the Publisher/Subscriber and Observer Patterns: it allows to register methods that will be called when the event is raised, and offers a simple syntax for registering, unregistering and clearing event handlers. An event handler is just an instance of a delegate, the delegate is the event’s signature:

publicclass MyClass
{
publicevent EventHandler MyEvent;
 
publicvoid ClearEventHandlers()
    {
//check for registered event handlers
if (this.MyEvent != null)
        {
//raise event
this.MyEvent(this, EventArgs.Empty);
 
//clear event handlers
this.MyEvent = null;
        }
    }
}
 
MyClass a = new MyClass();
 
//register event handler
c.MyEvent += OnMyEvent;
 
//unregister event handler
c.MyEvent -= OnMyEvent;

Like with properties, it is also possible in C# to implement the event add and remove methods explicitly, so as to add our own behavior:

publicclass MyClass
{
private EventHandler myEvent;
 
publicevent EventHandler MyEvent
    {
        add
        {
this.myEvent += value;
        }
        remove
        {
this.myEvent -= value;
        }
    }
}

Automatic Initialization of Fields and Properties

All fields declared in a class are initialized to their type’s default value (0 for integers and floating point number, false for booleans, null for classes). C#’s auto-implemented properties are also implicitly initialized to their type’s default value. This behavior is the same in both languages, of course, Java does not have properties.

Member Visibilities

C# has four visibility levels for members:

  • private: accessible from the declaring type;
  • internal: accessible from types in the same assembly as the declaring type;
  • protected: accessible from types inheriting from the declaring type;
  • protected internal: accessible from types either inheriting from the declaring type or from its same assembly;
  • public: accessible by everyone.

And Java, we only have:

  • package: only accessible by classes in the same package;
  • protected: only accessible by descending classes;
  • private: only accessible by the declaring class;
  • public: accessible by everyone.

Virtual Members

In Java, all methods are virtual by default (there is no virtual keyword), unless marked as final.

In C#, a method, property or event needs to be explicitly marked as virtual so that it can be overridden, and all overrides must state so:

publicclass MyBaseClass
{
publicvirtualvoid MyMethod()
    {
    }
}
 
publicclass MyDerivedClass : MyBaseClass
{
publicoverridevoid MyMethod()
    {
    }
}

If a derived class member with the same name as one in the base class exists, but it is not an override of it, we need to mark it as new:

publicclass MyBaseClass
{
publicvoid MyMethod()
    {
    }
}
 
publicclass MyDerivedClass : MyBaseClass
{
publicnewvoid MyMethod()
    {
//no relation with MyBaseClass.MyMethod
    }
}

Sealed Members

In C# as in Java, it is possible to mark a member (method) as sealed/final, meaning, it is not available for overriding in a derived class. In C# the same applies to events and properties, which, of course, don’t exist in Java.

C# syntax:

publicclass MyClass
{
publicsealedvoid DoSomething()
    {
    }
}

And Java syntax:

publicclass MyClass
{
publicfinalvoid doSomething()
    {
    }
}

Abstract Members

In both languages, abstract members (methods) can exist in abstract classes, but they are not required: we can have abstract classes without any abstract members. In C#, besides methods, we can also have abstract properties and events.

Generic Methods

Methods can also be generic, regardless of living in generic classes or not. The same constraints apply, but generic methods also have automatic type inference:

publicclass MyClass
{
publicstaticint Compare<T>(T v1, T v2)
    {
if (v1 == v2)
        {
return 0;
        }
 
return -1;
    }
}
 
//no need to specify the int parameter type
int areEqual = MyClass.Compare(1, 2);

Read-only and Constant Fields

Both Java and C# have read-only fields, but C# uses the readonly keyword:

publicstaticclass Singleton
{
//a C# readonly field
publicstaticreadonly Singleton Instance = new Singleton();
}

And Java uses final:

publicclass Singleton
{
//a Java final field
publicstaticfinal Singleton INSTANCE = new Singleton();
}

C# also offers another kind of read-only field, constants. A constant is always static and can only be of one of the primitive types, or an enumerated value:

publicstaticclass Maths
{
//a C# constant field
publicconstdouble PI = 3.1415;
}

The difference between readonly and const is that the C# compiler inlines all constants, that is, it actually replaces any references to it by their concrete values. The Java compiler does something similar for static final fields. Read-only fields can be initialized inline, together with the field declaration, or in constructors (static or instance).

Technical Review

I couldn’t have written this post without the technical review by my friend and colleague Roberto Cortez (@radcortez), of Java fame. Thanks, Roberto! Winking smile

Next Steps

That’s it for now. Stay tuned for the next post, where I will talk about other language differences. Let me hear from you!


ASP.NET Web Forms Extensibility: Control Builders

$
0
0

One of the most often ignored extensibility point in Web Forms is the Control Builder. Control Builders are subclasses of ControlBuilder (or other more specialized, such as FileLevelPageControlBuilder, for pages, or FileLevelMasterPageControlBuilder, for master pages) that can be specified per class. It controls some aspects of a control instance:

It also allows overriding a couple of things:

  • The parameters specified in the markup (Init);
  • What to do when the control builder is added to a parent control builder (OnAppendToParentBuilder);
  • Modify the code that will be generated in the code-behind class that is produced by ASP.NET or the code that will be used to instantiate the control (ProcessGeneratedCode);
  • Change the tag’s inner textual content (SetTagInnerText);
  • Etc.

This is a powerful mechanism, which has even been used to allow generic control classes. We apply a control builder through a ControlBuilderAttribute (for regular controls) or FileLevelControlBuilderAttribute for pages, master pages or user controls.

I won’t go into many details, but instead I will focus on the Init and ProcessGeneratedCode methods.

Init let’s us do things such as:

publicoverridevoid Init(TemplateParser parser, ControlBuilder parentBuilder, Type type, String tagName, String id, IDictionary attribs)
{
if (type == typeof(SomeBaseControl)
    {
//replace the control's type for another one
        type = typeof(SomeDerivedControl);
 
//convert an hypothetical Text property value to upper case
        attribs["Text"] = (attribs["Text"] as String).ToUpper();
    }
 
base.Init(parser, parentBuilder, type, tagName, id, attribs);
}

And ProcessGeneratedCode, messing with the generated page class:

publicoverridevoid ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod)
{
//add some interface to the generated page class
    derivedType.BaseTypes.Add(typeof(ISomeInterface));
 
//add a property implementation to the generated page class
    var prop = new CodeMemberProperty();
    prop.Attributes = MemberAttributes.Public;
    prop.Name = "SomeProperty";
    prop.Type = new CodeTypeReference(typeof(String));    
    prop.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Hello, World, from a generated property!")));
    derivedType.Members.Add(prop);
 
base.ProcessGeneratedCode(codeCompileUnit, baseType, derivedType, buildMethod, dataBindingMethod);
}

But also something MUCH more fun! Imagine you are using an IoC container – I will use Unity, but you can use whatever you want. We might have something like this in Application_Start (or whatever method spawned from it);

var unity = new UnityContainer();
unity.RegisterInstance<MyControl>(new MyControl { Text = "Bla bla" });
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(unity));

Notice I am using the Common Service Locator to abstract the IoC container and to make the code independent of it. Here, I am assigning a static instance to the MyControl type, in essence, a singleton.

Now, we can change our control builder so as to have the control build method return this instance:

publicoverridevoid ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod)
{
//return ServiceLocator.Current.GetInstance(typeof(MyControl));
    var type = Type.GetType((buildMethod.Statements[0] as CodeVariableDeclarationStatement).Type.BaseType);
    var currentProperty = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof (ServiceLocator)), "Current");
    var getInstance = new CodeMethodInvokeExpression(currentProperty, "GetInstance", new CodeTypeOfExpression(type));
    var @cast = new CodeCastExpression(type, getInstance);
    var @return = new CodeMethodReturnStatement(@cast);
 
    buildMethod.Statements.Clear();
    buildMethod.Statements.Add(@return);
 
base.ProcessGeneratedCode(codeCompileUnit, baseType, derivedType, buildMethod, dataBindingMethod);
}

In case you didn’t notice, what this does is, every time the MyControl control is instantiated in a page, for every request, ASP.NET will always return the same instance!

Now, I am not saying that you SHOULD do this, but only that you CAN do this! Winking smile

Take care out there…

ASP.NET Web Forms Extensibility: Control Builder Interceptors

$
0
0

After my previous post on Control Builders, what could possibly come next? Of course, Control Builder Interceptors! Not much documentation on this one, which is a shame, because it is an even more powerful feature that was recently introduced in ASP.NET 4.5.

A Control Builder Interceptor inherits from, unsurprisingly, ControlBuilderInterceptor. This is configured for the whole application, in the Web.config file, in the compilation section, by a controlBuilderInterceptorType (sorry, no link, since the ASP.NET 4.5 documentation is not online) attribute:

<compilationtargetFramework="4.5"controlBuilderInterceptorType="MyNamespace.MyControlBuilderInterceptor, MyAssembly"/>

Similarly to Control Builders, a Control Builder Interceptor allows us to:

Granted, less than Control Builders, but the point here is that this is fired for all markup-declared controls, not just those that have a specific Control Builder applied to. With that in mind, we can write code like this:

publicclass MyControlBuilderInterceptor : ControlBuilderInterceptor
{
//raised for every control on markup
publicstaticevent Action<ControlInterceptedEventArgs> ControlIntercepted;
 
publicoverridevoid OnProcessGeneratedCode(ControlBuilder controlBuilder, CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod, IDictionary additionalState)
    {
        var controlDeclaration = buildMethod.Statements[0] as CodeVariableDeclarationStatement;
 
if (controlDeclaration != null)
        {
            var controlName = controlDeclaration.Name;
 
            buildMethod.Statements.Insert(buildMethod.Statements.Count - 1, new CodeSnippetStatement(String.Concat(this.GetType().FullName, ".Intercept(@", controlName, ");")));
        }
 
base.OnProcessGeneratedCode(controlBuilder, codeCompileUnit, baseType, derivedType, buildMethod, dataBindingMethod, additionalState);
    }
 
publicoverridevoid PreControlBuilderInit(ControlBuilder controlBuilder, TemplateParser parser, ControlBuilder parentBuilder, Type type, String tagName, String id, IDictionary attributes, IDictionary additionalState)
    {
if ((attributes != null) && (attributes.Contains("Text") == true))
        {
//make property value uppercase
            attributes["Text"] = (attributes["Text"] as String).ToUpper();
        }
 
base.PreControlBuilderInit(controlBuilder, parser, parentBuilder, type, tagName, id, attributes, additionalState);
    }
 
publicstaticvoid Intercept(Control instance)
    {
        var handler = ControlIntercepted;
 
if (handler != null)
        {
            handler(new ControlInterceptedEventArgs(instance));
        }
    }
}

And there you have it. By adding an event handler to MyControlBuilderInterceptor.ControlIntercepted, we can analyze and change the properties of every control:

[Serializable]
publicsealedclass ControlInterceptedEventArgs : EventArgs
{
public ControlInterceptedEventArgs(Control control)
    {
this.Control = control;
    }
 
public Control Control { get; private set; }
}
 
MyControlBuilderInterceptor.ControlIntercepted += e =>
{
    var myControl = e.Control as MyControl;
if (myControl != null)
    {
        myControl.Text = myControl.Text.ToUpper();
    }
};

Stay tuned for more extensibility points of your favorite framework!

Freetext Extension in Entity Framework Code First

$
0
0

I posted before a solution for adding custom SQL functions to Entity Framework Code First as extension methods. This time I am going to show how we can do something similar for the FREETEXT function of SQL Server. Please note that this example will only work if you have the Fulltext Search component installed and your table is indexed.

OK, so we want to have an extension method like this:

[DbFunction("CodeFirstDatabaseSchema", "FREETEXT")]
publicstatic Boolean Freetext(this String column, String value)
{
return column.Contains(value);
}

In order for Entity Framework to recognize it, we need to write our own convention, this is because Entity Framework only recognizes out of the box a number of SQL Server built-in functions. We can write one as this:

publicclass FreetextConvention : IStoreModelConvention<EdmModel>
{
publicstaticreadonly FreetextConvention Instance = new FreetextConvention();
 
publicvoid Apply(EdmModel item, DbModel model)
    {
        var valueParameter = FunctionParameter.Create("column", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
        var formatParameter = FunctionParameter.Create("value", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
        var returnValue = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Boolean), ParameterMode.ReturnValue);
 
        var function = this.CreateAndAddFunction(item, "FREETEXT", new[] { valueParameter, formatParameter }, new[] { returnValue });
    }
 
protected EdmFunction CreateAndAddFunction(EdmModel item, String name, IList<FunctionParameter> parameters, IList<FunctionParameter> returnValues)
    {
        var payload = new EdmFunctionPayload { StoreFunctionName = name, Parameters = parameters, ReturnParameters = returnValues, Schema = this.GetDefaultSchema(item), IsBuiltIn = true };
        var function = EdmFunction.Create(name, this.GetDefaultNamespace(item), item.DataSpace, payload, null);
 
        item.AddItem(function);
 
return (function);
    }
 
protected EdmType GetStorePrimitiveType(DbModel model, PrimitiveTypeKind typeKind)
    {
return (model.ProviderManifest.GetStoreType(TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(typeKind))).EdmType);
    }
 
protected String GetDefaultNamespace(EdmModel layerModel)
    {
return (layerModel.GlobalItems.OfType<EdmType>().Select(t => t.NamespaceName).Distinct().Single());
    }
 
protected String GetDefaultSchema(EdmModel layerModel)
    {
return (layerModel.Container.EntitySets.Select(s => s.Schema).Distinct().SingleOrDefault());
    }
}

This registers a FREETEXT function with two string parameters and returning a boolean. All is fine, we add it to the DbContext in OnModelCreating:

modelBuilder.Conventions.Add(FreetextConvention.Instance);

You might have noticed the usage of a Instance static field, this is because, since the FreetextConvention class is stateless, there’s no point in creating many of them, we can just use the same instance.

Now, if we issue a LINQ query as:

var customers = ctx.Customers.Where(x => x.Name.Freetext("ricardo")).ToList();

It will fail miserably, complaining about this SQL fragment:

WHERE ((FREETEXT(name, N'ricardo') = 1)

The “= 1” part is here because the function is prototyped as boolean, which maps to SQL Server’s BIT data type, and the value for true is 1. Apparently, SQL Server does not support comparisons of some functions with 1; but if we run it as:

WHERE ((FREETEXT(name, N'ricardo') = 1)

without the explicit comparison, it works perfectly. So, all we have to do is get rid of “= 1”. Fortunately, Entity Framework, as of version 6, offers some very nice extensibility points. There are at least two ways by which we can achieve this:

  • By intercepting the command tree;
  • By intercepting the raw SQL.

Here we will use option #2 and leave command trees for another post.

We need to identity something with a format of “FREETEXT(something) = 1”. We can do it using a regular expression, and the interception of the SQL command can be achieved by implementing IDbCommandInterceptor (no reference documentation yet, but I have reported it and it will soon be fixed, hopefully) and registering one such instance in the DbInterception (same) static class. An IDbCommandInterceptor implementation might look like this:

publicclass FreetextInterceptor : IDbCommandInterceptor
{
publicstatic readonly FreetextInterceptor Instance = new FreetextInterceptor();
 
    private static readonly Regex FreetextRegex = new Regex(@"FREETEXT\(([^)]+\))\) = 1");
 
public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<Int32> interceptionContext)
    {
    }
 
public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<Int32> interceptionContext)
    {
    }
 
public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
    }
 
public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        var matches = FreetextRegex.Matches(command.CommandText);
 
if (matches.Count> 0)
        {
            command.CommandText = FreetextRegex.Replace(command.CommandText, "FREETEXT($1)");
        }
    }
 
public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<Object> interceptionContext)
    {
    }
 
public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<Object> interceptionContext)
    {
    }
}

You can see that the only method we’re interested in is ReaderExecuting (again, no documentation available), with is the one that will be called just before a SQL SELECT query is sent to the database. In here we analyze the CommandText property of the DbCommand and get rid of the “= 1” clause, using a regular expression. Finally, we need to register the interceptor before we issue the query, maybe in the static constructor of our DbContext:

DbInterception.Add(FreetextInterceptor.Instance);

And now we can finally execute our query:

var customers = ctx.Customers.Where(x => x.Name.Freetext("ricardo")).ToList();

And that’s it. Don’t forget that in order for this to work, you need to enable Full Text Search.

Entity Framework Extensibility Index

$
0
0

Hosting HTTP Resources

$
0
0

Introduction

How do I host thee? Let me count the ways!

You may not have realized that .NET offers a lot of alternatives when it comes to hosting an HTTP server, that is, without resorting to IIS, IIS Express or the now gone Visual Studio Web Development Server (aka, Cassini, rest in peace); by that, I either mean:

  • Opening up a TCP port and listening for HTTP requests, or a subset of them;
  • Running ASP.NET pages without a server.

In this post I am going through some of them. Some are specific to web services, but since they understand REST, I think they qualify as well as generic HTTP hosting mechanisms.

.NET HttpListener

Let’s start with HttpListener. This is included in .NET since version 2 and offers a decent server for static contents, that is, it cannot run any dynamic contents, like ASP.NET handlers, nor does it know anything about them. You merely point it to a physical folder on your file system, and it will happily serve any contents located inside it. Let’s see an example:

using (var listener = new System.Net.HttpListener())
{
    var url = "http://*:2000/";
    listener.Prefixes.Add(url);
    listener.Start();
 
    var ctx = listener.GetContext();
 
    var message = "Hello, World!";
 
    ctx.Response.StatusCode = (Int32) HttpStatusCode.OK;
    ctx.Response.ContentType = "text/plain";
    ctx.Response.ContentLength64 = message.Length;
 
using (var writer = new StreamWriter(ctx.Response.OutputStream))
    {
        writer.Write(message);
    }
 
    Console.ReadLine();
}
This is a very basic example that just listens on port 2000, for any host name and request, and just returns Hello, World! when contacted before shutting down.

ASP.NET ApplicationHost

Complementary to HttpListener, we have a way to execute ASP.NET handlers (ASPX pages, ASHX generic handlers and ASMX web services) in a self-hosted application domain. For that, we use the ApplicationHost class to create the ASP.NET application domain, and a regular .NET class for the server implementation. An example:

publicclass Host : MarshalByRefObject
{
publicvoid ProcessPage(String page, String query, TextWriter writer)
    {
        var worker = new SimpleWorkerRequest(page, query, writer);
        HttpRuntime.ProcessRequest(worker);
    }
}
 
//strip out bin\debug, so as to find the base path where web files are located
var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).Replace(@"\bin\Debug", String.Empty);
 
//we need to copy the assembly to the base path
File.Copy(Assembly.GetExecutingAssembly().Location, Path.Combine(path, "bin", Assembly.GetExecutingAssembly().CodeBase.Split('/').Last()), true);
 
var host = System.Web.Hosting.ApplicationHost.CreateApplicationHost(typeof(Host), "/", path) as Host;
host.ProcessPage("Default.aspx", null);

Notice the File.Copy call; this is necessary because the assembly referenced by the Default.aspx page needs to be located in the same folder as the page. An alternative to this would be to add a post build-event to the Visual Studio project:

image

I leave as an exercise to the interested readers how we can combine this with HttpListener! Winking smile

OWIN WebApp

Moving on to more recent technologies, we now have OWIN. In case you’ve been living in another world and haven’t heard of OWIN, I’ll just say that it is a standard for decoupling .NET from any particular web servers, like IIS or IIS Express. It also happens to have a self-hosting implementation – which, by the way, uses HttpListener underneath.

We need to add a reference to the Microsoft.Owin.SelfHostNuGet package:

image

After that, we just register an instance of WebApp with the default parameters, add an handler, and we’re done:

class Program
{
publicstaticvoid Configuration(IAppBuilder app)
    {
        app.Use(new Func<AppFunc, AppFunc>(next => (async ctx =>
        {
using (var writer = new StreamWriter(ctx["owin.ResponseBody"] as Stream))
            {
                await writer.WriteAsync("Hello, World!");
            }
        })));
    }
 
staticvoid Main(String[] args)
    {
using (WebApp.Start<Program>("http://*:2000"))
        {
            Console.ReadLine();
        }
    }
}

Again, no fancy dynamic stuff, just plain and simple HTTP: it waits for a request and just returns Hello, World!. It is possible to run ASP.NET MVC on top of OWIN, that is the goal of project Helios, which is currently in alpha stage. Do check out the Helios NuGet package at https://www.nuget.org/packages/Microsoft.Owin.Host.IIS/1.0.0-alpha1:

image

WCF ServiceHost

Since its release, WCF offers a way for it to be self-hosted in a .NET process. The class responsible for that is ServiceHost, or one of its descendants, like WebServiceHost, more suitable for REST. I will show an example using REST, which can be easily tested using a web browser:

[ServiceContract]
publicinterface IRest
{
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    String Index();
}
 
publicclass Rest : IRest
{
public String Index()
    {
return"Hello, World!";
    }
}
 
using (var host = new WebServiceHost(typeof(Rest)))
{
    var url = new Uri(@"http://localhost:2000");
    var binding = new WebHttpBinding();
 
    host.AddServiceEndpoint(typeof(IRest), binding, url);
    host.Open();
 
    Console.ReadLine();
}

This example listens for a request of /Index on port 2000 and upon receiving it, returns Hello, World! in JSON format – because we are only sending a string, it will be wrapped in . WCF REST out of the box only supports returning data in XML or JSON format, no Text or HTML, but, to be fair, that’s not what it was meant to. Should be possible to return HTML, but, honestly, it would probably mean more work than it's worth.

Web API HttpServer

Another web services technology in the .NET stack is Web API. Web API uses a concept similar to MVC, with controllers, models and action methods, but no views. It can be self-hosted as well, using the HttpServer class. In order to use it, install the Microsoft.AspNet.WebApi.SelfHost NuGet package. You will notice that its description claims that it is legacy, and has been replaced for another based on OWIN, yet, it is fully functional, if you don’t required it to be OWIN-compliant:

image

Because of the Web API architecture, we need to implement a controller for handling requests, :

publicclass DummyController : ApiController
{
    [HttpGet]
public IHttpActionResult Index()
    {
returnthis.Content(HttpStatusCode.OK, "Hello, World!");
    }
}

In this example, we do not take any parameters and just return the usual response.

Here’s the infrastructure code:

var url = "http://localhost:2000";
var config = new HttpSelfHostConfiguration(url);
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}");
 
using (var server = new HttpSelfHostServer(config))
{
    server.OpenAsync().Wait();
}

The DummyController is found by reflecting the current executing assembly and applying conventions; any HTTP requests for /api/Dummy/Index will land there and the outcome will be plain text.

IIS Hostable Web Core

Now, this one is tricky. IIS, from version 7, allows hosting its core engine in-process, that is, from inside another application; this is called IIS Hostable Web Core (HWC). We can supply our own Web.config and ApplicationHost.config files and specify a root folder from which IIS will serve our web resources, including any dynamic contents that IIS can serve (ASPX pages, ASHX handlers, ASMX and WCF web services, etc). Yes, I know, this contradicts my introduction, where I claimed that this post would be about hosting web resources without IIS... still, I think this is important to know, because it can be fully controlled through code.

You need to make sure HWC is installed... one option is using PowerShell's Install-WindowsFeature cmdlet:

Or the Server Manager application:

 

Features page

 

Because HWC is controlled through an unmanaged DLL, we have to import its public API control functions and call it with .NET code. Here's an example:

publicclass Host : IDisposable
{
privatestaticreadonly String FrameworkDirectory = RuntimeEnvironment.GetRuntimeDirectory();
privatestaticreadonly String RootWebConfigPath = Environment.ExpandEnvironmentVariables(Path.Combine(FrameworkDirectory, @"Config\Web.config"));
 
public Host(String physicalPath, Int32 port)
    {
this.ApplicationHostConfigurationPath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName() + ".config");
this.PhysicalPath = physicalPath;
this.Port = port;
 
        var applicationHostConfigurationContent = File.ReadAllText("ApplicationHost.config");
        var text = String.Format(applicationHostConfigurationContent, this.PhysicalPath, this.Port);
 
        File.WriteAllText(this.ApplicationHostConfigurationPath, text);
    }
 
    ~Host()
    {
this.Dispose(false);
    }
 
public String ApplicationHostConfigurationPath
    {
        get;
private set;
    }
 
public Int32 Port
    {
        get;
private set;
    }
 
public String PhysicalPath
    {
        get;
private set;
    }
 
publicvoid Dispose()
    {
this.Dispose(true);
        GC.SuppressFinalize(this);
    }
 
protectedvirtualvoid Dispose(Boolean disposing)
    {
this.Stop();
    }
 
publicvoid Start()
    {
if (IisHostableWebCoreEngine.IsActivated == false)
        {
            IisHostableWebCoreEngine.Activate(this.ApplicationHostConfigurationPath, RootWebConfigPath, Guid.NewGuid().ToString());
        }
    }
 
publicvoid Stop()
    {
if (IisHostableWebCoreEngine.IsActivated == true)
        {
            IisHostableWebCoreEngine.Shutdown(false);
 
this.PhysicalPath = String.Empty;
this.Port = 0;
 
            File.Delete(this.ApplicationHostConfigurationPath);
 
this.ApplicationHostConfigurationPath = String.Empty;
        }
    }
 
privatestaticclass IisHostableWebCoreEngine
    {
privatedelegate Int32 FnWebCoreActivate([In, MarshalAs(UnmanagedType.LPWStr)] String appHostConfig, [In, MarshalAs(UnmanagedType.LPWStr)] String rootWebConfig, [In, MarshalAs(UnmanagedType.LPWStr)] String instanceName);
privatedelegate Int32 FnWebCoreShutdown(Boolean immediate);
 
privateconst String HostableWebCorePath = @"%WinDir%\System32\InetSrv\HWebCore.dll";
privatestaticreadonly IntPtr HostableWebCoreLibrary = LoadLibrary(Environment.ExpandEnvironmentVariables(HostableWebCorePath));
 
privatestaticreadonly IntPtr WebCoreActivateAddress = GetProcAddress(HostableWebCoreLibrary, "WebCoreActivate");
privatestaticreadonly FnWebCoreActivate WebCoreActivate = Marshal.GetDelegateForFunctionPointer(WebCoreActivateAddress, typeof(FnWebCoreActivate)) as FnWebCoreActivate;
 
privatestaticreadonly IntPtr WebCoreShutdownAddress = GetProcAddress(HostableWebCoreLibrary, "WebCoreShutdown");
privatestaticreadonly FnWebCoreShutdown WebCoreShutdown = Marshal.GetDelegateForFunctionPointer(WebCoreShutdownAddress, typeof(FnWebCoreShutdown)) as FnWebCoreShutdown;
 
internalstatic Boolean IsActivated
        {
            get;
private set;
        }
 
internalstaticvoid Activate(String appHostConfig, String rootWebConfig, String instanceName)
        {
            var result = WebCoreActivate(appHostConfig, rootWebConfig, instanceName);
 
if (result != 0)
            {
                Marshal.ThrowExceptionForHR(result);
            }
 
            IsActivated = true;
        }
 
internalstaticvoid Shutdown(Boolean immediate)
        {
if (IsActivated == true)
            {
                WebCoreShutdown(immediate);
                IsActivated = false;
            }
        }
 
        [DllImport("Kernel32.dll")]
privatestaticextern IntPtr LoadLibrary(String dllname);
 
        [DllImport("Kernel32.dll")]
privatestaticextern IntPtr GetProcAddress(IntPtr hModule, String procname);
    }
}

In order for this to work, we need to have an ApplicationHost.config file, a minimum working example being:

<?xmlversion="1.0"encoding="UTF-8" ?>
<configuration>
<configSections>
<sectionGroupname="system.applicationHost">
<sectionname="applicationPools"/>
<sectionname="sites"/>
</sectionGroup>
 
<sectionGroupname="system.webServer">
<sectionname="globalModules"/>
<sectionname="modules"/>
<sectionname="handlers"/>
<sectionname="staticContent"/>
<sectionname="serverRuntime"/>
<sectionGroupname="security">
<sectionname="access"/>
<sectionGroupname="authentication">
<sectionname="anonymousAuthentication"/>
<sectionname="windowsAuthentication"/>
<sectionname="basicAuthentication"/>
</sectionGroup>
<sectionname="authorization"/>
<sectionname="requestFiltering"/>
<sectionname="applicationDependencies"/>
<sectionname="ipSecurity"/>
</sectionGroup>
<sectionname="asp"/>
<sectionname="caching"/>
<sectionname="cgi"/>
<sectionname="defaultDocument"/>
<sectionname="directoryBrowse"/>
<sectionname="httpErrors"/>
<sectionname="httpLogging"/>
<sectionname="httpProtocol"/>
<sectionname="httpRedirect"/>
<sectionname="httpTracing"/>
<sectionname="isapiFilters"allowDefinition="MachineToApplication"/>
<sectionname="odbcLogging"/>
</sectionGroup>
</configSections>
 
<system.applicationHost>
<applicationPools>
<addname="AppPool"managedPipelineMode="Integrated"managedRuntimeVersion="v4.0"autoStart="true"/>
</applicationPools>
 
<sites>
<sitename="MySite"id="1">
<bindings>
<bindingprotocol="http"bindingInformation="*:{1}:localhost"/>
</bindings>
<applicationpath="/"applicationPool="AppPool">
<virtualDirectorypath="/"physicalPath="{0}"/>
</application>
</site>
</sites>
</system.applicationHost>
 
<system.webServer>
<globalModules>
<addname="StaticFileModule"image="%windir%\System32\inetsrv\static.dll"/>
<addname="AnonymousAuthenticationModule"image="%windir%\System32\inetsrv\authanon.dll"/>
<addname="ManagedEngine"image="%windir%\Microsoft.NET\Framework\v4.0.30319\webengine4.dll"/>
</globalModules>
 
<modules>
<addname="StaticFileModule"/>
<addname="AnonymousAuthenticationModule"/>
<addname="DefaultAuthentication"type="System.Web.Security.DefaultAuthenticationModule"preCondition="managedHandler"/>
<addname="UrlAuthorization"type="System.Web.Security.UrlAuthorizationModule"preCondition="managedHandler"/>
<addname="FileAuthorization"type="System.Web.Security.FileAuthorizationModule"preCondition="managedHandler"/>
<addname="AnonymousIdentification"type="System.Web.Security.AnonymousIdentificationModule"preCondition="managedHandler"/>
</modules>
 
<handlersaccessPolicy="Read, Script">
<addname="PageHandlerFactory-Integrated"path="*.aspx"verb="GET,HEAD,POST,DEBUG"type="System.Web.UI.PageHandlerFactory"preCondition="integratedMode"/>
<addname="StaticFile"path="*"verb="*"modules="StaticFileModule"resourceType="Either"requireAccess="Read"/>
</handlers>
 
<staticContent>
<mimeMapfileExtension=".html"mimeType="text/html"/>
<mimeMapfileExtension=".jpg"mimeType="image/jpeg"/>
<mimeMapfileExtension=".gif"mimeType="image/gif"/>
<mimeMapfileExtension=".png"mimeType="image/png"/>
</staticContent>
</system.webServer>
</configuration>

And all we need to start hosting pages on the port and physical path specified by ApplicationHost.config is:

using (var host = new Host(path, port))
{
    host.Start();
 
    Console.ReadLine();
}

A couple of notes:

  • Because it calls unmanaged functions, can be terrible to debug;
  • The ApplicationHost.config needs to be in the application's binary build directory and must have two placeholders, {0} and {1}, for the physical path and HTTP port, respectively;
  • It refers to .NET 4.0, if you want to change it, you will to change a number of modules and paths;
  • Only very few modules are loaded, if you want, get a full file from %HOMEPATH%\Documents\IISExpress\config\ApplicationHost.config and adapt it to your likings.

.NET TcpListener

And finally, one for the low-level guys. The TcpListener class allows the opening of TCP/IP ports and the handling of requests coming through them. It doesn’t know anything about the HTTP protocol, of course, so, if we want to leverage it, we need to implement it ourselves. Here’s a very, very, basic example:

var listener = System.Net.Sockets.TcpListener.Create(2000);
listener.Start();
 
using (var client = listener.AcceptTcpClient())
{
using (var reader = new StreamReader(client.GetStream()))
using (var writer = new StreamWriter(client.GetStream()))
    {
        var request = reader.ReadLine();
 
        writer.WriteLine("HTTP/1.1 200 OK");
        writer.WriteLine("Content-type: text/plain");
        writer.WriteLine();
        writer.WriteLine("Hello, World!");
        writer.Flush();
    }
}
 
listener.Stop();

Here we’re just reading any string content and responding with some HTTP headers plus the usual response. Of course, HTTP is quite complex, so I wouldn’t recommend you try to implement it yourself.

Conclusion

I presented a couple of solutions for hosting web resources, servicing HTTP requests or running ASP.NET handlers. Hopefully you will find one that matches your needs.

Entity Framework Code First Succinctly, Second Edition

Java vs C# – Part 2

$
0
0

Introduction

This is part two of a series of posts on Java and C#. You can read the first part, on structure, here. This time, we are going to talk about a lot of things that weren’t covered before, and leave some stuff for future posts! Smile

Object and Collection Initialization

C# offers an interesting syntax for initializing instance properties at the same time a variable is declared, which can be combined with parameterized constructors:

MyClass c = new MyClass("constructor argument") { OneProperty = 1, AnotherProperty = "two" };

It also offers a syntax for defining the values of a collection upon declaration:

List<string> list = new List<string>{ "A", "B", "C" };
Dictionary<int, string> dictionary = new Dictionary<int, string>{ { 0, "A" }, { 1, "B" } };

Any class with an instance Add method can use this syntax, because it’s this method that the compiler calls behind the scene. Inside the { }, we need to pass as many elements as the Add method takes, and of the same type.

Casts

In Java, we only have one kind of cast between types:

Object o = ...;
String s = (String) o;

But in C#, we have two: the same as in Java, plus a “dynamic”, that returns null if the types are not compatible:

Object o = 1;
String s = o as String; //s is null

The as operator can only be used with reference types (classes and interfaces) and also nullable types (like int ?). It does not automatically use conversion operators (see below).

In C# there’s also something related, the null coalescing operator. Basically, it allows this syntax for initializing a variable to some value only if it is null:

Object o1 = null;
Object o2 = new MyClass();
Object o3 = o1 ?? o2; //short for: o1 == null ? o3 : o1

Methods

Undefined Number of Parameters

Both Java and C# support methods with an undefined number of parameters. The syntax is slightly different, in C# being:

publicvoid Print(params String [] args)
{
}

An in Java:

publicvoid print(String... args)
{
}

Default Parameter Values

C# allows setting default parameter values. The default values can only be:

  • null;
  • Literals (“string”, 1, false, etc);
  • Enumerated values (MyEnum.Value);
  • Constant or read-only fields (MyClass. SomeField).
publicvoid SayHello(String to = "me")
{
}

A method can have any number of parameters with default values, but these parameters need to come at the end, after any other parameters without default values. Java does not offer default parameter values, we have to use method overloading for that.

Changing Parameter Order

C#, unlike Java, also allows passing parameters in any order, by name, which is very useful when we have methods with a lot of parameters, and we don’t want to remember their exact order:

publicvoid DoSomething(int a, string b)
{
}
 
DoSomething(b: "a string value", a: 10);

Passing Parameters by Reference

C# has two ways to pass parameters:

  • By value, the default, which is a pointer for reference types - classes and interfaces - and the actual value for value types - enumerations, structures;
  • By reference: the actual address of the variable is passed, similar to ** or & in C++.

Passing parameter values by reference can be done in one of two ways:

  • Forcing the parameter to have a value set;
  • Not forcing the parameter to have a value set.

One example that forces assignment uses the out keyword:

publicvoid Execute(outint result)
{
    result = 0;
}

And if no assignment is required, we use ref instead:

publicvoid Swap(refint a, refint b)
{
int c = a;
    a = b;
    b = c;
}

Both out and ref are functionally equivalent, but out enforces a compile-time constraint that the parameter has a value set. Passing values by reference is particularly useful in the case of structures, because, since they are not passed by pointer, they need to be copied byte by byte, which can take some time, and they might also be boxed if the method argument is of a reference type; passing structures by reference only sends the address of the local variable.

By comparison, Java always passes parameters by value, meaning, basic types pass their actual bytes and the others are passed as pointers to the original variable.

Extension Methods

C# offers the concept of extension methods. An extension method appears to be part of some type, as an instance method of that type, but it doesn’t break encapsulation, because it really isn’t part of it, and it doesn’t have access to the type’s internals.

Extension methods are defined as static methods in static classes with a this parameter of the target type:

namespace Extensions
{
publicstaticclass StringExtensions
    {
publicstatic String Revert(this String s)
        {
//...
        }
    }
    }

We call an extension method just as we call a regular method, provided that the class that defines it is in context, either by being in the same namespace as the calling method’s class, or by having its namespace imported.

using Extensions;//this is where the StringExtensions class lives
 
//...
 
String text = "abcd";
String reverted = text.Revert();

Java has virtual extension methods, also called default methods, which provide a default implementation of a method in an interface, which is then inherited (and can be overridden) by classes implementing the interface. This is the building block for the Stream API introduced recently. I talked about default methods on the first part of this series, but here’s an example.

publicinterface MyInterface
{
defaultvoid doSomething()
    {
//do something
    }
}

Default methods are always public, so there’s no need to use the public qualifier.

Static Interface Methods

Java also allows defining static methods, with implementation, in interfaces:

publicinterface MyInterface
{
staticvoid doSomethingElse()
    {
//does something else
    }
}

Like default methods, static interface methods are always public.

C# doesn’t have any way to add statics or code to interfaces.

Synchronized Methods

Both languages allow a method, static or instance, to be declared as synchronized, meaning, it will lock the object on which it is being called (or the class, if it is a static method). The Java syntax is:

publicsynchronizedvoid myMethod()
{
//I am synchronized
}

While the C# one use the MethodImplAttribute attribute:

[MethodImpl(MethodImplOptions.Synchronized)]
publicvoid MyMethod()
{
//I am synchronized
}

The syntax for acquiring a lock on an object is identical, but Java uses the synchronized keyword:

synchronized (this.someLock)
{
//...
}

And C#, lock:

lock (this.someLock)
{
//...
}

Inline Methods

In C#, it is possible to instruct the compiler to try to inline certain methods, through the MethodImplAttribute attribute:

publicclass Something
{
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
publicvoid ShouldBeMadeInline()
    {
    }    
}

The actual decision, however, is up to the compiler. Java does not allow this.

Operator Overloading

Overloadable Operators

In C#, most operators (arithmetic, comparison, bitwise) can be overloaded for a class, similarly to C++. This means that C# allows them to be redefined, so as to implement a more friendly syntax, or just change the default one:

publicstaticbooloperator == (MyClass c1, MyClass c2)
{
return c1.MyProperty == c2.MyProperty;
}

In this example, I am changing the default == operator, which just does a reference comparison, to a value comparison, where the actual contents of the class are compared. If we change ==, we also need to change !=:

publicstaticbooloperator != (MyClass c1, MyClass c2)
{
return !c1 == c2;
}

Some of the basic operators (+=, for example), cannot be defined explicitly, but can be defined from others (+):

publicstatic MyClass operator + (MyClass c1, MyClass c2)
{
returnnew MyClass(c1.MyProperty + c2.MyProperty);
}

It is also possible to compare unrelated classes, but the declaring class must appear as one of the arguments:

publicstaticbooloperator == (MyClass c, String s)
{
return c.MyProperty == s;
}

The argument order defines if the operator is to be applied, for example, the previous code applies to:

MyClass c = new MyClass();
bool areEqual = c == "some string";

But not to:

MyClass c = new MyClass();
bool areEqual = "some string" == c;

We can, however, add two times the same overloadable operator with the arguments switched, so that they can be called interchangeably. The String class overrides the == operator, so as to always do comparisons by value.

The number of arguments is defined by the operator, there are unary and binary operators, and the types they return cannot be changed. For example, operator == always expects two arguments of any kind but has to return a bool.

Type Conversions

C# also features a special kind of operator: type conversion. Actually, there are two, for implicit and explicit conversions. Implicit conversions do not need an explicit cast:

publicstaticimplicitoperatorstring (MyClass c)
{
return c.MyProperty; //MyProperty is of type string
}
 
MyClass c = new MyClass();
string s = c;

Whereas explicit ones do:

publicstaticexplicitoperatorint (MyClass c)
{
returnint.Parse(c.Property); //MyProperty is of type string
}
 
MyClass c = new MyClass();
int s = (int) c;

All operators need to be public and static.

Attributes

Attributes are static metadata that can be added to types, packages, parameters, members, variables and assemblies (in C#). Some attributes have meaning to the compiler, and in C#, they can even be used as an Aspect-Oriented Programming (AOP) mechanism, because some system attributes are evaluated at runtime.

Java offers the following out of the box attributes (called annotations in Java):

  • @FunctionalInterface: declares an interface as a functional interface (an interface with a single method);
  • @Override: informs the compiler that the method to which it is applied is an override of a method with the same name and signature declared in a base class;
  • @Deprecated: marks the method as deprecated, which issues a compile-time warning;
  • @SafeVarargs: suppresses warnings related to the (mis)use of varargs (undefined number of parameters);
  • @SuppressWarnings: tells the compiler to suppress certain warnings, passed as parameters.

There are also meta-annotations, annotations that apply to other annotations:

  • @Retention: how is the annotation kept after compilation (SOURCE: only at source level, stripped at compilation, CLASS: kept at compile time, but ignored by the Java VM, RUNTIME: kept after compilation and considered by the JVM);
  • @Documented: when the annotation is applied, some elements should be documented with JavaDocs;
  • @Target: the single target of an annotation (ANNOTATION_TYPE: other annotations, CONSTRUCTOR: constructors only, FIELD: fields, LOCAL_VARIABLE: local variables inside methods, METHOD: methods, PACKAGE: packages, PARAMETER: method parameters or TYPE: any elements of classes);
  • @Inherited: the annotation can be inherited from the type’s base class;
  • @Repeatable: the annotation can be applied several times.

As you can see, an annotation starts with a @ and must be defined as an interface using a special syntax:

@Target(value=CLASS)
public @interface MyAnnotation
{
    String name() default"";
int number();    //required since a default was not supplied
}

Annotation methods can only return basic types, enumerations and arrays of them, and cannot take parameters.

The application of the MyAnnotation annotation can be:

@MyAnnotation(number = 10) //uses default value for name
publicclass MyClass
{
}

In C#, attributes are not totally different, but there are some differences:

  • An attribute must inherit from the Attribute class, and, by convention, should have the Attribute suffix;
  • When applied, we can leave out the Attribute suffix;
  • Attribute’s members can only be of basic types, enumerations, or arrays of them;
  • Required attribute properties should be passed in the attribute’s constructor.

There are lots of attributes included in the .NET, so it is not practical to cover them all. I leave just some examples:

By applying an AttributeUsageAttribute, we can specify:

  • AllowMultiple: if there can be many occurrences of this attribute, in the same element;
  • Inherited: if the attribute’s presence and values is inherited in descending classes;
  • ValidOn: the elements to which the attribute can be applied (All, Assembly, Class, Constructor, Delegate, Enum, Event, Field, GenericParameter, Interface, Method, Module, Parameter, Property, ReturnValue, Struct).

Here’s an example of a C# attribute:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true, AllowMultiple = false)]
publicclass MyAttribute : Attribute
{
public MyAttribute(String required)
    {
this.Required = required;
    }
 
public String Required { get; private set; }
 
public Int32 Optional { get; set; }
}

And its usage, notice that we leave out the Attribute suffix and the declaration syntax:

[My("name", Optional = 10)]
publicstruct MyStruct
{
//...
}

Exceptions

Throwable Types

In .NET, any type can be thrown as an exception, but C# limits this to instances of the Exception class, or one derived from it.

In Java, we can only throw classes that implement the Throwable interface. The most common example of one such class is Exception.

Checked Exceptions

In Java, methods in classes, enumerations and interfaces must declare any exceptions that they may throw, except those inheriting from RuntimeException; these are considered special, in that they can be thrown at unforeseen situations – a division by zero, a null pointer access, etc. The syntax is for declaring the “expectable” exceptions is:

publicvoid myMethod() throws MyException
{
}

Calling any method that declares that it may throw an exception requires that the calling code be wrapped in a try…catch block, where all checked exception types must be explicitly handled, or, of course, a superclass of them (catch is polymorphic):

try
{
    myMethod();
}
catch (MyException ex)
{
}

In both languages, more specific exception classes need to be catched first, that is, if you want to catch an Exception and a MyException that inherits from Exception, the catch block for MyException must be the first. C# allows you to omit either the class variable or even the class, if it doesn't matter:

try
{
//...
}
catch(MyException)
{
//no need to refer to the exception instance
throw;  //no argument required
}
catch
{
//all other exception types
}

Rethrowing Exceptions

In Java as in C#, we can rethrow an exception caught in a catch clause:

try
{
//...
}
catch (Exception ex)
{
throw ex;
}

However, if we do it like this in C#, we lose the stack trace prior to the method issuing the throw. If we don’t want that, the alternative syntax is:

try
{
//...
}
catch (Exception ex)
{
throw;
}

Notice that if we don’t pass an argument to throw, it will rethrow the current exception – of course, this only works inside a catch clause.

Iterations

In C# and in Java we can iterate through the elements of a collection using either iterators or a specific syntax, which for C# is:

foreach (String item in list)
{
//...
}

And for Java:

for (String arg : args)
{
//...
}

In C#, any collection that has a method GetEnumerator returning an IEnumerator can benefit of this syntax, normally, all collections inheriting from IEnumerable (non-generic) or IEnumerable<T>. Java has a similar requirement, but the method needs to be called iterator and the required interface is Iterator<T>, which is implemented by most collections.

Returning Enumerables

In C#, if we want to return enumerations of values from a method, we normally prototype the method as returning IEnumerable<T>. If we do, we have a simplified syntax for returning individual values from it:

public IEnumerable<String> GetPhrases()
{
    var count = 0;
 
for (var s in listOfStrings)
    {
if (++count == 0)
        {
yieldbreak;    //break loop
        }
 
yieldreturn s;    //return one value, but continue loop
    }
}

Lambda Functions

Lambda functions in C# are built upon delegates and extension methods. A lambda is just syntactic sugar for calling methods – which can be defined inline, as anonymous ones -, and are most useful in collections processing:

List<MyClass> untidyCollection = ...;
List<MyClass> sortedAndFilteredCollection = untidyCollection.Where(c => c.MyProperty > 100).OrderBy(c => c.MyProperty).ToList();

In this example, Where and OrderBy are lambda functions defined over the IEnumerable<T> interface, which is implemented by List<T>. The types of the lambda variables can be omitted. This would be the same as:

class MyClassComparer : IComparer<MyClass>
{
public Int32 Compare(MyClass c1, MyClass c2)
    {
return c1.MyProperty.Compare(c2.MyProperty);
    }
}
 
List<MyClass> FilterCollection(List<MyClass> source, Int32 value)
{
    List<MyClass> target = new List<MyClass>();
 
foreach (MyClass c in source)
    {
if (c.MyProperty > value)
        {
            target.Add(c);
        }
    }
 
return target;
}
 
List<MyClass> SortCollection(List<MyClass> source)
{
    List<MyClass> target = new List<MyClass>(source);
    target.Sort(new MyClassComparer());
return target;
}
 
List<MyClass> untidyCollection = ...;
List<MyClass> sortedAndFilteredCollection = SortCollection(FilterCollection(untidyCollection));

Uuuf… see the gain?

A lambda can have several parameters:

Func<MyClass, Int32, MyClass> multiplicationTransformation = (c, multiplier) => new MyClass(c.MyProperty * multiplier);
MyClass source = ...;
MyClass target = multiplicationTransformation(source, 10);

In Java, things are very different. First, a lambda function can only be used over a functional interface, that is, an interface implementation with a single method. A method call that takes as a single parameter a class that implements this functional interface can be made a lambda function:

interface Operation
{
defaultint operate(int a, int b);
}
 
class Calculator
{
int doOperation(Operation op, int a, int b)
    {
return op.operate(a, b);
    }
}
 
Calculator calc = new Calculator();
Operation sumOperation = (int x, int y) -> x + y;
calculator.doOperation(sumOperation, 1, 2);

Also comparison:

List<MyClass> unsortedCollection = ...;
List<MyClass> sortedCollection = Collections.sort(unsortedCollection, (MyClass c1, MyClass c2) -> c1.getMyProperty().compareTo(c2.getMyProperty()));

And finally, action listeners:

JButton button = ...;
button.addActionListener(evt -> System.out.println("Button clicked"));

Expression Trees

Related, but even more interesting than lambda expressions, are expression trees. These can be defined using the same syntax as lambda expressions:

List<MyClass> untidyCollection = ...;
IQueryable<MyClass> untidyQueryable = untidyCollection.AsQueryable();
IQueryable<MyClass> sortedAndFilteredQueryable = untidyQueryable.Where(x => x.MyProperty > 100).OrderBy(x => x.MyProperty);

But now sortedAndFilteredQueryable is an IQueryable<T>, a standard interface for wrapping expressions that return something. From it we can access the underlying Expression, the base class for all expression

Expression expression = sortedAndFilteredQueryable.Expression;
 
if (expression is MethodCallExpression)
{
    MethodCallExpression methodCall = expression as MethodCallExpression;
    Method method = methodCall.Method;
foreach (Expression arg in methodCall.Arguments)
    {
//iterate through each argument
if (arg is ConstantExpression)
        {
//constant
        }
elseif (arg is MemberExpression)
        {
//property or field
        }
    }
}

This capability to analyze at runtime an expression is the basis for, for example, translating expression trees to SQL or OData calls – Entity Framework, LINQ to SQL, NHibernate, WCF Data Services, all use expression trees. Unlike lambdas, which do not retain the expression used, just the result, expression trees do not execute, but instead describe a C# expression.

Auto Closing Blocks

Both Java and C# offer an interesting construct for making sure resources are released when they are no longer needed.

In C#, these resources must implement IDisposable, and the syntax for the using block is as this:

using (IDisposable ctx = new DisposableContext())
{
//...
}

It allows multiple disposables in the same block:

using (var disp1 = new DisposableContext())
using (var disp2 = new DisposableContext())
{
//...
}
 

In Java, the required interface is AutoCloseable and the feature is called try with resources:

try (AutoCloseable disp1 = new Something())
{
//...
}

The syntax for having several auto-closing variables is also allowed:

try (AutoCloseable disp1 = new DisposableContext(), AutoCloseable disp2 = new DisposableContext())
{
//...
}

This basically is the same as (in both languages):

MyClass c = new MyClass();
 
try
{
//...
}
finally
{
if (c != null)
    {
        c.Dispose();    //C#
        c.close();      //Java
    }
}

Conclusion

Well, not exactly a conclusion! There will be more posts, keep dropping by and sending your feedback! Winking smile

Again, I need to thank Roberto Cortez (@radcortez) for his review of the Java parts! Thanks, man! Winking smile


Visual Studio Tips

$
0
0

Some random tips:

  1. If you need to run a web site under a different domain, so as to test multitenancy, for example, you need to run Visual Studio as an Administrator, otherwise you will get an error about an invalid hostname;
  2. If you want, you can configure Visual Studio to always start as Administrator: set the compatibility options to require additional permissions, see more here;
  3. You can have the Solution Explorer track (select automatically) the file you are editing; just select option Tools - Options - Track Active Item in Projects and Solutions;
  4. In case you need to find some class that you don't know where is located, or you only know a part of its name, use the Edit - Navigate To option or click <Ctrl>+<comma>;
  5. Split the editor window: select Window - Split; to close it, unselect it;
  6. You can now move a window to another monitor;
  7. Select columns across lines: click <Alt> while you make a vertical selection using the mouse or cursor keys; you can then copy the selection or paste some code into it;
  8. With <Alt>+<Up> or <Alt>+<Down>, you can switch the order of lines;
  9. Paste your JSON or XML code as classes: select Edit - Paste Special - Paste JSON as Classes/Paste XML as Classes;
  10. You can see the classes that inherit from some of your project's class: just select the file containing it in Solution Explorer, expand the selection to find the class, and then expand the class; you will find an option Derived Types.

And that's it for now. More will follow!

ASP.NET Web Forms Extensibility: Model Binding Value Providers

$
0
0

ASP.NET 4.5 introduced model binding: basically, it is a way for databound controls - Repeater, GridView, ListView, etc - to be fed, not from a datasource control - ObjectDataSource, EntityDataSource, SqlDataSource, etc -, but from a method in the page. This method needs to return a collection, and may have parameters. The problem is: how these parameters get their values? The answer is: through a model binding value provider.

A model binding value provider is a class that implements IValueProvider, and normally is injected through a ValueProviderSourceAttribute-derived attribute. ASP.NET includes some implementations:

If we want, say, to return a value from the Common Service Locator, it's pretty easy. First, an attribute:

[Serializable]
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
publicsealedclass ServiceLocatorAttribute : ValueProviderSourceAttribute
{
privatereadonly Type serviceType;
privatereadonly String key;
 
public ServiceLocatorAttribute(Type serviceType, String key = null)
    {
this.serviceType = serviceType;
this.key = key;
    }
 
publicoverride IValueProvider GetValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
    {
returnnew ServiceLocatorValueProvider(this.serviceType, this.key);
    }
}

And now the actual value provider:

publicsealedclass ServiceLocatorValueProvider : IValueProvider
{
privatereadonly Type serviceType;
privatereadonly String key;
 
public ServiceLocatorValueProvider(Type serviceType, String key)
    {
this.serviceType = serviceType;
this.key = key;
    }
 
public Boolean ContainsPrefix(String prefix)
    {
returntrue;
    }
 
public ValueProviderResult GetValue(String key)
    {
returnnew ValueProviderResult(ServiceLocator.Current.GetInstance(this.serviceType, this.key), null, CultureInfo.CurrentCulture);
    }
}

You can even have the ServiceLocatorAttribute implement the IValueProvider interface, I just separated it because conceptually they are different things.

Finally, here's how we would use it:

public IQueryable<SomeEntity> GetItems([ServiceLocator(typeof(MyComponent), "SomeKey")] MyComponent cmp)
{
//do something
}

Pretty sleek, don't you think? Winking smile

Querying SharePoint

$
0
0

Introduction

SharePoint, being a content management system, of course, offers a couple of ways to query its contents programmatically. Here we will explore some of these options.

Web Parts

First, of course, there are the web parts. These allow us to configure queries visually on a page. The most important web parts are:

ContentByQueryWebPart: use this for simple queries that do not return much contents, on a single site collection. Can be used in SharePoint Online. Can only be customized through XSLT.

ContentBySearchWebPart (introduced in SharePoint 2013): more powerful, but does not exist in SharePoint Online. Can handle more complex queries that can span multiple site collections and multiple levels of sorting. Can only be customized through HTML and JavaScript templates. Results can be refined.

XsltListViewWebPart/DataFormWebPart: can be used to view of a specific list. The display can be totally configured. XsltListViewWebPart is a bit more powerful.

ListViewByQuery: requires that you pass an SPList and a SPQuery instance. Can only display pre-defined views.

APIs

There are several APIs for querying, either directly or using the search index.

SPQuery: can only be applied to a single list:

var query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>Bla Bla</Value></Eq></Where>";
 
var list = site.RootWeb.Lists["Some List"];
 
var table = list.GetItems(query).GetDataTable();

SPSiteDataQuery: can be applied to several lists across a site collection. Has some issues, for example, won't return values for multi-value fields:

var query = new SPSiteDataQuery();
query.Lists = "<List Name='Tasks'/>";
query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>Bla Bla</Value></Eq></Where>";
query.Webs = "<Web Scope='SiteCollection'/>";
 
var table = site.RootWeb.GetSiteData(query);

KeywordQuery: uses the search index to search for keywords, so it requires that contents are indexed beforehand, and the search service is functioning:

using (var query = new KeywordQuery(site))
{
    query.QueryText = "Bla Bla";
    query.ResultsProvider = SearchProvider.Default;
 
    var searchExecutor = new SearchExecutor();
 
    var resultTableCollection = searchExecutor.ExecuteQuery(query);
 
    var searchResult = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults).Single();
 
    var table = new DataTable();
    table.TableName = "Result";
    table.Load(searchResult, LoadOption.OverwriteChanges);
}

FullTextSqlQuery: uses SharePoint Search SQL to execute queries, which makes it generally more powerful than KeywordQuery:

using (var query = new FullTextSqlQuery(site))
{
    query.QueryText = "SELECT * FROM scope() WHERE Title = 'Teste'";
    query.ResultsProvider = SearchProvider.Default;
 
    var searchExecutor = new SearchExecutor();
 
    var resultTableCollection = searchExecutor.ExecuteQuery(query);
 
    var searchResult = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults).Single();
 
    var table = new DataTable();
    table.TableName = "Result";
    table.Load(searchResult, LoadOption.OverwriteChanges);
}

CrossListQueryInfo and CrossListQueryCache: performs queries in a single site collection but multiple sites, with optional audience targeting. CrossListQueryCache caches the results for a period of time:

var crossListQueryInfo = new CrossListQueryInfo();
crossListQueryInfo.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>Bla Bla</Value></Eq></Where>";
crossListQueryInfo.Lists = "<List Name='Some List'/>";
crossListQueryInfo.Webs = "<Webs Scope='SiteCollection' />";
crossListQueryInfo.UseCache = true;
 
var crossListQueryCache = new CrossListQueryCache(crossListQueryInfo);
 
var table = crossListQueryCache.GetSiteData(site.RootWeb);

Client KeywordQuery: this is the client counterpart to KeywordQuery. It uses the SharePoint Client Components, or Client Side Object Model (CSOM), which means, it accesses SharePoint through its web services. It is basically similar to the server KeywordQuery, but can be used from a remote machine:

var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(ctx);
keywordQuery.QueryText = "SharePoint";
 
var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(ctx);
 
var results = searchExecutor.ExecuteQuery(keywordQuery);
 
ctx.ExecuteQuery();
 
var searchResult = results.Value.Where(x => x.TableType == KnownTableTypes.RelevantResults.ToString()).Single();

Web Services

Search.asmx: SOAP web service that takes a SharePoint SQL query. Part of the SharePoint Foundation 2010 Web Services, now somewhat obsolete.

Lists.asmx: Another SOAP web service that can return and update items in a list.

ListData.svc: WCF Data Service REST/OData that can be used for querying (including OData queries) or modifying contents of lists.

SharePoint 2013 REST Services: new REST/OData web services introduced in SharePoint 2013. Includes _api/web, _api/search, _api/web/lists, for searches, web or list operations.

SharePoint Foundation RPC Protocol

The SharePoint Foundation RPC Protocol, now obsolete, this allowed querying, exporting contents and performing a number of other operations through the OWSSVR.DLL handler. Although almost unused nowadays, still offers the only out of the box way to, for example, export a list in XML format.

JavaScript

In SharePoint 2010 the JavaScript Side Object Model (JSOM) was introduced and in version 2013 it was enhanced. It is now possible to do anything that the SharePoint Client API allows.

Conclusion

You see, lots of ways to get contents from SharePoint, as usual. Make sure you chose the one that best suits your needs.

References

SharePoint 2013 .NET Server, CSOM, JSOM, and REST API index

When to use the Content Query Web Part or the Content Search Web Part in SharePoint

Choose the right API set in SharePoint 2013

Use OData query operations in SharePoint REST requests

SharePoint Server 2013 Client Components SDK

SharePoint Search SQL Syntax Reference

Visual Studio Tips 2

$
0
0

OK, continuing with my previous post, here are some more Visual Studio tips, this time, with a lot more pictures! Winking smile

  1. Start several projects simultaneously: when it comes to starting a project in a solution, there are three options:
    1. Start a single, fixed, project;
    2. Start the project where the focus is currently on;
    3. Start multiple projects simultaneously.

    Right click on the solution - Properties - Common Projects - Startup Project and select Multiple startup projects:

    image

  2. Break on exceptions: Visual Studio can break automatically on first-chance exceptions (ones that may be caught afterwards). This is useful, because if you have catch blocks, you might not even notice them. First-chance exception breaking can be defined on a class per class basis. First, click on Debug - Exceptions:

    image

    Then, check the ones that you are interested in:

    image

  3. Conditional breakpoints: you can enable breakpoints based on some condition on the code. First, create a breakpoint, right click in it, then click on Condition:

    image

    Now you can add any condition you want, either based on local or global variables and methods - watch out for any possible side effects!

    image

    Another option is to only break when the hit count - the number of times the program has processed the instruction - has reached some value. Click on Hit Count and select the right condition, break always is the default:

    image

    Yet another option is to add a filter. This is a limited condition, which can only take a couple of variables. Activate it by clicking on Filter:

    image

  4. Tracepoints: in the Ultimate edition of Visual Studio (sorry, folks that to not have it!) you can send output to the trace window without actually writing any code. How many times did you add a Trace.WriteLine call, or something similar, for this purpose? Create a breakpoint, then click When Hit:

    image

    Now, add an output string, which can take variables, parameters or properties, plus some special tokens:

    image

    image

  5. Showing or hiding items from Output window: while debugging your application, the Output windows tends to be cluttered with all sorts of messages. Well, you can hide some of them. Just right click on the Output window and check out those that you want to hide:

    image

  6. Add links: in a project, you can add physical files, which are copied to the project's folder, or links, which are kept in their original locations. Select Add - Existing Item, navigate to the folder containing the file you want to add, select it, but instead of clicking Add, select Add As Link from the drop down:

    image

  7. Save text files with different encoding: due to several reasons, you might need to save a text file with a particular encoding. When about to save the file, click the drop down in the Save button and select Save with Encoding:

    image

    Then select the encoding and line ending you want:

    image

  8. Preview Web.config transformations: ASP.NET Web.config Transformations were introduced in Visual Studio 2010 and allow us to perform transformations on the Web.config file based on the current configuration - Debug, Release, etc, upon deployment. The problem is, most of you don't know it's possible to view the result file without actually deploying the application, but it is! Right click on a transformation file, like Web.Release.config, and select Preview Transform:

    image

  9. Generate ASP.NET designer files: when your ASP.NET web forms designer files - like Default.Designer.aspx.cs - become corrupted, for whatever reason, it's better to remove them and have them generated by Visual Studio. Right click on the markup file - .aspx, .master or .ascx - and click on Project - Convert to Web Application (weird choice of name, I know):

    image

  10. Debug MSBuild scripts: I left the best for last! It's possible to debug .csproj build tasks, which are basically MSBuild tasks. I won't cover it all here, but instead make sure you read this post by Dan Moseleyhttp://blogs.msdn.com/b/visualstudio/archive/2010/07/06/debugging-msbuild-script-with-visual-studio.aspx.

I will be back! Winking smile

Lesser-Known NHibernate Features: Mapping By Attributes

$
0
0

Some O/RMs do their mapping based on attributes. LINQ to SQL and Entity Framework are good examples, although Entity Framework also supports mapping by code. I'm not saying this is good or bad - some people think it "pollutes" POCOs, other think it makes them easier to understand -, but, likewise, NHibernate also allows to map entities by attributes, let's see how.

First, add a reference to the NHibernate.Mapping.Attributes NuGet package:

image

Next, go to your entity and start adding some attributes:

[NHibernate.Mapping.Attributes.Class(Table = "blog", Lazy = true)]
publicclass Blog
{
public Blog()
    {
this.Posts = new List<Post>();
    }
 
    [NHibernate.Mapping.Attributes.Id(0, Column = "blog_id", Name = "BlogId")]
    [NHibernate.Mapping.Attributes.Generator(1, Class = "hilo")]
publicvirtual Int32 BlogId { get; set; }
 
    [NHibernate.Mapping.Attributes.Property(Name = "Picture", Column = "picture", NotNull = false, TypeType = typeof(ImageUserType), Lazy = true)]
publicvirtual Image Picture { get; set; }
 
    [NHibernate.Mapping.Attributes.Property(Name = "PostCount", Formula = "(SELECT COUNT(1) FROM post WHERE post.blog_id = blog_id)")]
publicvirtual Int64 PostCount { get; protected set; }
 
    [NHibernate.Mapping.Attributes.ManyToOne(0, Column = "user_id", NotNull = true, Lazy = NHibernate.Mapping.Attributes.Laziness.NoProxy, Name = "Owner", Cascade = "save-update")]
    [NHibernate.Mapping.Attributes.Key(1)]
publicvirtual User Owner { get; set; }
 
    [NHibernate.Mapping.Attributes.Property(Name = "Name", Column = "name", NotNull = true, Length = 50)]
publicvirtual String Name { get; set; }
 
    [NHibernate.Mapping.Attributes.Property(Name = "Creation", Column = "creation", NotNull = true)]
publicvirtual DateTime Creation { get; set; }
 
    [NHibernate.Mapping.Attributes.List(0, Name = "Posts", Cascade = "all-delete-orphan", Lazy = NHibernate.Mapping.Attributes.CollectionLazy.True, Inverse = true, Generic = true)]
    [NHibernate.Mapping.Attributes.Key(1, Column = "blog_id", NotNull = true)]
    [NHibernate.Mapping.Attributes.Index(2, Column = "number")]
    [NHibernate.Mapping.Attributes.OneToMany(3, ClassType = typeof(Post))]
publicvirtual IList<Post> Posts { get; protected set; }
}

Basically, you will use:

  • ClassAttribute for marking a class as an entity;
  • IdAttribute: for declaring the id property;
  • GeneratorAttribute: for the id generator strategy;
  • PropertyAttribute: a mapped property;
  • BagAttribute/ListAttribute/SetAttribute/ArrayAttribute/etc: kinds of collections;
  • KeyAttribute: the key in a relation;
  • ElementAttribute: an element of an indexed collection;
  • IndexAttribute: the index in an indexed collection;
  • OneToManyAttribute/ManyToOneAttribute/OneToOneAttribute/ManyToManyAttribute: an endpoint property.

All these attributes live in the NHibernate.Mapping.Attributes namespace and are named very closely to the equivalent HBM.XML elements, which means they must be ordered (notice the first number on some attributes). Now, in order to actually make sense of these attributes, you need to:

var cfg = new Configuration();
var serializer = new HbmSerializer() { Validate = true };
 
using (var stream = serializer.Serialize(assemblyContainingEntitiesWithAttributes))
{
    cfg.AddInputStream(stream);
}

And that's all it takes! Have fun! Winking smile

MVP Showcase Portugal 2015

$
0
0

(Portuguese only, sorry!)

É com muito gosto que anuncio o evento MVP Showcase Portugal 2015!

Organizado pela comunidade de MVPs portugueses, irá ocorrer dia 22 de Abril, nas instalações da Microsoft Portugal, e tem como objectivos:

  • Apresentar o programa MVP da Microsoft e explicar como os seus membros podem ajudar as empresas e mesmo developers individuais;
  • Promover as várias comunidades de developers portuguesas;
  • Realizar apresentações sobre várias tecnologias Microsoft, por especialistas nessas mesmas tecnologias;
  • Networking, networking, networking! Winking smile

Cada sessão terá entre 30 e 45 minutos, e entre as quais haverá espaço para confraternizar com os MVPs e colocar questões: Ask The Experts.

A participação é gratuita mas sujeita a inscrição em http://mvpshowcase2015.eventbrite.pt.

Podem encontrar mais detalhes sobre o evento em http://msmvppt.org, incluindo a agenda detalhada.

Estamos no Facebook em https://www.facebook.com/MVPpt, no Twitter em @mvpportugal e respondemos a quaisquer questões que tenham no email msmvp@outlook.pt.

Os nossos patrocinadores, que tornaram este evento possível, são:

patrocinadores

Esperamos por vocês lá! Winking smile

XSLT Processing in .NET

$
0
0

God only knows why, but the .NET framework only includes support for XSLT 1.0. This makes it difficult, but not impossible, to use the more recent 2.0 version: a number of external libraries exist that can help us achieve that.

I wanted to make this easier for us developers, namely:

  1. To have a common interface for abstracting typical functionality - transform some XML with some XSLT;
  2. Be able to inject parameters;
  3. Be able to inject custom extension functions.

I first set out to define my base API:

[Serializable]
publicabstractclass XsltProvider
{
publicabstract String Transform(String xml, String xslt, XsltExtensionEventArgs args);
publicabstract Single Version { get; }
}
 
[Serializable]
publicsealedclass XsltExtensionEventArgs
{
public XsltExtensionEventArgs()
    {
this.Extensions = new Dictionary<String, Object>();
this.Parameters = new HashSet<XsltParameter>();
    }
 
public IDictionary<String, Object> Extensions
    {
        get;
private set;
    }
 
public ISet<XsltParameter> Parameters
    {
        get;
private set;
    }
 
public XsltExtensionEventArgs AddExtension(String @namespace, Object extension)
    {
this.Extensions[@namespace] = extension;
returnthis;
    }
 
public XsltExtensionEventArgs AddParameter(String name, String namespaceUri, String parameter)
    {
this.Parameters.Add(new XsltParameter(name, namespaceUri, parameter));
returnthis;
    }
}

The XsltProvider class only defines a version and a transformation method. This transformation method receives an XML and an XSLT parameters and also an optional collection of extension methods and parameters. There's a singleton instance to make it easier to use, since this class really has no state.

An implementation using .NET's built-in classes, for XSLT 1.0, is trivial:

[Serializable]
publicsealedclass DefaultXsltProvider : XsltProvider
{
publicstaticreadonly XsltProvider Instance = new DefaultXsltProvider();
 
publicoverride Single Version
    {
        get { return 1F; }
    }
 
publicoverride String Transform(String xml, String xslt, XsltExtensionEventArgs args)
    {
using (var stylesheet = new XmlTextReader(xslt, XmlNodeType.Document, null))
        {
            var arg = new XsltArgumentList();
 
foreach (var key in args.Extensions.Keys)
            {
                arg.AddExtensionObject(key, args.Extensions[key]);
            }
 
foreach (var param in args.Parameters)
            {
                arg.AddParam(param.Name, param.NamespaceUri, param.Parameter);
            }
 
            var doc = new XmlDocument();
            doc.LoadXml(xml);
 
            var transform = new XslCompiledTransform();
            transform.Load(stylesheet);
 
            var sb = new StringBuilder();
 
using (var writer = new StringWriter(sb))
            {
                var results = new XmlTextWriter(writer);
 
                transform.Transform(doc, arg, results);
 
return sb.ToString();
            }
        }
    }
}

For XSLT 2.0, we have a number of options. I ended up using Saxon-HE, an open-source and very popular library for .NET and Java. I installed it through NuGet:

image

Here is a possible implementation on top of my base class:

[Serializable]
publicsealedclass SaxonXsltProvider : XsltProvider
{
publicstaticreadonly XsltProvider Instance = new SaxonXsltProvider();
 
publicoverride Single Version
    {
        get { return 2F; }
    }
 
publicoverride String Transform(String xml, String xslt, XsltExtensionEventArgs args)
    {
        var processor = new Processor();
 
foreach (var key in args.Extensions.Keys)
        {
foreach (var function inthis.CreateExtensionFunctions(args.Extensions[key], key))
            {
                processor.RegisterExtensionFunction(function);
            }
        }
 
        var document = new XmlDocument();
        document.LoadXml(xslt);
 
        var input = processor.NewDocumentBuilder().Build(document);
 
        var xsltCompiler = processor.NewXsltCompiler();
 
        var xsltExecutable = xsltCompiler.Compile(input);
 
        var xsltTransformer = xsltExecutable.Load();
 
foreach (var parameter in args.Parameters)
        {
            xsltTransformer.SetParameter(new QName(String.Empty, parameter.NamespaceUri, parameter.Name), CustomExtensionFunctionDefinition.GetValue(parameter.Parameter));
        }
 
using (var transformedXmlStream = new MemoryStream())
        {
            var dataSerializer = processor.NewSerializer(transformedXmlStream);
 
            xsltTransformer.InputXmlResolver = null;
            xsltTransformer.InitialContextNode = processor.NewDocumentBuilder().Build(input);
            xsltTransformer.Run(dataSerializer);
 
            var result = Encoding.Default.GetString(transformedXmlStream.ToArray());
 
return result;
        }
    }
 
private IEnumerable<ExtensionFunctionDefinition> CreateExtensionFunctions(Object extension, String namespaceURI)
    {
foreach (var method in extension.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).Where(x => x.IsAbstract == false))
        {
yieldreturnnew CustomExtensionFunctionDefinition(method, namespaceURI, extension);
        }
    }
 
class CustomExtensionFunctionDefinition : ExtensionFunctionDefinition
    {
privatereadonly String namespaceURI;
privatereadonly MethodInfo method;
privatereadonly Object target;
 
public CustomExtensionFunctionDefinition(MethodInfo method, String namespaceURI, Object target)
        {
this.method = method;
this.namespaceURI = namespaceURI;
this.target = target;
        }
 
publicoverride XdmSequenceType[] ArgumentTypes
        {
            get
            {
returnthis.method.GetParameters().Select(x => this.GetArgumentType(x)).ToArray();
            }
        }
 
private XdmSequenceType GetArgumentType(ParameterInfo parameter)
        {
returnnew XdmSequenceType(GetValueType(parameter.ParameterType), XdmSequenceType.ONE);
        }
 
internalstatic XdmAtomicValue GetValue(Object value)
        {
if (valueis String)
            {
returnnew XdmAtomicValue(value.ToString());
            }
 
if ((valueis Int32) || (valueis Int32))
            {
returnnew XdmAtomicValue(Convert.ToInt64(value));
            }
 
if (valueis Boolean)
            {
returnnew XdmAtomicValue((Boolean)value);
            }
 
if (valueis Single)
            {
returnnew XdmAtomicValue((Single)value);
            }
 
if (valueis Double)
            {
returnnew XdmAtomicValue((Double)value);
            }
 
if (valueis Decimal)
            {
returnnew XdmAtomicValue((Decimal)value);
            }
 
if (valueis Uri)
            {
returnnew XdmAtomicValue((Uri)value);
            }
 
thrownew ArgumentException("Invalid value type.", "value");
        }
 
internalstatic XdmAtomicType GetValueType(Type type)
        {
if (type == typeof(Int32) || type == typeof(Int64) || type == typeof(Int16))
            {
return XdmAtomicType.BuiltInAtomicType(QName.XS_INTEGER);
            }
 
if (type == typeof(Boolean))
            {
return XdmAtomicType.BuiltInAtomicType(QName.XS_BOOLEAN);
            }
 
if (type == typeof(String))
            {
return XdmAtomicType.BuiltInAtomicType(QName.XS_STRING);
            }
 
if (type == typeof(Single))
            {
return XdmAtomicType.BuiltInAtomicType(QName.XS_FLOAT);
            }
 
if (type == typeof(Double))
            {
return XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE);
            }
 
if (type == typeof(Decimal))
            {
return XdmAtomicType.BuiltInAtomicType(QName.XS_DECIMAL);
            }
 
if (type == typeof(Uri))
            {
return XdmAtomicType.BuiltInAtomicType(QName.XS_ANYURI);
            }
 
thrownew ArgumentException("Invalid value type.", "value");
        }
 
publicoverride QName FunctionName
        {
            get { returnnew QName(String.Empty, this.namespaceURI, this.method.Name); }
        }
 
publicoverride ExtensionFunctionCall MakeFunctionCall()
        {
returnnew CustomExtensionFunctionCall(this.method, this.target);
        }
 
publicoverride Int32 MaximumNumberOfArguments
        {
            get { returnthis.method.GetParameters().Length; }
        }
 
publicoverride Int32 MinimumNumberOfArguments
        {
            get { returnthis.method.GetParameters().Count(p => p.HasDefaultValue == false); }
        }
 
publicoverride XdmSequenceType ResultType(XdmSequenceType[] argumentTypes)
        {
returnnew XdmSequenceType(GetValueType(this.method.ReturnType), XdmSequenceType.ONE);
        }
    }
 
class CustomExtensionFunctionCall : ExtensionFunctionCall
    {
privatereadonly MethodInfo method;
privatereadonly Object target;
 
public CustomExtensionFunctionCall(MethodInfo method, Object target)
        {
this.method = method;
this.target = target;
        }
 
publicoverride IXdmEnumerator Call(IXdmEnumerator[] arguments, DynamicContext context)
        {
            var args = new List<Object>();
 
foreach (var arg in arguments)
            {
                var next = arg.MoveNext();
                var current = arg.Current as XdmAtomicValue;
                args.Add(current.Value);
            }
 
            var result = this.method.Invoke(this.target, args.ToArray());
 
            var value = CustomExtensionFunctionDefinition.GetValue(result);
returnvalue.GetEnumerator() as IXdmEnumerator;
        }
    }
}

You can see that this required considerable more effort. I use reflection to find all arguments and the return type of the passed extension objects and I convert them to the proper types that Saxon expects.

A simple usage might be:

//sample class containing utility functions
class Utils
{
publicint Length(string s)
    {
//just a basic example
return s.Length;
    }
}
 
var provider = SaxonXsltProvider.Instance;
 
var arg = new XsltExtensionEventArgs()
    .AddExtension("urn:utils", new Utils())
    .AddParameter("MyParam", String.Empty, "My Value");
 
var xslt = "<?xml version='1.0'?><xsl:transform version='2.0' xmlns:utils='urn:utils' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:template match='/'>Length: <xsl:value-of select='utils:Length(\"Some Text\")'/> My Parameter: <xsl:value-of select='@MyParam'/></xsl:template></xsl:transform>";
var xml = "<?xml version='1.0'?><My><SampleContents/></My>";
 
var result = provider.Transform(xml, xslt, arg);

Here I register an extension object with a public function taking one parameter and also a global parameter. In the XSLT I output this parameter and also the results of the invocation of a method in the extension object. The namespace of the custom function (Length) must match the one registered in the XsltExtensionEventArgs instance.

As always, hope you find this useful! Winking smile


SharePoint XSLT Web Part

$
0
0

After my previous post on XSLT processing, what else could follow? Of course, an XSLT web part for SharePoint! Smile

Here I want to solve a couple of problems:

  • Allow the usage of XSLT 2.0;
  • Have a more flexible parameter passing mechanism than <ParameterBindings>;
  • Make the XSLT extension mechanism (parameters, functions) more usable.

Similar to XsltListViewWebPart and the others, this web part will query SharePoint and return the results processed by a XSLT style sheet. I am going to built on top of the classes introduced in the last post. Here is the SPCustomXsltWebPart (please, do give it a better name...):

public enum XsltVersion
{
    Xslt1 = 1,
    Xslt2 = 2
}
 
public class SPCustomXsltWebPart : WebPart, IWebPartTable
{
    private static readonly Regex parametersRegex = new Regex(@"@(\w+)\b", RegexOptions.IgnoreCase);
 
    [NonSerialized]
    private DataTable table;
    [NonSerialized]
    private IOrderedDictionary parameters;
 
    public SPCustomXsltWebPart()
    {
        this.AddDefaultExtensions = true;
        this.RowLimit = Int32.MaxValue;
        this.Parameters = new ParameterCollection();
        this.XsltVersion = XsltVersion.Xslt1;
    }
 
    [Category("XSLT")]
    [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(true)]
    [WebDisplayName("XSL Version")]
    [WebDescription("The XSLT version")]
    [DefaultValue(XsltVersion.Xslt1)]
    public XsltVersion XsltVersion { get; set; }
 
    [Category("XSLT")]
    [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(true)]
    [WebDisplayName("XSL Link")]
    [WebDescription("The URL of a file containing XSLT")]
    [DefaultValue("")]
    public String XslLink { get; set; }
 
    [Category("XSLT")]
    [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(true)]
    [WebDisplayName("XSL")]
    [WebDescription("The XSLT content")]
    [DefaultValue("")]
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public String Xsl { get; set; }
 
    [Category("Query")]
    [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(true)]
    [WebDisplayName("Query")]
    [WebDescription("The CAML query")]
    [DefaultValue("")]
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public String Query { get; set; }
 
    [Category("Query")]
    [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(true)]
    [WebDisplayName("Row Limit")]
    [WebDescription("The row limit")]
    [DefaultValue(Int32.MaxValue)]
    public UInt32 RowLimit { get; set; }
 
    [Category("Query")]
    [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(true)]
    [WebDisplayName("Lists")]
    [WebDescription("The target lists")]
    [DefaultValue("")]
    public String Lists { get; set; }
 
    [Category("Query")]
    [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(true)]
    [WebDisplayName("Webs")]
    [WebDescription("The target webs")]
    [DefaultValue("")]
    public String Webs { get; set; }
 
    [Category("Query")]
    [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(true)]
    [WebDisplayName("View Fields")]
    [WebDescription("The view fields")]
    [DefaultValue("")]
    public String ViewFields { get; set; }
 
    [Category("Query")]
    [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(true)]
    [WebDisplayName("Query Throttle Mode")]
    [WebDescription("The query throttle mode")]
    [DefaultValue(SPQueryThrottleOption.Default)]
    public SPQueryThrottleOption QueryThrottleMode { get; set; }
 
    [Category("General")]
    [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(true)]
    [WebDisplayName("Add Default Extensions")]
    [WebDescription("Adds the default extensions")]
    [DefaultValue(true)]
    public Boolean AddDefaultExtensions { get; set; }
 
    [PersistenceModeAttribute(PersistenceMode.InnerProperty)]
    public ParameterCollection Parameters { get; private set; }
 
    public event EventHandler<XsltExtensionEventArgs> XsltExtension;
 
    protected XsltProvider XsltProvider
    {
        get
        {
            return this.XsltVersion == XsltVersion.Xslt1 ? DefaultXsltProvider.Instance : SaxonXsltProvider.Instance;
        }
    }
    protected virtual void OnXsltExtension(XsltExtensionEventArgs e)
    {
        var handler = this.XsltExtension;
 
        if (handler != null)
        {
            handler(this, e);
        }
    }
 
    protected override void CreateChildControls()
    {
        var xml = this.GetXml();
        var html = this.Render(xml);
        var literal = new LiteralControl(html);
 
        this.Controls.Add(literal);
 
        base.CreateChildControls();
    }
 
    private String GetXslt()
    {
        var xslt = String.Empty;
 
        if (String.IsNullOrWhiteSpace(this.Xsl) == false)
        {
            xslt = this.Xsl;
        }
        else if (String.IsNullOrWhiteSpace(this.XslLink) == false)
        {
            var doc = new XmlDocument();
            doc.Load(this.XslLink);
 
            xslt = doc.InnerXml;
        }
 
        return xslt;
    }
 
    private DataTable GetTable()
    {
        if (this.table == null)
        {
            var query = new SPSiteDataQuery();
            query.Query = this.ApplyParameters(this.Query);
            query.QueryThrottleMode = this.QueryThrottleMode;
            query.RowLimit = this.RowLimit;
            query.Lists = this.Lists;
            query.Webs = this.Webs;
            query.ViewFields = this.ViewFields;
 
            this.table = SPContext.Current.Site.RootWeb.GetSiteData(query);
            this.table.TableName = "Row";
 
            foreach (var column in this.table.Columns.OfType<DataColumn>())
            {
                column.ColumnMapping = MappingType.Attribute;
            }
        }
 
        return this.table;
    }
 
    private String ApplyParameters(String value)
    {
        var parameters = this.GetParameters();
 
        value = parametersRegex.Replace(value, x => this.GetFormattedValue(parameters[x.Value.Substring(1)]));
 
        return value;
    }
 
    private String GetFormattedValue(Object value)
    {
        if (value == null)
        {
            return String.Empty;
        }
 
        if (value is Enum)
        {
            return ((Int32)value).ToString();
        }
 
        if (value is DateTime)
        {
            return SPUtility.CreateISO8601DateTimeFromSystemDateTime((DateTime)value);
        }
 
        if (value is IFormattable)
        {
            return (value as IFormattable).ToString(String.Empty, CultureInfo.InvariantCulture);
        }
 
        return value.ToString();
    }
 
    private IOrderedDictionary GetParameters()
    {
        if (this.parameters == null)
        {
            this.parameters = this.Parameters.GetValues(this.Context, this);
        }
 
        return this.parameters;
    }
 
    private String GetXml()
    {
        var sb = new StringBuilder();
        var table = this.GetTable();
 
        using (var writer = new StringWriter(sb))
        {
            table.WriteXml(writer);
        }
 
        sb
            .Replace("<DocumentElement>", "<dsQueryResponseRowLimit='" + this.RowLimit + "'><Rows>")
            .Replace("</DocumentElement>", "</Rows></dsQueryResponse>");
 
        return sb.ToString();
    }
 
    private String ApplyXslt(String xml, String xslt, XsltExtensionEventArgs args)
    {
        return this.XsltProvider.Transform(xml, xslt, args);
    }
 
    private String Render(String xml)
    {
        if (String.IsNullOrWhiteSpace(xml) == true)
        {
            return String.Empty;
        }
 
        var xslt = this.GetXslt();
 
        if (String.IsNullOrWhiteSpace(xslt) == true)
        {
            return String.Empty;
        }
 
        var extensions = new XsltExtensionEventArgs();
 
        this.OnXsltExtension(extensions);
 
        if (this.AddDefaultExtensions == true)
        {
            var defaultExtensions = Activator.CreateInstance(typeof(Microsoft.SharePoint.WebPartPages.DataFormWebPart).Assembly.GetType("Microsoft.SharePoint.WebPartPages.DataFormDdwRuntime"));
            extensions.AddExtension("http://schemas.microsoft.com/WebParts/v2/DataView/runtime", defaultExtensions);
        }
 
        foreach (var ext in extensions.Extensions)
        {
            extensions.AddExtension(ext.Key, ext.Value);
        }
 
        var parameters = this.GetParameters();
 
        foreach (var key in parameters.Keys.OfType<String>())
        {
            extensions.AddParameter(key, String.Empty, parameters[key].ToString());
        }
 
        foreach (var param in extensions.Parameters)
        {
            extensions.AddParameter(param.Name, param.NamespaceUri, param.Parameter.ToString());
        }
 
        return this.ApplyXslt(xml, xslt, extensions);
    }
 
    void IWebPartTable.GetTableData(TableCallback callback)
    {
        callback(this.GetTable().DefaultView);
    }
 
    PropertyDescriptorCollection IWebPartTable.Schema
    {
        get { return TypeDescriptor.GetProperties(this.GetTable().DefaultView); }
    }
}

This class extends the basic WebPart class and adds a couple of properties:

  • XsltVersion: the XSLT version to use, which will result in either my DefaultXsltProvider or the SaxonXsltProvider being used;
  • XslLink: the URL of a file containing XSLT;
  • Xsl: in case you prefer to have the XSLT inline;
  • Query: a CAML query;
  • Webs: the webs to query;
  • Lists: the lists to query;
  • ViewFields: the fields to return;
  • RowLimit: maximum number of rows to return;
  • QueryThrottleMode: the query throttle mode;
  • AddDefaultExtensions: whether to add the default extension functions and parameters;
  • Parameters: a standard collection of ASP.NET parameter controls.

The web part uses SPSiteDataQuery to execute a CAML query. Before the query is executed, any parameters it may have, in the form @ParameterName,  are replaced by actual values evaluated from the Parameters collection. This gives some flexibility to the queries, because, not only ASP.NET includes parameters for all the common sources, it's very easy to add new ones. The web part knows how to format strings, enumerations, DateTime objects and in general any object implementing IFormattable; if you wish, you can extend it to support other types, but I don't think it will be necessary.

An example usage:

<web:SPCustomXsltWebPartrunat="server"XslLink="~/Style.xslt">
<Query>
<Where><Eq><FieldRefName='Id'/><ValueType='Number'>@Id</Value></Eq></Where>
</Query>
<Parameters>
<asp:QueryStringParameterName="Id"QueryStringField="Id"Type="Int32"/>
</Parameters>
</web:SPCustomXsltWebPart>

Notice that one of the Xsl or the XslLink properties must be set, and the same goes for the Query.

Hope you find this useful, and let me know how it works!


 

Lesser-Known NHibernate Features: Custom Loggers

$
0
0

Extensible as it is, it's no wonder that NHibernate also supports injecting custom loggers. The support is twofold:

  • There's the ILoggerFactory interface, that must be implemented by custom logger factories; this is the responsible for creating actual loggers;
  • Then there's the IInternalLogger interface, the one that provides the common functions found in most loggers (warn, info, debug, error, fatal, etc).

By default, it uses Log4Net, but it is easy to add our own logger.

So, let's start by implementing a logger factory - just the skeleton, I leave it to you as an exercise:

publicclass CustomLoggerFactory : ILoggerFactory
{
public IInternalLogger LoggerFor(Type type)
    {
returnnew CustomLogger(type.FullName);
    }
 
public IInternalLogger LoggerFor(String keyName)
    {
returnnew CustomLogger(keyName);
    }
}

And then the actual logger:

publicclass CustomLogger : IInternalLogger
{
public String Key { get; private set; }
 
public CustomLogger(String key)
    {
this.Key = key;
    }
 
publicvoid Debug(Object message, Exception exception)
    {
    }
 
publicvoid Debug(Object message)
    {
    }
 
publicvoid DebugFormat(String format, params Object[] args)
    {
    }
 
publicvoid Error(Object message, Exception exception)
    {
    }
 
publicvoid Error(Object message)
    {
    }
 
publicvoid ErrorFormat(String format, params Object[] args)
    {
    }
 
publicvoid Fatal(Object message, Exception exception)
    {
    }
 
publicvoid Fatal(Object message)
    {
    }
 
publicvoid Info(Object message, Exception exception)
    {
    }
 
publicvoid Info(Object message)
    {
    }
 
publicvoid InfoFormat(String format, params Object[] args)
    {
    }
 
public Boolean IsDebugEnabled
    {
        get { returntrue; }
    }
 
public Boolean IsErrorEnabled
    {
        get { returntrue; }
    }
 
public Boolean IsFatalEnabled
    {
        get { returntrue; }
    }
 
public Boolean IsInfoEnabled
    {
        get { returntrue; }
    }
 
public Boolean IsWarnEnabled
    {
        get { returntrue; }
    }
 
publicvoid Warn(Object message, Exception exception)
    {
    }
 
publicvoid Warn(Object message)
    {
    }
 
publicvoid WarnFormat(String format, params Object[] args)
    {
    }
}

Remember, this is just a skeleton, do implement these methods anyway you like.

Now, all that is left is the registration:

LoggerProvider.SetLoggersFactory(new CustomLoggerFactory());

And NHibernate will start logging using your logger!

PS - Issue NH-3776 is an attempt to make using logger factories even simpler and in a similar fashion to other pluggable features.

MVP Showcase 2015

$
0
0

(This post is in Portuguese and in English)

As I mentioned earlier, the Portuguese MVPs are organizing the MVP Showcase 2015 event, this Wednesday, April 22nd, in Lisbon, at Microsoft's premises.

I will be presenting on Entity Framework 7, and the slide deck will be available here after the event. Besides myself, the other presenters will be:

The keynote will come from Cristina Gonzalez Herrero (@crisgherrero), the head of the MVP program for Portugal, Spain and Italy.

Looking forward to seeing you all there!


Como disse antes, os MVPs portugueses estão a organizar o evento MVP Showcase 2015, na próxima quarta-feira, 22 de Abril, em Lisboa, nas instalações da Microsoft.

Eu vou fazer uma apresentação sobre o Entity Framework 7, e os slides irão estar disponíveis aqui após o evento. Além de mim, os outros apresentadores serão:

A apresentação será feita pela Cristina Gonzalez Herrero (@crisgherrero), a responsável do programa MVP para Portugal, Espanha e Itália.

Espero ver-vos todos por lá!

MVP Showcase 2015 – Wrap Up

$
0
0

(This post is in portuguese and english)

Well, the MVP Showcase 2015 event is over! After all the excitement, it’s nice to calm down, but I am already missing all these extraordinarily gifted people and all the technical hype! Smile

I couldn’t attend all the sessions that I wanted, because there were always two in parallel, but I must say that I was very impressed with the overall quality of the presentations! Well done, guys!

For those who might be interested, here are the slides for my presentation, “Entity Framework 7: NoORM” (in english). As always, I’d love to hear your feedback!

Once again, thanks to all our sponsors, and to all attended the event!


Bem, o MVP Showcase 2015 acabou! Depois de toda a excitação, é bom ter um bocado de sossego, mas já estou a sentir saudades de toda aquela gente tão extraordinariamente dotada e de toda a envolvente técnica! Smile

Não pude assistir a todas as sessões que gostaria, porque havia sempre duas em simultâneo, mas devo dizer que fiquei muito impressionado com a qualidade geral das apresentações! Bom trabalho, pessoal!

Para aqueles que possam estar interessados, aqui estão os slides da minha apresentação, “Entity Framework 7: NoORM” (em inglês). Como sempre, adorava ouvir o vosso feedback!

Mais uma vez, o meu obrigado aos nossos patrocinadores, e a todos os que assistiram ao evento!

Silverlight DynamicResource

$
0
0

This will be my first post on Silverlight!

WPF offers two markup extensions, StaticResource and DynamicResource, that can be used to set property values from items in resource dictionaries.

The difference between the two can be summarized as:

  • StaticResource is evaluated at the start of the application, and will find resources defined before its actual usage;
  • DynamicResource is evaluated at a later point, and will find resources declared anywhere, before or after its usage.

Unfortunately, Silverlight does not include DynamicResource, but it is relatively easy to achieve something like that; that is the purpose of this post.

Check out the following code:

publicclass DynamicResource : MarkupExtension
{
public DynamicResource()
    {
    }
 
public String ResourceName { get; set; }
 
publicoverride Object ProvideValue(IServiceProvider serviceProvider)
    {
        var provideValueTarget = serviceProvider.GetService<IProvideValueTarget>();
        var target = provideValueTarget.TargetObject as FrameworkElement;
        var property = provideValueTarget.TargetProperty as PropertyInfo;
 
if (target != null)
        {
            RoutedEventHandler handler = null;
            handler = (sender, e) =>
            {
                var elm = sender as FrameworkElement;
 
if (elm != null)
                {
                    var resource = TryFindResource(elm, this.ResourceName);
                    var typeConverterAttribute = property.GetCustomAttributes(typeof(TypeConverterAttribute), true).OfType<TypeConverterAttribute>().SingleOrDefault() ?? property.PropertyType.GetCustomAttributes(typeof(TypeConverterAttribute), true).OfType<TypeConverterAttribute>().SingleOrDefault();
 
if (typeConverterAttribute != null)
                    {
                        var typeConverterType = Type.GetType(typeConverterAttribute.ConverterTypeName, false);
 
if (typeConverterType != null)
                        {
                            var typeConverter = Activator.CreateInstance(typeConverterType) as TypeConverter;
 
if (typeConverter != null)
                            {
                                resource = typeConverter.ConvertFrom(resource);
                            }
                        }
                    }
 
                    property.SetValue(sender, resource, null);
                }
 
                target.Loaded -= handler;
            };
 
            target.Loaded += handler;
        }
 
return (property.PropertyType.IsClass == true) ? null : Activator.CreateInstance(property.PropertyType);
    }
 
privatestatic Object TryFindResource(FrameworkElement element, Object resourceKey)
    {
        var currentElement = element;
 
while (currentElement != null)
        {
            var resource = currentElement.Resources[resourceKey];
if (resource != null)
            {
return resource;
            }
 
            currentElement = currentElement.Parent as FrameworkElement;
        }
 
return Application.Current.Resources[resourceKey];
    }
}

I won't go into details on markup extensions and all that, but basically, this one hooks to the Loaded event of the FrameworkElement, thus deferring the setting of the property. The property and the target are found through the IProvideValueTarget instance and the resource is looked up recursively from the target element up to the Application instance. If the property to be set, or its class, defines a type converter, it will try to convert the found resource to the proper type.  In the meantime, it just returns the default value of the property type, null or a default instance, in case of a value type.

Viewing all 404 articles
Browse latest View live