XML Serialization quick and easy csharp

Serialization with XML and C#

this is mainly here as a reminder for me on how to do it!

To serialize to a file:


using System.Xml;
using System.Xml.Serialization;
// other code

List<string> mylist = this.getList();

Type stype = typeof(List<string>);

var serializer = new XmlSerializer(stype);
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true; // this is because of microsofts dodgy xml tag
using (var writer = XmlWriter.Create("outputfile.xml",settings))
{
serializer.Serialize(writer,mylist);
}
 

To serialize to a string:

string r = "";
List<string> mylist = this.getList();
   using (MemoryStream memS = new MemoryStream())
    {
      //set up the xml settings
      XmlWriterSettings settings = new XmlWriterSettings();
      settings.OmitXmlDeclaration = true;
      Type stype = typeof(mylist);
      var xmlSerializer = new XmlSerializer(stype);
      StringBuilder retString = new StringBuilder();
      using (XmlWriter writer = XmlTextWriter.Create(memS, settings))
       {
         //write the XML to a stream
         xmlSerializer.Serialize(writer, mylist);
         writer.Close();
       }
    //encode the memory stream to xml
    string v = Encoding.UTF8.GetString(memS.ToArray());
    r = v;             
    memS.Close(); // the using should do this anyway
    }        

To de-serialize xml from a string

public List<string> getMyStrings(string xmlString)
{
 XmlSerializer serializer = new XmlSerializer(typeof(List<string>));
   using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
    {
      return (List<string>)serializer.Deserialize(ms);
    }
}

That’s it, any errors are due to me typing most of it from memory, so if it doesn’t work it’s probably missing a ‘;’ or something

You will need these usings:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

Bootstrap compatible asp.net button

Similar to my previous post, you can use the following code to create a custom asp.net button with the ‘button’ tags used in HTML5 and bootstrap.

  [ParseChildren]
   public class bsButton : Button
    {

        private string _ButtonCss = "btn btn-default";
        [Browsable(true), Description("The css class"),]
        public string ButtonCss
        {
            get
            { return _ButtonCss; }
            set
            {
                _ButtonCss = value;
            }
        }

        private string _glyphicon = "";
        [Browsable(true), Description("GlyphiconName"),]
        public string glyphIcon
        {
            get
            {
                return _glyphicon;
            }
            set
            {
                _glyphicon = value;
            }

        }


        protected override void Render(HtmlTextWriter writer)
        {

            if (glyphIcon == "")
            {
                System.Web.UI.HtmlControls.HtmlGenericControl
                            btn = new System.Web.UI.HtmlControls.HtmlGenericControl("button");
                btn.Page = this.Page;
                btn.ID = this.ClientID;
                btn.InnerText = this.Text;
                btn.Attributes.Add("class", ButtonCss);
                btn.Visible = this.Visible;
                btn.Attributes.Add("name", this.UniqueID);
                btn.Attributes.Add("onchange", "__doPostBack('" + this.ClientID + "', 'OnClick',true)"); // fire postback
                btn.RenderControl(writer);
            }

            else {
                System.Web.UI.HtmlControls.HtmlGenericControl groupbtn = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                groupbtn.Attributes.Add("class", "input-group-btn");

                System.Web.UI.HtmlControls.HtmlGenericControl
                       btn = new System.Web.UI.HtmlControls.HtmlGenericControl("button");
                System.Web.UI.HtmlControls.HtmlGenericControl
                    ithing = new System.Web.UI.HtmlControls.HtmlGenericControl("i");

                Literal litText = new Literal();

                ithing.Attributes.Add("class", "glyphicon glyphicon-" + glyphIcon);

                btn.Page = this.Page;
                btn.ID = this.ClientID;
                litText.Text = this.Text;
                btn.Attributes.Add("class", ButtonCss);
                btn.Visible = this.Visible;
                btn.Attributes.Add("name", this.UniqueID);
                btn.Attributes.Add("onchange", "__doPostBack('" + this.ClientID + "', 'OnClick',true)"); // fire postback
                btn.Controls.Add(ithing);
                btn.Controls.Add(litText);
                groupbtn.Controls.Add(btn);

                groupbtn.RenderControl(writer);


            }


        }
    }

you will need to surround that with

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Controls
{
//..Code here
}

Or append it to the class used for the radio button list.

Bootstrap compatible asp.net radio button list

Recently I have had the requirement to make some of my asp.net controls ‘bootstrap compatible’

In this instance it has been asp.net’s radio button list that is causing me consternation!

An inline bootstrap radio button list has the mark up of this:

<div class="radio">
                <label class="radio-inline">
                    <input type="radio" value="Ac" name="optArchive" checked="checked">Active</label>
                <label class="radio-inline">
                    <input type="radio" value="Ar" name="optArchive">Archive</label>
            </div>

You could use hidden fields and JavaScript to control Postbacks and capture the data.I feel this is not a reliable option.

The easiest and I think the best method I have found so far is to extend the RadioButtonList to do my bidding.

I started by creating a class file to contain all of my bootstrap friendly controls, in this instance I named it ‘/App_Code/bsFriendly.cs’, creating a namespace in that class called Controls

In that file I extend the RadioButtonList, so far it looks like this:


//bsFriendly.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Controls
{
    public class bsRadioButtonList : RadioButtonList
    {
    }
}

Nothing too exciting.

Within our ‘bsRadioButtonList’ the RenderItem method has to be overridden. In VS this is a case of typing ‘protected override’ to get IntelliSense to present a list of override-able properties and methods. From that list select ‘RenderItem’, Visual Studio will create the override with a call back to it’s base.

Remove the base call and instead replace it with the following:

namespace Controls
{
    public class bsRadioButtonList : RadioButtonList
    {
 
   
        protected override void RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer)
        {




            RadioButton radioButton = new RadioButton(); // to hold our radio button
            Literal litText = new Literal(); //to hold our labels text
            radioButton.Page = this.Page;
            radioButton.GroupName = this.UniqueID;
            radioButton.ID = this.ClientID + "_" + repeatIndex.ToString();
            radioButton.Attributes["value"] = this.Items[repeatIndex].Value;
            radioButton.Checked = this.Items[repeatIndex].Selected;
            radioButton.TextAlign = this.TextAlign;
            radioButton.AutoPostBack = this.AutoPostBack;
            radioButton.Attributes.Add("onchange", "__doPostBack('" + this.ClientID + "_" + repeatIndex.ToString() + "',' ')"); // fire postback
            radioButton.TabIndex = this.TabIndex;
            radioButton.Enabled = this.Enabled;
            System.Web.UI.HtmlControls.HtmlGenericControl gnLabelHolder = new System.Web.UI.HtmlControls.HtmlGenericControl("label"); // our label holder
            gnLabelHolder.Attributes.Add("for", this.ClientID + "_" + repeatIndex.ToString()); //associated to the radio button
            gnLabelHolder.Attributes.Add("class", "radio-inline"); //give it the bootstrap inline class, could extend as a property
            litText.Text = this.Items[repeatIndex].Text;

            gnLabelHolder.Controls.Add(radioButton); // add in the correct order of radio button then texts
            gnLabelHolder.Controls.Add(litText);
           
            
            gnLabelHolder.RenderControl(writer); //render to the writer


        }
    }

}

This will now act as new control.

To include the control on a page, simply add:

<%@ Register TagPrefix="bs" Assembly="App_Code" Namespace="Controls" %>

At the top of the page, below the Language and Codefile definitions at the top.

As a control in the page:

          <bs:bsRadioButtonList AutoPostBack="true" OnSelectedIndexChanged="test_SelectedIndexChanged" ID="test" runat="server" RepeatLayout="Flow"  RepeatDirection="Horizontal">
                    <asp:ListItem Selected="True">Active</asp:ListItem>
                    <asp:ListItem>Archive</asp:ListItem>

                </bs:bsRadioButtonList>

And in our back end cs file:

    protected void test_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

That’s all there is to it.

Caveats:

  1. In the mark up you need to select an item, not doing so could cause confusion with postbacks
  2. AutoPostBack needs to be set to true to allow the hookup on __DoPostBack

Calculate a fraction in javascript

Calculating a fraction from a double in javascript

The following code will allow you to calculate a fraction in javascript

 function getFraction(dblValue, dblTolerance)
    {
        var f0 = 1 / dblValue;

        var f1 = 1 / (f0 - Math.floor(f0));

        var a_t = Math.floor(f0);

        var a_r = Math.round(f0);

        var b_t = Math.floor(f1);

        var b_r = Math.round(f1);

        var c = Math.round(1 / (f1 - Math.floor(f1)));

        if (Math.abs(1.0 / a_r - dblValue) <= dblTolerance)
        {
            return [1, a_r];
        }
        else if (Math.abs(b_r / (a_t * b_r + 1.0) - dblValue) <= dblTolerance)
        {
            return [b_r, a_t * b_r + 1];
        }
        else {
            return [c * b_t + 1, c * a_t * b_t + a_t + c];

        }
    }

For example the following code examples give you a numerator and a denominator

console.log(getFraction(0.75,0.02));
/*[3, 4]*/
/***********************************/

console.log(getFraction(0.5,0.02));
/*[1, 2]*/
/***********************************/

console.log(getFraction(0.25,0.02));
/*[1, 4]*/
/***********************************/

console.log(getFraction(0.33,0.02));
/*[1, 3]*/
/***********************************/

Hope that’s of use to somebody!

Javascript Dynamic Event

Javascript Dynamic Events / Javascript Custom Events

I often asked myself: How do I create a custom event in javascript?

Something I have been using for quite awhile now is my own custom event handler for javascript, it’s pretty simple compact and easy to use

To use; just copy the devent function to the page in which it needs to be used.

Initialize it by xxEventName = new devent()

You can set what happens when the event is fired by assigning a function to the XXEventName.myEvent property, and you can trigger the event by using the XXEventName.fire() method.

The example below is the best method on which to use it.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>oop Example</title>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
        function devent(runonce)
        {

            /******************
            * Javascript Dynamic Events
            * (c) joesblog.me.uk 2011
            *******************/

            // event has run
            this.onEvent_hasrun = false;

            // only allow running once
            this.onEvent_runonce = runonce;

            // event function
            this.myEvent = function () { };

            // now obsolete
            this.myCallback = null;

            //data to be passed to event
            this.myEvent_Data = null;

            // how many times the event has been fired
            this.myEventCount = 0;

            //fire the event , in other words execute the function assigned in myEvent
            this.fire = function ()
            {
                if (this.myEvent != null)
                {
                    if (!this.onEvent_runonce)
                    {
                        this.onEvent_hasrun = true;
                        this.myEventCount++;
                        this.myEvent();
                        return;
                    }
                    else
                    {
                        if (!this.onEvent_hasrun)
                        {
                            this.onEvent_hasrun = true;
                            this.myEventCount++;
                            this.myEvent();
                        } else
                        { return; }
                    }
                }
            }
        }

        ///An example of a static javascript class
        var myStaticClass = new function ()
        {
            // the event for when the sum has been done
            this.mathsDone = new devent();

            // the result of the addition
            this.simpleMaths = null;
            //The interval object timer.
            this.waitInterval = null;
            //self explainatory 
            this.countDown = 5; 
            
            //default countdown
            this.defaultCount = 5;

            //initialise all the objects and things that we need in this class
            this.init = function ()
            {
         
                //clear the interval 
                 this.waitInterval = null;

                //set the coutndown to its starting position
                 this.countDown = this.defaultCount;
            }

            //function called no the interval 'pulse'
            this.controlTime = function ()
            {
                if (myStaticClass.countDown == 0)
                {   ///if all the countdown has reached zero, do the maths, reset the countdown and clear the interval object

                    myStaticClass.doSimpleMaths(); 
                    myStaticClass.countDown = myStaticClass.defaultCount;
                    clearInterval(myStaticClass.waitInterval);
                }
                else
                {
                    myStaticClass.countDown--;
                }

                document.getElementById('countdown').innerHTML = myStaticClass.countDown

            }


            this.doSimpleMaths = function ()
            {
                myStaticClass.simpleMaths = (100 * 100) + 5;
                this.mathsDone.fire(); //fire the mathsDone event and cause the function we have set to run
            }

            this.start = function ()
            {
                myStaticClass.waitInterval = setInterval(myStaticClass.controlTime, 1000);
            }
        }
        //An example of a nonStaticClass
        function nonStaticClass(constructorVar1, constructorVar2)
        {
            this.aVar = constructorVar1;
            this.bVar = constructorVar2;
            this.result = 12;
            this.method = function () { this.result = this.aVar + this.bVar;  alert('do something'); }
        }

        var nonStaticClass_Instance = null;

        $('document').ready(function ()
        {
            //init the class
            myStaticClass.init();
            //assign a function to the mathsdone event
            myStaticClass.mathsDone.myEvent = function ()
            {
                alert(myStaticClass.simpleMaths);
            }

            nonStaticClass_Instance = new nonStaticClass(5, 12);

        });
    </script>

    <style type="text/css">
        body {
            font-family: verdana;
        }

        .centerDiv {
            height: 500px;
            width: 500px;
            background-color: #eaeaea;
            margin: auto;
            border-radius: 5px;
            border: solid 1px #ccc;
        }

            .centerDiv p {
                padding: 10px;
            }

        input[type=button] {
            padding: 10px;
            margin: 10px;
        }
    </style>
</head>
<body>
    <div class="centerDiv">
        <p>Click below and then Wait <span id="countdown">5</span> seconds</p>
        <input type="button" value="click ME" onclick="myStaticClass.start()" />
        <input type="button" value="click ME non Static method" onclick="nonStaticClass_Instance.method()" />

    </div>
</body>
</html>

Demo of the code

Using XSD/XML With LINQ; Serializing and Deserializing – Visual Studio .Net 4.0


In this example i am using VS2010 with .Net 4.0 as the framework.

The XML i am using is:

<!--?xml version="1.0" encoding="utf-8"?-->

 File.html

 List.html

 Data.html

 A4

Located in VS2010, and most likely VS2008 is the CreateSchema option in the XML menu, this becomes available when editing XML documents.

Using create schema on the above XML sheet would create a XSD document as below:


Using the XSD tool (Found in C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\xsd.exe with VS2010) it is possible to create a LINQ query-able Dataset/Class from XML.

Running the following from a CMD prompt will generate a class file that you can use in your application:

“C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\xsd.exe” C:\_DEVELOPMENT\Your.xsd /c /eld /edb /o:C:\_DEVELOPMENT\

What the command line parameters mean:

  • The Location of the xsd.exe
  • The Location of your xsd file
  • The Arguments:
  • /c indicates we are creating a class.
  • /eld indicates we are creating a dataset that can be queryable by LINQ
  • /edb indicates we are to allow data binding
  • The destination of the class file, in this instance it will be called Your.cs and placed in the C:\_DEVELOPMENT\ dicrectory.

Import the Your.cs class into the project you are working on.

I Have used all the following namespaces, plus the standard ones for a application/webapp:

using System.Diagnostics;
using System.IO;
using System.Security.Permissions;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

//The following function can de-serialze the ‘Convert Object’ from an XML document
public Convert GetConvert(string FilePath)
{
Convert res = null;
if (System.IO.File.Exists(FilePath)) //Check to see if the file is there
{
using (FileStream fs = new FileStream(FilePath, FileMode.Open)) // Load the file into a file stream
{
using (XmlReader reader = XmlReader.Create(fs)) // Create an XMLReader from the 
{
XmlSerializer serializer = new XmlSerializer(typeof(Convert)); //Prepare a serializer, with the Convert Object type
Convert deserializedconverts = serializer.Deserialize(reader) as Convert; // Deserialize an object
res = deserializedconverts; // * return the deserialized object.
}
}
}
return res; // * return the deserialized object.
}
//The following function can serialize a ‘Convert Object’ to an XML Document
public bool WriteConvert(string FilePath, Convert input)
{
try
{
using (FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate)) // Open or create a file named by the filepath param.
{
XmlWriterSettings writerSettings = new XmlWriterSettings() { Encoding = new UTF8Encoding(false) }; // set the encoding to UTF8
using (XmlWriter writer = XmlWriter.Create(fs, writerSettings)) // Create a new xml writer
{
XmlSerializerNamespaces names1 = new XmlSerializerNamespaces(); names1.Add(“”, “”); // Remove any silly microsoft namespaces
XmlSerializer serializer = new XmlSerializer(typeof(Convert)); // create us a serializer
serializer.Serialize(fs, input, names1); // serialize the object.
}
}
return true; // if it worked return true
}
catch (Exception ex)
{
return false; // if it didnt work return false
}
}

 

That’s essentially it, You may have to add references to both the System.Xml.Linq and the System.Data.DataSetExtensions if you get build Errors.

Copying Data Between/Within Tables in Sql

Simple method of copying data between tables or within the same table in SQL.

The following can be used to copy data within its own table, altering fields as required:

INSERT INTO Table1
(

[Some_Id],
,[Position]
,[Name]
,[Description]
,[LastAction]

)

SELECT

954 as Some_Id,
,[Position]
,[Name]
,[Description]
,[LastAction]
FROM Table1 where Some_Id = 52

The following can be used to copy data from a different table:

INSERT INTO Table1
(

[Some_Id],
,[Position]
,[Name]
,[Description]
,[LastAction]

)

SELECT

43 as Some_Id,
,[Position]
,[Name_First] + ‘ ‘ + [Name_Last]
,[Job_Title]
,NOW()
FROM tblStaff where Job_Title  like ‘%developer%’

Delete / Drop all stored procedures in an SQL Database

The following SQL will delete all stored procedures in a specified database.
Make sure you specify the database you are using!

USE [MyDatabase]
DECLARE @spName varchar(500)
DECLARE _CurCursor CURSOR
 FOR SELECT [name] FROM sys.objects WHERE type = 'p'
 OPEN _CurCursor
 FETCH NEXT FROM _CurCursor INTO @spName
 WHILE @@fetch_status = 0
 BEGIN
 EXEC('DROP PROCEDURE ' + @spName)
 FETCH NEXT FROM _CurCursor INTO @spName
 END
CLOSE _CurCursor
DEALLOCATE _CurCursor

Sorry that it lacks formatting, though it should work with just a copy and paste

Beeker MSN

Download and Use the old Windows Live Messenger 2009

Well Forgive me, I’m not normally one to rant(Ed. okay that may be a lie).But this time it’s almost serious!

Since the dawn of the blue screen, Microsoft have been royally screwing things up for the likes of you, me and everybody else.

Now they have unleashed their greatest stagnation upon the masses; Windows Live Messenger 2011 (Wave 4) . Not only has it got all the gloss of a polished turd, its got more bugs than a fisherman’s hut.  its also got a brand new terrible interface combined with the removal of some very useful features that the previous versions had.

Apart from giving me a case of the grumps..lets see what they’ve given us…

  • Tabbed conversations… We already had this with msn plus
  • A redesign of how the emoticons look how useful.
  • The ability to ignore Bing search not only from your browser, but now from within msn as well!
  • Connections to various social networks.. Okay that could be useful, but its handled in a most cumbersome way.
  • Integration with Facebook chat…Really ? why ?
  • OOOOH BADGES …erm no

Though on the flip side of the coin, here are some of the more useful things they have removed:

  • One way web cam support, you can no longer Send my web cam or View this contacts web cam instead you are forced to do some kind of Skype-esq video call which resembles half the quality of Skype but double the annoyance.
  • The abolition of contact Import/Exports.. This one really is beyond me, Why do this? okay sure i never used it.. but i could have?
  • Display names are now royally screwed up.
  • Oh yes, sorry folks, if your using anything other than Vista/Windows 7 your no longer supported.

Now you all may think I’m just a mad man ranting about a situation with no solution, a wolf crying in the wilderness? Well not exactly; There are alternatives.

For years aMSN has been developing, it is an open source alternative to the run of the mill, its free, very easy to use and works on most major platforms(Windows,MacOs,Linux etc..).

I’ve used that for awhile, but when I’m on a windows machine I still prefer the style n feel of the older msn clients…that’s why i have provided this Earlier version of Windows Live 2009.

Just un-install the latest one, via the program / features part of your control panel.

Another useful tool I use to wallow away the days is MSN plus, with polygamy( in the non marital sense) and various other tools it makes the MSN experience a bit more bearable.

A Small Update 24th Feburary 2011

Some of you may now be getting:

A newer version is available. You must install the newer version in order to continue. Would you like to do this now ?

Microsoft now deem it a requirement for you to update again to a later version, once again removing features. I am including a small replacement for the msnmsg.exe file, simply copy it into your windows live messenger directory (most likely: C:\Program Files\Windows Live\Messenger)

You will still need to install the version of Windows live messenger 2009 above.

The msnmsgr patch can be found here. Just simply replace that msnmsg.exe with the one in your Windows Live Messenger directory and all should work fine!

Happy hunting.

Beeker MSN

Things should be made as simple as possible, but no simpler.