Discussion Locked

C# my biggest challenge

0 helpful
23 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
blog root

23 replies

by stefanprodan

UCL is a portable lossless data compression library written in ANSI C by Markus F.X.J. Oberhumer, it can be found on his site.  When I first tried the System.IO.Compression of the new 2.0 Framework I was not happy, the compression is ok with text input but nothing more. So in looking for a new compression algorithm beside #ziplib I?ve found oberhumer.com. I must say that for me it was a great thing the algorithms that oberhumer made are much faster and with a better compression ration then all free or commercial algorithms. I am not a C or C++ programmer but I can understand the logic, so I decided to make a C# Api, an interface between the C library and my .NET applications. For now I?ve used Ucl in a SOA project, with web services and windows services that are made for sql data replication. The data is archived and then encrypted with Ucl before sending it on the web. The Api is not fully done, still beta but with some help and free time I'll finish it. In my next posts I'll share some code and ideas.

by stefanprodan

Here it is a safe method based on the .NET Random class:

/// <summary>/// Secure Deletion method/// </summary>/// <param name="strFilename">/// the path of the file to be erased/// </param>/// <param name="nTimes">/// number of times to run the erase algorithm/// </param>

public static void EraseFile(string strFilename, int nTimes){    if (!File.Exists(strFilename))    {        throw new               ArgumentException("The file does not exist");    }    while (nTimes >= 0)    {        FileStream fs = File.OpenWrite(strFilename);        int nBytesInFile = (int)fs.Length;
        Random random = new Random();        Byte[] b = new Byte[nBytesInFile];        random.NextBytes(b);
        for (int i = 0; i < nBytesInFile; i++)        {            fs.WriteByte(b[i]);        }        fs.Close();
        nTimes--;    }}

This post originally appeared on an external website

by stefanprodan

Grasshopper

Mainsoft announced the release of "Grasshopper," a free Visual Studio .Net plug-in, which enables developers to create applications for Linux.
Grasshopper is a Visual Studio .NET plug-in, which enables you to use C# or Visual Basic .NET to develop cross-platform ASP.NET applications that run on Linux and any platform running Apache Tomcat.
This is something you must see :)

This post originally appeared on an external website

by stefanprodan

The zip file standard was too big for my project with to much data that I don't find useful, so I decided to do my own file. Here is the xml representation of the ucl archive structure:

<UclArchive> <ArchiveHeader size="11">  <magicNumbers size="2"></magicNumbers>  <uclAlgorithm size="1"></uclAlgorithm>  <compressionLevel size="1"></compressionLevel>  <encrypted size="1"></encrypted>  <encrytionAlgorithm size="1"></encrytionAlgorithm>  <checksumAlgorithm size="1"></checksumAlgorithm>  <filesIndex size="4"></filesIndex> </ArchiveHeader> <FILE multiplication="n">  <FileHeader size="8" extrasize="filename">   <fileIndex size="4"></fileIndex>   <fileNameSize size="4"></fileNameSize>   <fileName size="fileNameSize"></fileName>  </FileHeader>  <BLOC multiplication="n">   <BlocHeader size="8">    <originalSize size="4"></originalSize>    <compressedSize size="4"></compressedSize>   </BlocHeader>   <DATA></DATA>   <BlocFooter size="8"></BlocFooter>  </BLOC>  <FileFooter size="12">   <checksum size="4"></checksum>   <totalLenght size="8"></totalLenght>  </FileFooter> </FILE> <ArchiveFooter size="0"></ArchiveFooter></UclArchive>

This post originally appeared on an external website

by stefanprodan

using System.Management;
/// <summary>/// Returns the processor ID of the first/// CPU found on the machine/// </summary>

public static string CpuInfo(){ string cpuInfo =  String.Empty; ManagementClass managementClass =       new ManagementClass("Win32_Processor"); ManagementObjectCollection managementObjCol =       managementClass.GetInstances();
 foreach(ManagementObject managementObj in managementObjCol) {  if(cpuInfo==String.Empty)   {   cpuInfo =    managementObj.Properties["ProcessorId"].Value.ToString();  }     } return cpuInfo;}

This post originally appeared on an external website

by stefanprodan

It has past some time since I haven?t work on the ucl compression project. With the closure on C# 2005 release I?ve been doing a review of my code and decide what I should keep from the 1.1 aleph framework. UCL is for sure a project that I?ll need in the new environment due to the low performance of the new System.IO.Compresion from the 2.0 NET Framework.
Today I?ve stared to code a windows application named UCL Viewer. For now it can open an .ucl file and read the content files, list the size of each file and checksum. By the end of the week it will have more features like decompressing a chosen file, test the entire archive and maybe make sense of the folders.

This post originally appeared on an external website

by stefanprodan




UCL Compressor
Originally uploaded by Stefan Prodan.

First beta release is out of the box :) It can create a new ucl archive, append folders to it, extract files from folders, extract the whole content and the directory structure to a desired location, and check the CRC of the whole file.
All is done with VS.NET 2005 Beta 2 and I tell you its working great. Much more to do thaw. UCL Compressor Beta 2 will be build on the release version of the VS.NET 2005 and I'll try to upload some ware the setup for download.

This post originally appeared on an external website

by stefanprodan

One word on this "Software Isolated Processes" !

Lines from the channel9 forum:

In our world, we compile entire MSIL for the kernel into x86 instructions at installation time. There is no libc at the bottom. However, we do have around some assembly code. Like a kernel written in C, our C# kernel needs assembly code to handle the lowest part of the interrupt dispatch on the x86. But once the assembly code has finished, it dispatches directly into compiled C# (no C). BTW, there is some C code in the system, primarily for the debugger stub.

The MSIL to x86 compiler we use is Bartok, developed by Microsoft Research's Advanced Compiler Technology Group. David Tarditi and his team have created this fantastic whole-program optimizing compiler that reads in a collection of MSIL Assemblies and outputs an x86 binary. At the end of the day, its just code.

Remember that libc is just x86 code. So, we replace whatever one might need from libc, with C# code. Instead of calling a C version of libc, Singularity uses safe code written in C# to directly access the screen hardware (for example).

This probably makes more sense when you realizes the most OSes don't use BIOS except during the very earliest stage of boot. Singularity does the same as well, it only use BIOS during the 16-bit real-mode boot strap. Once jump to 32-bit mode, we never use BIOS again, but use device drivers written in C# instead. Yes, we had to replace a lot of CLR libraries with different code. However, unlike the CLR, the Singularity runtime is written in C#.

We use the Bartok compiler and runtime from the ACT group in MSR (http://research.microsoft.com/act/). It is a highly optimizing compiler that compilers MSIL down to x86 code. It comes with a runtime system written entirely in C#--though parts of it, most notably the garbage collector (GC) are unsafe C#. (It is an open research challenge to write a real GC in a type-safe language.)

Bartok is a very high quality compiler that produces good code, but it is a research prototype. It doesn't handle exactly the same language as MS's product compilers (e.g. no reflection) and isn't ready for widespread use. Don't ask when it will be shipped, since it isn't going to be. If you wonder why, say "research prototype" 10 times fast and you'll have the reason.

A couple things to note. Everything in Singularity is written in safe managed code (C#), except the kernel. This includes device drives, system components, applications, etc. The kernel, since it implements the memory system, scheduler, and manages devices is pretty low-level code and is primarily written in safe C#, though there are parts written in unsafe C# and a HAL written in C++.

Also note that we own the compiler and can control the code that it generates. Using an off-the-shelf compiler would introduce a lot of difficulties in predicting exactly what code would be generated in different situations. This is not fundamental, but rather a big convenience.

And yes, you too can write a good part of your run-time system in safe code. Look at a library sometime. Most of it is pretty simple data manipulation that can be written in any language. There are a few tricky parts where the unsafe subset of C#, or its equivalent, is essential. The key is to factor your system so these parts live in the kernel, with a safe interface, or are inserted by your compiler.

This post originally appeared on an external website

by stefanprodan

I've stated a new research project based on Web Services Enhancements Version 3.0. The goal is to port the FTP standard on Soap. I have tried this before on the Net Framework 1.1 using DIME Attachments. The problem was that Dime could not be used with WS-* because the binary content of the message was sent outside the SoapEnvelope of the XML message. Even if the message is secure the binary attachment is not.
WSE 3.0 comes with MTOM (Message Transmission Optimization Mechanism), MTOM fully complies with WS-Security so the entire message is secure. Code upgrade concerning Dime to MTOM is easy, example follows:

//DIME
[WebMethod]
public void GetFile(string fileName){   SoapContext repcntxt = ResponseSoapContext.Current;
   DimeAttachment dimeattch =  new DimeAttachment("binary",  TypeFormat.Unknown, HttpContext.Current.Server.MapPath(fileName));  repcntxt.Attachments.Add(dimeattch);}

//MTOM
[WebMethod]
public byte[] GetFile(string fileName){    byte[] response = File.ReadAllBytes(fileName);    return response;}

I will post more stuff on MTOM and FTP over SOAP as the project will go on. Wish me luck.

This post originally appeared on an external website

by stefanprodan

private void StopIIS(){    ServiceController iis = new ServiceController("W3SVC");    if (null != iis)    {        do
        {            iis.Refresh();        }        while
            (            iis.Status ==             ServiceControllerStatus.ContinuePending ||            iis.Status ==             ServiceControllerStatus.PausePending ||            iis.Status ==             ServiceControllerStatus.StartPending ||            iis.Status ==            ServiceControllerStatus.StopPending            );        if (ServiceControllerStatus.Running ==             iis.Status ||            ServiceControllerStatus.Paused == iis.Status)        {            iis.Stop();            iis.WaitForStatus(                ServiceControllerStatus.Stopped);        }        iis.Close();    }}

private void StartIIS(){     ServiceController iis = new ServiceController("W3SVC");     if (null != iis)     {         do
         {             iis.Refresh();         }         while              (             iis.Status ==              ServiceControllerStatus.ContinuePending ||             iis.Status ==              ServiceControllerStatus.PausePending ||             iis.Status ==              ServiceControllerStatus.StartPending ||             iis.Status ==              ServiceControllerStatus.StopPending             );         if (ServiceControllerStatus.Stopped == iis.Status)         {             iis.Start();             iis.WaitForStatus(                 ServiceControllerStatus.Running);         }         else
         {             if (ServiceControllerStatus.Paused ==                  iis.Status)             {                 iis.Continue();                 iis.WaitForStatus(                     ServiceControllerStatus.Running);             }         }         iis.Close();     }}

This post originally appeared on an external website

by stefanprodan

Handy class if you plan to create sites from your .net application. There are xml comments on it, so if you need more details on how to use it let me know, I'll give you an example.
Here comes the code :)

using System;
using System.DirectoryServices;
using System.ServiceProcess;

/// <summary>
/// IIS Services Schema
/// </summary>
public enum Schema : int
{
	/// <summary>MSFTPSVC</summary>
	FTP = 1,
	/// <summary>W3SVC</summary>

	WEB = 2
}
/// <summary>
/// IIS Virtual Directory manager
/// </summary>
public class IISManager
{
    private static string ftpSchema = "IIsFtpVirtualDir";
    private static string ftpRoot = "/MSFTPSVC/";
    private static string webSchema = "IIsWebVirtualDir";
    private static string webRoot = "/W3SVC/";
    private int serverId = 1;
    private string serverName = "localhost";
    private string root;
    private Schema schema = Schema.WEB;
    private DirectoryEntry deRoot;
    private string errorMessage = string.Empty;

    /// <summary>
    /// Returns last error
    /// </summary>
    public string ErrorMessage
    {
        get { return this.errorMessage; }
    }

    /// <summary>
    /// Default constructor, 
    /// IIS://localhost/W3SVC/1/Root
    /// </summary>
    public IISManager()
    {
        root = "IIS://" + this.serverName + webRoot + this.serverId + "/Root";
        this.deRoot = new DirectoryEntry(this.root);
    }

    /// <summary>
    /// Custom Constructor
    /// </summary>
    /// <param name="serverName">localhost</param>
    /// <param name="serverId">1</param>
    /// <param name="schema">WEB</param>
    public IISManager(string serverName, int serverId, Schema schema)
    {
        this.serverName = serverName;
        this.serverId = serverId;
        this.schema = schema;
        if (this.schema == Schema.FTP)
        {
            root = "IIS://" + this.serverName + ftpRoot + this.serverId + "/Root";
        }
        else

        {
            root = "IIS://" + this.serverName + webRoot + this.serverId + "/Root";
        }

        this.deRoot = new DirectoryEntry(this.root);
    }

    /// <summary>
    /// Check for existing virtual directory
    /// </summary>
    /// <param name="name">virtual directory name</param>
    /// <returns></returns>
    public bool IsDirectory(string name)
    {
        try

        {
            return DirectoryEntry.Exists(root + "/" + name);
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// Create a virtual directory
    /// </summary>
    /// <param name="name">virtual directory name</param>
    /// <param name="folderPath">local directory path</param>
    /// <param name="isApplication">create application for web virtual directory</param>
    /// <returns></returns>
    public bool CreateDirectory(string name, string folderPath, bool isApplication)
    {
        if (IsDirectory(name))
        {
            this.errorMessage = "Directory " + name + " exist";
            return false;
        }

        bool ok = true;

        DirectoryEntry deNewVDir;

        try

        {
            deRoot.RefreshCache();

            if (this.schema == Schema.FTP)
            {
                deNewVDir = deRoot.Children.Add(name, ftpSchema);
            }
            else
            {
                deNewVDir = deRoot.Children.Add(name, webSchema);
            }

            deNewVDir.Properties["Path"].Insert(0, folderPath);
            deNewVDir.CommitChanges();
            deRoot.CommitChanges();

            // Create a Web Application
            if (schema == Schema.WEB)
            {
                deNewVDir.Invoke("AppCreate", isApplication);
            }

            // Save Changes

            deNewVDir.CommitChanges();
            deRoot.CommitChanges();
            deNewVDir.Close();
            deRoot.Close();
        }
        catch (Exception ex)
        {
            this.errorMessage = ex.Message;
            ok = false;
        }
        return ok;
    }

    /// <summary>
    /// Delete a virtual directory
    /// </summary>
    /// <param name="name">virtual directory name</param>
    /// <returns></returns>
    public bool DeleteDirectory(string name)
    {
        bool ok = true;

        if (!IsDirectory(name))
        {
            this.errorMessage = "Directory " + name + " does not exist";
            return false;
        }

        Object[] parameters;

        try

        {
            if (this.schema == Schema.FTP)
            {
                parameters = new object[] { ftpSchema, name };
            }
            else
            {
                parameters = new object[] { webSchema, name };
            }
            deRoot.Invoke("Delete", parameters);
            deRoot.CommitChanges();
            deRoot.Close();
        }
        catch (Exception ex)
        {
            this.errorMessage = ex.Message;
            ok = false;
        }
        return ok;

    }

    /// <summary>
    /// Stop IIS Services
    /// </summary>
    /// <param name="schema">MSFTPSVC or W3SVC</param>
    public static void StopIIS(Schema schema)
    {
        ServiceController myServiceController;

        if (schema == Schema.FTP)
        {
            myServiceController = new ServiceController("MSFTPSVC");
        }
        else

        {
            myServiceController = new ServiceController("W3SVC");
        }
        if (null != myServiceController)
        {
            do
            {
                myServiceController.Refresh();
            }
            while

                (myServiceController.Status == ServiceControllerStatus.ContinuePending ||
                myServiceController.Status == ServiceControllerStatus.PausePending ||
                myServiceController.Status == ServiceControllerStatus.StartPending ||
                myServiceController.Status == ServiceControllerStatus.StopPending);

            if (ServiceControllerStatus.Running == myServiceController.Status ||
                ServiceControllerStatus.Paused == myServiceController.Status)
            {
                myServiceController.Stop();
                myServiceController.WaitForStatus(ServiceControllerStatus.Stopped);
            }
            myServiceController.Close();
        }
    }

    /// <summary>
    /// Start IIS Services
    /// </summary>
    /// <param name="schema">MSFTPSVC or W3SVC</param>
    public static void StartIIS(Schema schema)
    {

        ServiceController myServiceController;

        if (schema == Schema.FTP)
        {
            myServiceController = new ServiceController("MSFTPSVC");
        }
        else
        {
            myServiceController = new ServiceController("W3SVC");
        }

        if (null != myServiceController)
        {
            do

            {
                myServiceController.Refresh();
            }
            while
                (myServiceController.Status == ServiceControllerStatus.ContinuePending ||
                myServiceController.Status == ServiceControllerStatus.PausePending ||
                myServiceController.Status == ServiceControllerStatus.StartPending ||
                myServiceController.Status == ServiceControllerStatus.StopPending);

            if (ServiceControllerStatus.Stopped == myServiceController.Status)
            {
                myServiceController.Start();
                myServiceController.WaitForStatus(ServiceControllerStatus.Running);
            }
            else
            {
                if (ServiceControllerStatus.Paused == myServiceController.Status)
                {
                    myServiceController.Continue();
                    myServiceController.WaitForStatus(ServiceControllerStatus.Running);
                }
            }
            myServiceController.Close();
        }
    }
}

This post originally appeared on an external website

by stefanprodan

When dealing with message into an application, and the message that you are receiving or sending is over a not trusted channel you should think about a way to make sure that the message has not been altered. This is why cryptographic hash functions are used.
More on cryptographic hash function you can find here.
Here is a function in C# that can generate for you the hash of a string based on your favorite algorithm.

using System;
using System.Text;
using System.Security.Cryptography;

/// <summary>
/// Hash algorithms
/// </summary>
public enum HashType : int
{
    SHA1,
    SHA256,
    SHA384,
    SHA512,
    MD5,
    RIPEMD160
}

public static class Hash
{
    public static string FromString(string input, HashType hashtype)
    {
        Byte[] clearBytes;
        Byte[] hashedBytes;
        string output = String.Empty;

        switch (hashtype)
        {
            case HashType.RIPEMD160:
                clearBytes = new UTF8Encoding().GetBytes(input);
                RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create();
                hashedBytes = myRIPEMD160.ComputeHash(clearBytes);
                output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                break;
            case HashType.MD5:
                clearBytes = new UTF8Encoding().GetBytes(input);
                hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
                output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                break;
            case HashType.SHA1:
                clearBytes = Encoding.UTF8.GetBytes(input);
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                sha1.ComputeHash(clearBytes);
                hashedBytes = sha1.Hash;
                sha1.Clear();
                output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                break;
            case HashType.SHA256:
                clearBytes = Encoding.UTF8.GetBytes(input);
                SHA256 sha256 = new SHA256Managed();
                sha256.ComputeHash(clearBytes);
                hashedBytes = sha256.Hash;
                sha256.Clear();
                output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                break;
            case HashType.SHA384:
                clearBytes = Encoding.UTF8.GetBytes(input);
                SHA384 sha384 = new SHA384Managed();
                sha384.ComputeHash(clearBytes);
                hashedBytes = sha384.Hash;
                sha384.Clear();
                output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                break;
            case HashType.SHA512:
                clearBytes = Encoding.UTF8.GetBytes(input);
                SHA512 sha512 = new SHA512Managed();
                sha512.ComputeHash(clearBytes);
                hashedBytes = sha512.Hash;
                sha512.Clear();
                output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                break;
        }
        return output;
    }
}

This post originally appeared on an external website

by stefanprodan

Project Name: AlephFS
Start Date: 08 May 2006
Technologies used: ASP.NET 2.0 & WSE 3.0 & MTOM

I've stated a new research project based on Web Services Enhancements Version 3.0. The goal is to make a FTP server like application but on Soap. I have tried this before on the Net Framework 1.1 using DIME Attachments.
The problem was that Dime could not be used with WS-* because the binary content of the message was sent outside the SoapEnvelope of the XML message. Even if the message is secure the binary attachment is not.WSE 3.0 comes with MTOM (Message Transmission Optimization Mechanism), MTOM fully complies with WS-Security so the entire message is secure.
As long as the project will go on I will post here code that maybe you'll find useful.
The web service is based on the IFileServer interface but this is just the start point.

/// <summary>
/// File Server Interface
/// </summary>
public interface IFileServer
{
    //
    //CUSTOM SECURITY
    //

    /// <summary>
    /// Create a new directory
    /// </summary>
    /// <param name="dirName">Folder name</param>
    void CreateDir(string dirName);
    /// <summary>
    /// Returns the folders within the directory(first level not recursive)
    /// </summary>
    /// <param name="dirName"></param>
    /// <returns></returns>
    StringCollection ListDirs(string dirName);
    /// <summary>
    /// Delete an existing directory and all the content inside it
    /// </summary>
    /// <param name="dirName">Folder name</param>
    void DeleteDir(string dirName);
    /// <summary>
    /// Returns the files within the directory(first level not recursive)
    /// </summary>
    /// <param name="dirName">Folder name</param>
    /// <returns>files list</returns>
    StringCollection ListFiles(string dirName);
    /// <summary>
    /// Returns the files within the directory(recursive)
    /// </summary>
    /// <param name="dirName"></param>
    /// <returns>files list</returns>
    StringCollection ListFilesRecursive(string dirName);
    /// <summary>
    /// Uploads file to specific directory
    /// </summary>
    /// <param name="path">destination folder</param>
    /// <param name="fileName"> file name</param>
    void UploadFile(string path, string fileName, byte[] data);
    /// <summary>
    /// Downloads file from server
    /// </summary>
    /// <param name="path">server relative path to file</param>
    /// <returns>binary data</returns>
    byte[] DownloadFile(string path);
    /// <summary>
    /// Deletes a specific file from the server
    /// </summary>
    /// <param name="path">server relative path to file</param>
    void DeleteFile(string path);

    //
    //WINDOWS IMPERSONATION
    //

    /// <summary>
    /// Create a new directory
    /// </summary>
    /// <param name="dirName">Folder name</param>
    void CreateDirImp(string user, string domain, string password, string dirName);
    /// <summary>
    /// Returns the folders within the directory(first level not recursive)
    /// </summary>
    /// <param name="dirName"></param>
    /// <returns></returns>
    StringCollection ListDirsImp(string user, string domain, string password, string dirName);
    /// <summary>
    /// Delete an existing directory and all the content inside it
    /// </summary>
    /// <param name="dirName">Folder name</param>
    void DeleteDirImp(string user, string domain, string password, string dirName);
    /// <summary>
    /// Returns the files within the directory(first level not recursive)
    /// </summary>
    /// <param name="dirName">Folder name</param>
    /// <returns>files list</returns>
    StringCollection ListFilesImp(string user, string domain, string password, string dirName);
    /// <summary>
    /// Returns the files within the directory(recursive)
    /// </summary>
    /// <param name="dirName"></param>
    /// <returns>files list</returns>
    StringCollection ListFilesRecursiveImp(string user, string domain, string password, string dirName);
    /// <summary>
    /// Uploads file to specific directory
    /// </summary>
    /// <param name="path">destination folder</param>
    /// <param name="fileName"> file name</param>
    void UploadFileImp(string user, string domain, string password, string path, string fileName, byte[] data);
    /// <summary>
    /// Downloads file from server
    /// </summary>
    /// <param name="path">server relative path to file</param>
    /// <returns>binary data</returns>
    byte[] DownloadFileImp(string user, string domain, string password, string path);
    /// <summary>
    /// Deletes a specific file from the server
    /// </summary>
    /// <param name="path">server relative path to file</param>
    void DeleteFileImp(string user, string domain, string password, string path);
}

This post originally appeared on an external website

by stefanprodan

If you are looking at IFileServer interface you will notice that I use two types of security in AlephFS web service. The custom authentication is used when you don?t want to relay on the windows security like active directory. This scenario will need a user database or an XML file that the service can use to make decision based on the user role or group.
For this scenario I created a SoapHeader that looks like this:

using System.Web.Services.Protocols;

/// <summary>
/// Authentication Custom Soap Header
/// </summary>
public class AuthHeader : SoapHeader
{
    public string UserName;
    public string Password;
}

The clients that access the web service must use the custom header for authentication every time a method is called. In the web service the methods that use custom security must use the soap header. Here is an example:

public class Service : WebService, IFileServer
{
    public AuthHeader Credentials;
	
[WebMethod, SoapHeader("Credentials", Direction=SoapHeaderDirection.In)]
    public void CreateDir(string dirName)
    {
        ValidateUser(Credentials);
        try
        {
            Directory.CreateDirectory(dirName);
        }
        catch (IOException iox)
        {
		//log error
        }
    }
}

Every time a method is called we must make sure that the client is authorized. To validate the client credential before executing the body of the method we must call ValidateUser.Inside ValidateUser method we can connect to the database for user name and password validation, maybe get the rolls of the user and so on.

private void ValidateUser(AuthHeader Credentials)
{
	if (Credentials.UserName.Length < 1 ||
		Credentials.Password.Length < 1)
	{
		throw new SoapException("Unauthorized", SoapException.ClientFaultCode);
	}
	try
	{
		//TODO: Validate user & pass using database or xml
		if (Credentials.Password != "password")
		{
			throw new SoapException("Unauthorized", SoapException.ClientFaultCode);
		}
	}
	catch
	{
		throw new SoapException("Unauthorized", SoapException.ClientFaultCode);
	}
}

Now that we have implemented the custom authentication on the web server side let?s see how the client can communicate with AlephFS. I am using for testing a windows application. Here comes the client code:

private void CallWs()
{
	//proxy
	AlephFS.AlephFileServerWse ws;
	ws = new Client.AlephFS.AlephFileServerWse();

	//custom header
	AlephFS.AuthHeader authHeader = new Client.AlephFS.AuthHeader();
	authHeader.UserName = "user_name";
	authHeader.Password = "password";
	ws.AuthHeaderValue = authHeader;

	//call method
	try
	{
		ws.CreateDir("MyDocs");
	}
	catch (SoapException ex)
	{
		//log error
	}
}

This post originally appeared on an external website

by stefanprodan

Like the hash provider I need a function that will check for the integrity of the files managed by the web service. But CRC, MD5 and other checksum algorithms eat up a lot of CPU time and memory.
For my checksum function I've decided to use the Adler32 algorithm.The method that I am posting here works with any file size, as a remark, if you have a lot of memory on the server where you are doing checksums, make the buffer as big as you can, it will move faster but will eat more resources.

public static long Adler32Checksum(string filePath, int bufferLenght)
{
    long output = 0;
    int read = 0;

    Adler32 alder = new Adler32();

    byte[] buffer = new byte[bufferLenght];
    if (File.Exists(filePath))
    {
        using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            while ((read = fs.Read(buffer, 0, bufferLenght)) > 0)
            {
                alder.Update(buffer, 0, read);
            }
        }
    }
    output = alder.Value;
    return output;
}

This post originally appeared on an external website

by stefanprodan

If you work with multiple assemblies and you want to make sure no one uses your code by calling methods from other applications you can use strong names, first you have to sign with your private key all your components and application that you deploy to the client. If you want your code to be safe obfuscation is required too. So lets suppose I have an assembly that is validating the product serial number at installation time and I want only my application to able to instantiate it. This is the piece of code I must put in the constructor:

public class Activator
{
    public Activator()
    {
        Assembly callerAsm = Assembly.GetCallingAssembly();
        StrongName callerSn = GetStrongName(callerAsm.Evidence);

        Assembly thisAsm = Assembly.GetExecutingAssembly();
        StrongName thisSn = GetStrongName(thisAsm.Evidence);

        if (callerSn == null || thisSn == null || callerSn.PublicKey.ToString() != thisSn.PublicKey.ToString())
        {
            throw new SecurityException("Unauthorized execution detected, caller assemby unknown.");
        }
    }

    private static StrongName GetStrongName(Evidence evidence)
    {
        foreach (object o in evidence)
        {
            if (o is StrongName)
            {
                return o as StrongName;
            }
        }
        return null;
    }

    //protected methods 

}

So when I call Activator a = new Activator(); if my app is not signed with the same strong name as the Activator.dll the security exception will pop up.

This post originally appeared on an external website

This discussion is closed to new replies.