Some Notes on HTC files

I have only just come across htc files over the last couple of days (Hyper Text Components). These are essentially controls that extend the DOM for a page. The controls must be referenced in container – which has a style attribute set to e.g. “BEHAVIOR:url(webservice.htc)”.

I used a htc file in calling a webservice via JavaScript. Note that in the example I looked into, the webservice.htc file was a standard Microsoft script. The htc file for webservice calls seems to be based on the Microsoft.XMLHTTP ActiveX object.

Note that general, two functions need to be used when using the ht component – 1. to start the call to the webservice / instantiate the htc stuff and 2. a callback function that processes the returned information.

The reason for looking into htc files is that they seemed to correctly pass credentials through to the webservice (there were perms problems with ntlm auth when trying to call the webservice using simpler ajax stuff – as credentials seemed to be passed through as plain text).

Note that I believe that these only work in IE >5.

<script>
function DoWebServiceCall(id)
{
    var serviceReturn;
    //Set up the service call and set to async.
    document.all("divWS").useService("http://localhost/webservice.asmx?WSDL", "WebServiceMethodName");
    document.all("divWS").WebServiceMethodName.async = false;
    serviceReturn = document.all("divWS").WebServiceMethodName.callService(WebServiceCallback,"WebServiceMethodName", id);
}
function WebServiceCallback(result)
{
    if(result.error)
    {
        var xfaultcode   = result.errorDetail.code;
        var xfaultstring = result.errorDetail.string;
        var xfaultsoap   = result.errorDetail.raw;
        alert("ERROR:" + " c=" + xfaultcode + " s=" + xfaultstring + " soap=" + xfaultsoap);
    }
    else
    {
        document.getElementById("resultDiv").innerHTML = result.value;
    }
}
</script>
<div id="resultDiv">
  Results will be shown in here
</div>
<div id="divWS" style="BEHAVIOR: url(/_layouts/1033/webservice.htc)"></div>

Html Emails

Its been a little while since I played around a lot with html emails – I tried to set up a page in divs, but it turned out that for compliance, the layout still needs to be set out in a table (esp when viewed in outlook / hotmail). Man – I should read up on this stuff again as I’ve totally forgot a lot of it.

Some CSS Hacks

When constructing websites, there are a lot of gotchas in getting sites to work on a wide range of browsers. Below are some css hacks:

 

Minheight hack

Fixing min height in IE and firefox. This allows you to specify the minimum height of a block element. Insert relevant code into appropriate style element.

  min-height: 180px;
  height: auto !important;
  height: 180px;

Centering a div

To center a div within a page to work in all browsers, you need to add the following style attributes:

  text-align: center;
  margin: 0 auto;

Centering a table

You can center a table by adding an align=”center” however this may not work in all browsers. I prefer to keep all styling and position in a stylesheet, so to center a table using css, use the following: (note the table is belongs to a class name centered-table, you may also want to chuck “text-align: center;” in the css for a good measure).

table.centered-table {
   margin-left: auto;
   margin-right: auto;
}

General C# Learning Notes and Reminders

Below are some points I noted down when learning C#. As my memory is like a sieve, I though I should post them online!

C# Error Handling

Some notes on errors and exceptions. This is all bread and butter C#, but I thought id just blog some old notes from my first days of learning the language.

  • Separates the error handling logic from the main programming logic
  • Removes the need for error codes / flags to be passed around / global error flag
  • Try catch statements can be nested – the error will be caught by the closest nested catch statements.
  • Note that all of the standard exceptions are part of the System namespace.
  • Can use multiple catch handlers

Example
try
{
// Run some code here
}
catch (DivideByZeroException ex)
{
// Handle DivideByZeroException
}
catch (FormatException ex)
{
// Handle format exception
}
catch (Exception ex)
{
// general catch handler - fall through for any exceptions not previously caught
// Note that don't even need to specify (Expectation ex) in catch declaration if
// your not going to do anything with the actual exception object
}
finally
{
// Finally code - executes regardless of whether an exception was thrown or not
}

Throwing Exceptions
Examples (all have various overloads)…
throw new Exception(“An error message”);
throw new ArguementOutOfRangeException(“out of range”);
throw new FormatException(“Invalid Format”);

Checked / unchecked keywords
These are only relevant for integer arithmetic – to check for overflow etc

  • checked keyword – used around integers where exceptions will cause break
  • unchecked keyword – opposite as above

You can either wrap a code block with the checked / unchecked keyword using braces, or wrap an expression in brackets (ie using it as an operator – unchecked(expression) ).

Using keyword

The using keyword has various different meanings in C#. The first one is for namespace inclusion. It can also be used to scope variables e.g.
using console = System.Console; console.writeLine("Hello World");
It can also be used to specify the scope of a variable within a method e.g.:
using (WinForm our_Form = new WinForm())
{
    Application.Run(our_Form);
}

As keyword – effectively the same as casting:

Attempts to cast – returns null if fails – casting with brackets would throw an exception instead

Enums

enum day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}
Integer values are associated with enums. Numbering starts at 0, however can changed this eg
enum day {Monday=1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}
Can cast: (int)day.Tuesday; // returns 2.
Can also do enum day {Monday, WorstDay=Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}
Note that you can choose an enumeration type as well
enum day : byte {Monday, WorstDay=Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}
To call an enumeration
day firstDay = day.Monday;

GUIDS

Guids are Globally Unique Identifiers generated by Windows (numbers are 128 bits). These unique codes are used to uniquely identify stuff (eg records, files etc).
To create a guid simply do
Guid test = new Guid();
If you know a guid as a string, and you need a guid type in code, use the following constructor overload Guid test = new Guid(string guidId);
This can be really useful in sharepoint e.g. SPList list = SPWeb.Lists[test];

Compile directives

Conditional compilation – ive never used these (as yet) but thought id note down a couple of links for future reference.
http://www.csharphelp.com/archives/archive36.html
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfpreprocessordirectives.asp
I think these are used with switches on the compiler.

Reference / Value types

Value type
The variable holds the actual value. Primative data types such as int, char structs and enums are value types.
Reference type
Class types are reference types. A reference type varaible holds a reference to an object and not the actual object. Copying a reference variable does not make an actual copy of the data, it simply creates another reference to the data
Ref Keyword
Used to pass a reference to a variable into a method instead of the actual variable. If the actual variable was passed, a copy of that variable would be made which is local to that method (providing that the variable is a value type).
Note that if a reference type is passed to the method (eg an object), there is no point in using the ref keyword). The use of this is to ensure that any changes made to the variable referenced persist after the method has executed.
out keyword
This is essentially the same as the ref keyword, however it requires that the variable referenced must be set / updated the value that is referenced
Stack
Value types are stored on the stack. These are primitive data types such as int, char etc. These only exist for as long as the remain in scope. Note that I believe that actual references to objects are held on the stack.
Heap
Variables that are referenced (eg via ref, out or new keywords) are stored on the heap (objects etc). These continue to exist after the method referencing them is finished executed. They are only deleted when they are not referenced from anywhere (by C# disposal).
Boxing
If you reference an primitive type, the value of that primitive type is copied from the stack to the heap. Note that this mean that when you update the item on the stack, the item in the heap isnt updated and viceversa.
Unboxing
If you have a reference to an object that can be cast to a primitive type, casting will copy the value of the object to the primitive data type variable. Note that this mean that when you update the item on the stack, the item in the heap isnt updated and viceversa.

Structs

  • A struct type is a value type and not a reference type (such as a class).
  • A struct can have its own fields, methods and constructors
  • You cannot declare a default constructor (one with no params) – the compiler always writes one.
  • Note that if you dont intialise a variable in a class constructor, you will not be able to access it (a class would set uninitialised variables to 0, null or false).
  • Note that you cant initialise a struct member variable when you declare it.

struct Date
{
    private int _day, _month, _year;
    public Date(int  day, int month, int year) 
    {    
        _day = day;
        _month = month;
        _year = year; 
    }


Xml reading and writing and XPath

Rather than talking about xml and xpath, here is some example code…
using System.Xml;
// Load xml doc
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(pathToXmlFile);
// Get the table where name node innertext is equal to tableName
string xPath = string.Format("//settings/tables/table/name[. ='{0}']", tableName);
XmlNode tableXml = xmlDoc.SelectSingleNode(xPath).ParentNode;
if (tableXml != null)
{
    XmlNodeList fields = tableXml.SelectNodes("fields/field/name");
    foreach (XmlNode tableName in field)
    {
        Console.WriteLine(tableName.InnerText);
    }    
}
// To get a single value do
string connStr = xmlDoc.SelectSingleNode("/settings/databaseConnectionString").InnerText;
Console.WriteLine(connStr);
// Note, to do a where clause on an attribute, (Where attribute id=1 and type=b or c do 
xmlDoc.selectNodes("//settings/tables[@id='1' and (@type='B' or @type='C')]")

This is a pretty good article on xpath where clauses: http://www.eggheadcafe.com/articles/20030627d.asp

Indexers

Indexers are used to allow the properties of a class to be accessed using array like syntax (eg in Sharepoint SPListItem[“internalName”] to get the value of an internal name).
public class testClass
{
    string[] test = new string[]{"test1", "test2", "test3"};
    public int this[int index]
    {
        get
        {
            return test[index];
        }
        set 
        {
            test[index] = value;
        }
    }
}

Note that indexers can be specified in an interface e.g.
interface IExample
{
   int this[int index]{ get; set;}
}


Delegates and Events

A delegate can be thought of as a smart method, similar to thinking of properties as smart fields.
Delegates generally seem to be declared outside of a class, e.g.
delegate void DoSomething(int someParam);
Subsequent classes then implement Tick. A method must jsut have the same signature as tick, e.g.
void AnImplementationOfDoingSomething(int someParam)
{
   ...do something
}
You can pass the delegate method through as a method param to a method - eg
void Example(DoSomething param, int anotherParam)
{
    DoSomething(anotherParam);  // Call DoSomethingMethod
}

Events
To attach a delegate to an event anObject.anEvent += new MethodToExecute(param);
To detach a delegate to an event anObject.anEvent -= new MethodToExecute(param);
To raise an event
public event ActionHandler EventName;
private void Raise()
{
    if (EventName != null)
    {
        EventName();
    }
}

Other Notes

  • chars are denoted by single quotes – eg ‘:’ string are denoted by double quotes – eg “:” would be a string