Click here to Skip to main content
15,895,011 members
Articles / Programming Languages / XML

Using InsomniaServer to Build a Web-interface for your Application

Rate me:
Please Sign up or sign in to vote.
4.80/5 (11 votes)
15 Jul 2011CPOL3 min read 83.6K   1.2K   41  
InsomniaServer enables you to add a fully-featured, customizable webserver to your projects. See how it works.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.Net;

using InsomniaSoftware.Server;
using InsomniaSoftware.Server.Sources;


namespace MultiPaint
{
    class Sources
    {
        static MainForm _mainForm;
        static InsomniaServer _server;


        /// <summary>
        /// Adds all needed sources to the server
        /// </summary>
        public static void AddSources(MainForm mainForm, InsomniaServer server)
        {
            _mainForm = mainForm;
            _server = server;

            server.fileSystem.AddSource("index.html", GetPaintSource, null);
            server.fileSystem.AddSource("setcolor.html", GetSetColorSource, null);

            //Image download sources
            server.fileSystem.AddSource("image.bmp", GetDownloadPictureSource, ImageFormat.Bmp);
            server.fileSystem.AddSource("image.jpg", GetDownloadPictureSource, ImageFormat.Jpeg);
            server.fileSystem.AddSource("image.png", GetDownloadPictureSource, ImageFormat.Png);
        }

        
        public static ObjectType GetPaintSource(string subPath, HttpRequest request, object userData, out Source source)
        {
            StreamReader reader = new StreamReader("../paint.html", Encoding.ASCII);
            string pageContent = reader.ReadToEnd();
            reader.Dispose();

            Session newSession = request.server.sessionManager.RegisterSession();

            //Create a new PainForm and fill needed values into the registered session
            PaintForm newPaintForm = (PaintForm)_mainForm.Invoke(new CreatePaintFormDelegate(CreatePaintForm), request.remoteEndPoint.ToString() + " - " + newSession.id);
            newSession.SetValue("form", newPaintForm);
            newSession.SetValue("ip", request.remoteEndPoint.Address);
            newSession.OnDispose += new DisposeSessionDelegate(DisposeSession);

            //Update client list
            _mainForm.UpdateContent();

            //Prepare page and send
            pageContent = pageContent.Replace("<!--#SID#-->", newSession.id);
            source = new BinarySource(Encoding.ASCII.GetBytes(pageContent), ContentType.FromType(ContentType.Type.Html));
            return ObjectType.File;
        }


        public static ObjectType GetSetColorSource(string subPath, HttpRequest request, object userData, out Source source)
        {
            source = null;

            StringParameter sessionId = request.GetParameterAsString("sid");
            if (sessionId == null)
                return ObjectType.NotFound;

            Session belongingSession = _server.sessionManager.GetSession(sessionId.value);
            if (belongingSession == null)
                return ObjectType.NotFound;

            if (!((IPAddress)belongingSession.GetValue("ip")).Equals(request.remoteEndPoint.Address))
                return ObjectType.NotFound;

            IntParameter x = request.GetParameterAsInt("x");
            IntParameter y = request.GetParameterAsInt("y");
            StringParameter color = request.GetParameterAsString("c");

            IntParameter width = request.GetParameterAsInt("w");
            IntParameter height = request.GetParameterAsInt("h");

            if (sessionId == null || x == null || y == null || color == null)
                return ObjectType.NotFound;

            PaintForm paintForm = (PaintForm)belongingSession.GetValue("form");
            if (paintForm == null)
                return ObjectType.NotFound;

            if (width != null || height != null)
                paintForm.SetSize(width != null ? width.value : -1, height != null ? height.value : -1);

            try
            {
                Color finalColor = Color.FromArgb(int.Parse(color.value.Substring(1, 2), System.Globalization.NumberStyles.AllowHexSpecifier),
                                                  int.Parse(color.value.Substring(3, 2), System.Globalization.NumberStyles.AllowHexSpecifier),
                                                  int.Parse(color.value.Substring(5, 2), System.Globalization.NumberStyles.AllowHexSpecifier));
                while (paintForm.SetPixel(x.value, y.value, finalColor) == false) { } //While to prevent possible errors (not drawn pixels)
            }
            catch
            {
                return ObjectType.NotFound;
            }

            source = new NoContentSource();
            return ObjectType.File;
        }


        public static ObjectType GetDownloadPictureSource(string subPath, HttpRequest request, object userData, out Source source)
        {
            source = null;

            StringParameter sessionId = request.GetParameterAsString("sid");
            if (sessionId == null)
                return ObjectType.NotFound;

            Session belongingSession = _server.sessionManager.GetSession(sessionId.value);
            if (belongingSession == null)
                return ObjectType.NotFound;

            PaintForm paintForm = (PaintForm)belongingSession.GetValue("form");
            if (paintForm == null)
                return ObjectType.NotFound;

            source = new StreamSource(paintForm.SaveImage((ImageFormat)userData), ContentType.FromType(ContentType.Type.Binary), true);
            return ObjectType.File;
        }


        delegate PaintForm CreatePaintFormDelegate(string title);
        static PaintForm CreatePaintForm(string title)
        {
            PaintForm newPaintForm = new PaintForm();
            newPaintForm.Text = title;
            newPaintForm.Show(_mainForm);
            return newPaintForm;
        }

        static void DisposeSession(Session sessionToBeDisposed)
        {
            //Dispose the form, when session is removed - else the form will survive in background

            PaintForm paintForm = (PaintForm)sessionToBeDisposed.GetValue("form");
            if (paintForm != null)
                paintForm.Invoke(new DisposeDelegate(DisposeSessionAction), paintForm);
            _mainForm.UpdateContent();
        }

        delegate void DisposeDelegate(PaintForm paintForm);
        static void DisposeSessionAction(PaintForm paintForm)
        {
            paintForm.Dispose();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
Germany Germany
I was born in 1987. Unfortunately too late to experience the real rise of the PC. But fortunately late enough to enjoy things like MS's .net during my school time Wink | ;)

From the time when some relative taught me a little BASIC under MS DOS, I loved to tell computers what to do - even though my real start in programming was around the age of 16.

At the moment, I am studying Software Engineering at University of Augsburg, always hoping to find time to design and program.
Besides, I like meeting friends, spent time with my girlfriend and enjoy life Smile | :)

Comments and Discussions