Tuesday 25 November 2008

F# - Tutorial 1 - Getting Started and Hello World


recently i have been looking into F#, a rich and purely functional programming language now supported by the .NET framework and developed within the MS research centre.
F# is based on older functional languages such as: Haskell and OCML. Haskell Curry is an infamous mathematician and logistician and this is where the roots of this language originate from...

F# can be run as a standard installer from the research centre website.. or it can be integrated into Visual Studio 2008 by downloading the MSI installer. The latest release is "September 2008 CTP"

Lets have a little look at a simple Hello World application...


//------------------[F# Code]------------------
(*
 
(c) Sean G @ TutorialGenius.com 2008.
 
This sample Hello World application is the keyhole to many F# adventures. Like many other languages, the foundations begin with a Hello World example!
 
*)
 
// Set the compilation warning to light mode; pronounced: "Hash Light".
#light
 
// Output Hello World!
System.Console.WriteLine("Hello World")
 
// Stop console from closing
System.Console.ReadKey(true)

Friday 31 October 2008

An easy 30KB ISO Mounter


Virtual CD-ROM Control Panel Download


Instructions
=========================
1. Copy VCdRom.sys to your %systemroot%system32drivers folder.
2. Execute VCdControlTool.exe
3. Click "Driver control"
4. If the "Install Driver" button is available, click it. Navigate to the %systemroot%system32drivers folder, select VCdRom.sys, and click Open.
5. Click "Start"
6. Click OK
7. Click "Add Drive" to add a drive to the drive list. Ensure that the drive added is not a local drive. If it is, continue to click "Add Drive" until an unused drive letter is available.
8. Select an unused drive letter from the drive list and click "Mount".
9. Navigate to the image file
, select it, and click "OK". UNC naming conventions should not be used, however mapped network drives should be OK.

You may now use the drive letter as if it were a local CD-ROM device. When you are finished you may unmount, stop, and remove the driver from memory using the driver control.

Wednesday 29 October 2008

C# - Generating Strong Typed Datasets


Over the past few weeks I have been working with Strong Typed Datasets in C# to parse XML content easily and more efficiently.

If you've ever had an Xml file and struggled to flawlessly parse it without errors, and write it back (using System.Xml namespace objects like: XMLReader or XmlDocument) then you should take a look at Strong typed Datasets.

If you've worked with Datasets, then this should come naturally. The idea is, once the XML content has been parsed into the Dataset, we can access the data through column and row information within the Dataset.

Heres how we go about it...

1. Find the "xsd.exe" tool. This is shipped with all versions of Visual Studio or can be downloaded from Microsoft's download center. This will allow us to create an XSD and .cs file for our Xml File.
2. Ensure your Xml File is valid Xml.
3. Use the xsd.exe tool to create the XSD and .cs from your xml by command line.

xsd.exe .xml - This will generate the schema (XSD) based on the XML File.
xsd.exe .xsd /d - This will generate the .cs based on the schema (XSD).


Heres a batch script to automate this process...

@echo off
 
:BEGIN
 
CLS
 
COLOR A
 
REM --- Get XML file name.
echo "What is the Path/Name of the XML file (excluding '.xml'): "
set /p XMlFile=
echo.
echo.
echo "Generating XSD Schema Definitions..."
xsd.exe %XMlFile%.xml
echo.
echo.
echo "Generating Strongly Typed DataSet file..."
xsd.exe %XMlFile%.xsd /d
echo.
echo.
echo "Strongly Typed DataSet Created Successfully!"
echo.
 
PAUSE


4. Add these 3 files to your C# project. You will notice the class name in the .cs file derives its name from the main tag within your xml. Don't forget to add the namepsace if applicable!
If you have done this corrently, you will notice the class inherits the DataSet class: "global::System.Data.DataSet" .

5. Create a new instance of the class, then call the "ReadXml()" method, specifiying the path to the XML file as a string. This will parse your XML file and popualte the Dataset. As the class was generated from the XSD, the template should match up!

6. You may also note that the instance you've created in step (5) contains accessors (one for each child note of your xml!)... Each of these has a "Rows" accessor, which will return a DataRowCollection object. If we run a loop on this collection, we will be able to extract the information!


If the "ReadXml()" function fails, you may need to re-structure your XML. The erros are quite self-explanatory, but generally this will fail due to an XML parser error.

Sean

Thursday 23 October 2008

New Blog!!


All the posts below have been migrated from the TutorialGenius.com Tips feed.

The tips feed has now been deprecated and replaced with this blog. It just saves lots of time developing a new manageable blog with a nice GUI!

Installing the same .NET component twice, side by side


If you've ever needed to install the same product (wether its a web service or a DLL) on the same machine, twice! then here is a rought guide on how its performed...

If you notice, when you install an MSI or any DLL onto a system, and this component already exists, you will usually be asked wether to upgrade or remove the currently installed copmponent.

To get around this, we can edit the MSI installer and set the [RemovePreviousVersions] property to False... then set the grey box next to the [ProductCode] property, and generate a new code... this will give your component a new GUID (Global unique ID) and then the system will treat these as two seperate components.

This can also be performed in VS6.0 using a different method!

Make the internet control work with IE7


Heres a simple solution.

Close VB.
Open regedit.

Go to the "HKEY_CLASSES_ROOTTypeLib{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}1.1win32" branch and change the default value from
"C:WINDOWSsystem32ieframe.dll1" to
"C:WINDOWSsystem32ieframe.dll"

this will allow you to use the internet control again!

XAMPP! - PHP, MYSQL, Pear for Windows!


http://www.apachefriends.org/en/xampp-windows.html

this makes life a LOT easier for installing these tools on a windows machine.

The web services enumeration components are not available - Fix


In Visual Studio, if you are attempting to update your web references (Generate a new proxy stub for your web service)... you may come across this error...

"The web services enumeration components are not available!.

you may need to install Visual Studio, but try this first....

devenv /resetskippkgs

It clears some optinos that may have been currupted and clears all SkopLoading tags.

Reference: http://msdn.microsoft.com/en-us/library/ms241276(VS.80).aspx

Deny access to IP Addresses


If you've developed an Admin ASP.NET application, or even PHP (for instance) which manages users and roles within your application, you may want to deny access to certain users and/or roles when it comes to accessing this application.

This can be achieved in web.config, but if this application is located on a remote server, you may want to deny access to all users apart from localhost. IIS allows you to set this configuration.

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/a629438c-45f5-4b6d-a131-87253ae9dc87.mspx?mfr=true

A Better .NET BackGroundWorker!


have you ever wanted a better background worker control for your .NET projects?
Check this out, it currently supports VB.NET and C#.NET and resolves some of the issue currently emcompassed by the default worker.

http://weblogs.asp.net/rosherove/pages/BackgroundWorkerEx.aspx

Tracking TODO's in Visual Studio 2005


Start by going to the menu bar and selecting 'View' then 'Task List', when the windows appears, notice you can select a drop down box that has two options:
'User Tasks' by default and then comments. If you select 'comments', it will list all comments, the location and line number where you have written the comment prefixed with TODO:

So just write...

//TODO: Test  (C#)

or
'TODO: Test   (VB.NET)


in any document and have a look for yourself!

Logoff Users remotely within a Windows 2003 server session


Heres a tool called PsTools. It allows you to do such a thing...

http://kodethoughts.blogspot.com/2006/12/kill-remote-user-session-remotely.html


Heres a batch file i use quite ofter to utilise this tool...

@echo off
 
:BEGIN
 
CLS
 
COLOR A
 
echo "Enter Username (i.e. sean): "
set /p UserName=
 
echo "Enter Password: "
set /p PassWord=
 
echo "Enter Server Name (i.e. server1): "
set /p Server=
 
echo "Commands.... qwinsta - List all logged in users."
echo "Commands.... logoff [UserID] /v - To logoff a user..."
 
REM - Run psexec util
psexec \\%Server% -u DOMAIN\%UserName% -p %PassWord% cmd
 
REM - Get current logged in users...
REM - qwinsta
 
REM - echo "Enter a UserID to Logoff: "
REM - set /p UserID=
 
REM - Logoff user...
REM - logoff %UserID% /v
 
:END

Accessing Settings.settings properties


Simply use the Properties namespace.

Properties.Settings.Default.[Property Name]


to access any properties set within the settings file.

Allow remote access to .NET Web Service


When accessing a .NET webservice remotely, you may receive a message stating:
"You can only access this resource from its localhost.".

To resolve this, you will need to add permissions for external users to access the service over certain protocols.

Add the following to the web.config file of the web service...

<configuration>
    <system.web>
    <webservices>
        <protocols>
            <add name="HttpGet">
            <add name="HttpPost">
        </protocols>
    </webservices>
    </system.web>
</configuration>


This will allow access via. GET and POST. You may require SOAP here if you are not accessing via. GET or POST.

Sean

Installer Compile: An error occurred while validating. HRESULT = '80004005'


Have you ever received the message "An error occurred while validating. HRESULT = '80004005'" when attempting a compile an installer within .NET? You'll also notice that .NET provides very little information as a means to resolve this issue.

The issue is based around project dependencies. When you add a project output to an installer, you'll notice the installer automatically retrieves its dependencies (External DLLs, project references etc.). There may be a time when you remove a project from the solution, or re-locate them, by which, they can no longer be found or referenced in this case.

When compiling the project, we usually receive an error stating a project or reference cannot be found. However, when compiling an installer, we would expect to see "One or more of a project outputs project reference/s cannot be found..", however, in this case, we see "An error occurred while validating. HRESULT = '80004005'".

Hope this helps!

.NET Web Services - Parser Error Fix


Have you ever received this message? It usually displays when a web service has been installed using an installer (MSI) - This is ensuring your name spaces are correct however!

----------------------------------------------------------------------
Parser Error
Description: An error occurred during the parsing of a resource required to
service this request. Please review the following specific parse error details
and modify your source file appropriately.

Parser Error Message: Could not create type 'Namespace.ProjectName.Class'.

Source Error:


Line 1: <%@ WebService Language="C#" CodeBehind="Class.asmx.cs"
Class="Namespace.ProjectName.Class" %>
----------------------------------------------------------------------

Im not 100% sure this is a guaranteed bug (Occurs within VS 2005), but there is a workaround.

1. When generating your installer, its usually common to right click the Installer in the Solution Explorer and Select: "Add > Project Output...". You can then select the relevant projects and outputs required.

2. Once this has been done, double click one of the project outputs in solution explorer, and you'll see the directory structure upon where the installer will install certain information to.

3. If you are experiencing this issue, you will see project output files (Content files and Primary Output) finding their presence within the root directory of the web application! This is not what we want, and this is why we are getting the Parser Error, because its trying to find the associated web service class within the bin folder.

4. To resolve, simply delete the "Primary Output" output, and re-add this output within the bin folder. This can be achieved by navigating within the bin folder, right clicking, and adding the project output again.

5. Ensure the "Content Files" project output remains within the web applications root directory. This is usually the default.

Form Creation and BackgroundWorker processes


When a form is loaded/created... there are many events which take place throughout its creation phase.

Have you ever been in a position where you want something to trigger as soon as the application opens? Im sure you all have, in which case, code is placed within the 'Load' event handler for the associated form object. However, this event is triggered before the actual form is rendered to the user. What if we want the form to physically load (paint) before events are triggered?

We then could use the "Shown" event of the form object... once the form is 'shown' to the user, we can then perform some actions. This is also quite useful, but if your form contains many complex controls and images, then you might see a form which has been "half-generated" before the application starts (this would be useless if this form was, for example, a splashscreen").

We then look into "BackgroundWorker" objects. When dealing with .NET windows forms, these objects are available to us within the toolbar. Simply drag one onto your form and give it a name...

BackgroundWorker objects, in their simplest, are threads running alongside our main thread to process information (Mainly GUI creation) in the background. This allows the form to load and display its information fluently while the background processes are carried out on a seperate thread in the background.

To use this feature, we need to do the following:
1. override the events available from the control.
These are:
"DoWork" - This is triggered first and contains the 'work' to take place. This
could be a call to a function which contains web service consumption and other
means.
"ReportProgress" - This allows us to report progress back to the user.
"RunWorkerCompleted" - This event triggers when the 'work' has finished.

The "ReportProgress" event is useful if we wish to use a status bar of the progress, but generally, we only need the following 2 events...

this.bkWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(bkWorker_DoWork);
this.bkWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(bkWorker_RunWorkerCompleted);


To trigger the DoWork event, we call the "RunWorkerAsync()" function of the BackgroundWorker object. If we wish to pass parameters, we can retrieve them in
the DoWork event by referencing the DoWorkEventArgs parameter.

The DoWorkEventArgs parameter allows us to control and pass information between the worker object and the main windows form. e.Argument (Where e is a reference to the DoWorkEventArgs object) is used to retrieve the passed parameter. We can then store results within the e.Result data member.

e.Result can then be retrieved when the RunWorkerCompleted event is triggered and the GUI can be updated appropriately.

Note: We must not reference the form within the "DoWork" event. This is merely for processing only. We can however utilise the GUI objects from the main thread within the other events. This is why we use DoWorkEventArgs to store result information.

Triggering code depending on build type


In C#.NET we have 2 common build modes: Debug and Release. We use Debug to test the code (I.e. insert breakpoints, step through code) which generates our .PDB files (These contain debug symbols used by the compiler. However, in Release mode, we do not have these debug symbols as when we deliver a product it its user, they have nothing to do with the way the code is tested.

If we have two sets of data, I.e. two databases... one for our test environment and one for our live environment, we can make life easier by using the following code snippet to establish which database to use, depending upon the build type!

#if RELEASE
// Use release database here
#else
// Use test database here
#endif


(RELEASE can also be switched to DEBUG for the reverse effect).

When the build method is changed within VS.NET, the relevant code (for its build type) is highlighted and the code un-used is grayed out.

"The path is not of a legal form" designer error


If you ever come across the infamous "The path is not of a legal form" error which prevents you from viewing components in design view (but still build and function correctly at run time) then check your references!

The best thing to do is:
1. Right click the solution and execute the "Batch Build" command.
2. Select all projects and clean them.
3. Select all projects and do a build. This will highlight any 'bad' project
references.

You can then either choose to remove these references or re-reference them.

Your design view will then function correctly.

Validating an XML file against its Schema (XSD)


string strXmlFile;
string strXsdFile;
XmlDocument xmlDoc = null;
 
// Retrieve XML and XSD files from the locations specified in the Settings file.
strXmlFile = Properties.Settings.Default.XMLLocation;
strXsdFile = Properties.Settings.Default.XSDLocation;
 
 
try
{
    // Load XML data into a new XMLDocument
    xmlDoc = new XmlDocument();
    xmlDoc.Load(strXmlFile);
 
    // Validate the XML document against the Schema.
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
 
    settings.Schemas.Add("http://www.w3.org/2001/Messages.xsd", strXsdFile);
 
    XmlReader objXmlReader = XmlReader.Create(strXmlFile, settings);
 
    while (objXmlReader.Read()) { }
}
catch (XmlSchemaValidationException XmlSchemaEx)
{
    //"Xml file didn't conform to the schema.";
}
catch (XmlException XmlEx)
{
    //"Invalid XML File Location.";
}



Note: The namespace with the schema's 'Add' Function must match the schema namespace in the file. In this instance (http://www.w3.org/2001/Messages.xsd).

Web Service Error: The request failed with HTTP status 401: Unauthorized.


Why do I get this error?

The reason for this error is that by default, a web service project in Visual Studio 2005 Beta 2 required NTLM authentication. When you call the web service from another application, the application tries to call into the web service with anonymous access and fails. But, when you call the web service from the web service test page in Internet Explorer, your credentials are passed from IE to the web service which means that the call succeeds.

How do I fix this error?
There are two ways to fix this error.

1. Disable NTLM Authentication in Project Properties. If your web service is not intended to require authentication, the easiest way to fix this error is to turn off NTML authentication in a web service project.
To do this, right click on the web service project and select “Property Pages”.
On the “Start Options” page, uncheckNTLM Authentication”. NOTE: disabling this
option has security implications if you are running the web service in a
Terminal Server environment. If the web service is on your local machine and
it’s not being used in a Terminal Server environment, then you should be fine.

2. Pass User's Credentials from Calling Application to Web Service
If your web service is intended to require authentication and not anonymous
access, then pass the credentials of the user from the application to the web
service. Here is an example:
Samples.TimeWebService ws = new Samples.TimeWebService();
ws.Credentials = System.Net.CredentialCache.DefaultCredentials;
string currentTime = ws.GetCurrentTime();



If all of these steps fail, ensure "aspnet" (For .NET requests), "IUSR" (for most requests) and "IIS_WPG" (if running IIS 6.0) are allowed access to the folder of the service. "Everyone" could be tested up front to ensure its a user/group privileges issue.

SendMail with PHP


Heres a snippit ive used to send mail with PHP. Your mail server must be configured with your php installation, then your all set.


$EmailSubject = "Hello World Test";
$EmailFrom = "JoeBloggs@TutorialGenius.co.uk";
$EmailTo = "User@TutorialGenius.co.uk";
$Message = "Hi, I'm sending this quick E-Mail to test my PHP Mail functionality! Thanks TutorialGenius.com!";
 
 
$result = mail($EmailTo, $EmailSubject, $Message, "From: $EmailFrom");
 
 
if ($result == 1)
{
     echo "Mail sent sucessfully!";
}
else
{
     echo "There was an error sending the mail.";
} 

Force Download via. HTTP Headers


I've been playing a little with php headers recently, and if you've ever wanted to force a downloaded via. HTTP without reading the 14563 page specification document, then check this out.

 header('Content-type: application/zip');
 header('Content-Disposition: attachment; filename="File.zip"');
 readfile('File.zip');


Content-type - Defines what the browser is expecting to serve as content
Content-Disposition - Specifies the type and filename of the download.
readfile - basically sends the content to the output buffer and forces a download dialog.

have fun!

Parsing XML Escape Charcters


Here is some C# code i've used in the past to make any piece of text XML safe, and vice-versa. The logic applies across all languages. Remember to escape & first!

private string outputParseFields(string field)
{
    // Escape illegal chars. (escape '&' first!)
    field = field.Replace("&", "&");
    field = field.Replace("<", "<");
    field = field.Replace(">", ">");
    field = field.Replace("'", "'");
    field = field.Replace("\"", """);
 
    return (field);
}
 
private string inputParseFields(string field)
{
    // Escape illegal chars. (escape '&' first!)
    field = field.Replace("&", "&");
    field = field.Replace("<", "<");
    field = field.Replace(">", ">");
    field = field.Replace("'", "'");
    field = field.Replace(""", "\"");
 
    return (field);
} 

Referencing HTML tags from code-behind


In many instance of developing performant ASP.NET applications, you will require the need to reference standard HTML tags from code-behind. You may notice that if you associate an ID to a HTML tag, you still cannot control this from code behind.

The understanding behind this is quite simple. HTML tags are client-side controls, not server-side. Therefore, they are purely rendered by the users browser and no server processing is executed upon them. The code-behind view details events for server-side components only.

Therefore it becomes obvious that we need to make our tag a server-side component. To do this, we follow these steps:

1. Alter your HTML tag by giving it an ID (so we can reference it from the code-behind) and tell it to run at the server. I.e.

2. Browse the object library to find out what library this HTML tag belongs to. A 'div' tag for example would be a 'HtmlGenericControl' object. We therefore define this publicly in our code behind file (using the ID as before). I.e. public HtmlGenericControl test;

3. We can then use the methods of the 'HtmlGenericControl' object to control the DIV tag. A popular method would be: display.InnerHtml = "Hello World"

Sean

nVelocity


I've recently been looking at nVelocity. it's quite a nice template library (originally ported from Apache's Velocity - but for .NET). Templates are stored within .vm files and follow a pseudo-code formatting standard. Ive found that by using nVelocity, it enabled the following advantages:

1. Alterations can be made to the template for a piece of software without modification to the source code itself.
2. The template files are pseudo code and quite easy to understand. A user with minimalist knowledge would be able to alter these without a huge developer training overhead.
3. Templates can be switched easily and multiple templates can be adopted as required.

If you like this templating ideology, visit the website here: http://nvelocity.sourceforge.net

its free and open source!

Explanation of Managed Code


Managed code is code that has its execution managed by the .NET Framework Common Language Runtime. It refers to a contract of cooperation between natively executing code and the runtime. This contract specifies that at any point of execution, the runtime may stop an executing CPU and retrieve information specific to the current CPU instruction address. Information that must be query-able generally pertains to runtime state, such as register or stack memory contents.

The necessary information is encoded in an Intermediate Language (IL) and associated metadata, or symbolic information that describes all of the entry points and the constructs exposed in the IL (e.g., methods, properties) and their characteristics. The Common Language Infrastructure (CLI) Standard (which the CLR is the primary commercial implementation) describes how the information is to be encoded, and programming languages that target the runtime emit the correct encoding. All a developer has to know is that any of the languages that target the runtime produce managed code emitted as PE files that contain IL and metadata. And there are many such languages to choose from, since there are nearly 20 different languages provided by third parties – everything from COBOL to Camel – in addition to C#, J#, VB .Net, Jscript .Net, and C++ from Microsoft.

Before the code is run, the IL is compiled into native executable code. And, since this compilation happens by the managed execution environment (or, more correctly, by a runtime-aware compiler that knows how to target the managed execution environment), the managed execution environment can make guarantees about what the code is going to do. It can insert traps and appropriate garbage collection hooks, exception handling, type safety, array bounds and index checking, and so forth. For example, such a compiler makes sure to lay out stack frames and everything just right so that the garbage collector can run in the background on a separate thread, constantly walking the active call stack, finding all the roots, chasing down all the live objects. In addition because the IL has a notion of type safety the execution engine will maintain the guarantee of type safety eliminating a whole class of programming mistakes that often lead to security holes.

Contrast this to the unmanaged world: Unmanaged executable files are basically a binary image, x86 code, loaded into memory. The program counter gets put there and that’s the last the OS knows. There are protections in place around memory management and port I/O and so forth, but the system doesn’t actually know what the application is doing. Therefore, it can’t make any guarantees about what happens when the application runs.

Setting up SQL Server 2005 on Windows XP


Having avoided enpensive hosting options so far, I decided to setup SQL Server 2005 at home on my localhost box. heres a quick guide

regarding the installation of SQL Sevrer 2005 with GUI management.

Required SQL Server 2005 (the express edition is free and will do) SQL Server management studio express (GUI tool to config sql server 2005, saves bothing with nasty SQLCMD scripting) (Optional) SQL Server sample databases (these arent shipped with sql server by default) ... this file contains NorthWind and Pubs sample databases.

- All available for download at microsoft.com's download centre -

Install Order
1. Install SQL Server 2005
2. Install the GUI management tool
3. Open the GUI tool and login using windows authentication
4. (Optional) Run a new query, and insert the .SQL file from the sample Databases install. This will provide you with Northwind and Pubs

Next, we need SQL AUTHENTICATION enabled... right click your Server > Properties > Security tab.... change this to windows AND mixed mode

security (This will allow SQL Server Auth - No Need to reply on windows user accounts)

Next expand the northwind database, then its security folder.... right click the folder and add new user.... associate appropriate

permissions here. (This allows access for sql user accounts)

Next, we need to restart these windows sql server services for changes to take effect.... start > progs > sql server 2005 > configration

tools > config manager..... open your sql server instance (probably called SQLEXPRESS) you can stop and start the service from in here....

This is about it, good luck!

Sean

Motion Tweening


Motion tweening is a method used by many Flash Developers when designing animations within Flash. Motion tweening is a process where the computer works out the 'inbetween' processes based on a start point and an end point of an object.

For example, if you wanted to move a shape from the left hand side of the page to the right hand side, you only need to tell the compiler the position on the shape at the start, and the final position of the shape. Motion teen with calculate the rest. The speed at which motion tween operates depends upon how many frames you tween your animation over.