All posts by admin

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

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