Saturday, December 14, 2013

Artillery in HMTL5

My wife and I have another blog for our fledgling company @ http://blog.biggreenchair.com.  If you are interested in HTML5, javascript, Canvas controls, and Math then please check out our new series making a version of Artillery with javascript and HTML5.

http://blog.biggreenchair.com/learn-to-program-artillery/

Thursday, February 7, 2013

Helper Functions and ASPX

For several years I have compiled a library of helper functions to assist with recurring coding problems and repetitive tasks in my daily work.  Depending on the project, this helper class will grow or shrink but it always seems to find a home in my work.

So I thought I would share the core of my helper class and talk about some of the ideas behind it.

Lets start with errors.  The following function works OK.  It gets me the gyst of the error most of the time, but has the fatal flaw of not doing anything in the case it fails.  Luckily this is used in conjunction with logging so it has never really been a problem.

        public static void SendError(Exception ex, string sIPAddress, string strRequest = "")
        {
            try
            {
                MembershipUser objUser = Membership.GetUser();
                MailMessage message = new MailMessage();                message.From = new MailAddress(admin@homeschooloffice.com);
                message.To.Add(new MailAddress(support@homeschooloffice.com));
                message.Subject = string.Format("{0}-{2}:{1}", objUser.UserName, ex.Message, sIPAddress);
                message.Body = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\r\n{6}", ex.Message,
                                                                ex.Source,
                                                                ex.TargetSite.ToString(),
                                                                objUser.UserName,
                                                                strRequest,
                                                                sIPAddress,
                                                                ex.StackTrace);                SmtpClient client = new SmtpClient();
                client.Send(message);            }
            catch (Exception)
            {            }
        } If you use aspnet membership controls this next function is nice:          public static Guid UserID
        {
            get
            {
                MembershipUser objUser = Membership.GetUser();
                return new Guid(objUser.ProviderUserKey.ToString());
            }
        } Need to encrypt pesky ids or other information?  http://msdn.microsoft.com/en-us/library/ms972969.aspx provides some other guidelines that should be followed when working in web pages, but this was one take away:         public static string EncodeText(int text)
        {
            return EncodeText(text.ToString());
        }        public static string EncodeText(string text)
        {
            StringWriter writer = new StringWriter();
            LosFormatter formatter = new LosFormatter();
            formatter.Serialize(writer, text);
            return writer.ToString();
        }        public static string DecodeText(string text)
        {
            if (string.IsNullOrEmpty(text)) return "";            LosFormatter formatter = new LosFormatter();
            return formatter.Deserialize(text).ToString();
        } Lastly,  I have a few functions that follow this general idea.  If you want to bind common controls with default values or just make them one liners I suggest using functions like this for repeaters and similar variants, listboxes, dropdowns, etc.         public static void SetDropDownList(ref DropDownList ddlList, object DataSource, string TextField, string ValueField)
        {
            SetDropDownList(ref ddlList, DataSource, TextField, ValueField, "____________________", "");
        }         public static void SetDropDownList(ref DropDownList ddlList, object DataSource, string TextField, string ValueField, string DefaultText, string DefaultValue)
        {
            if (ddlList == null) return;
            System.Web.UI.WebControls.ListItem li = new System.Web.UI.WebControls.ListItem();
            li.Value = DefaultValue;
            li.Text = DefaultText;            ddlList.DataSource = DataSource;
            ddlList.DataTextField = TextField;
            ddlList.DataValueField = ValueField;
            ddlList.DataBind();
            ddlList.Items.Insert(0, li);
        }
 There are a few other items that I typically keep in my helper class (like functions to clear forms) but this covers most of the core.  I hope this helps.

Wednesday, October 3, 2012

JQuery FullCalendar The Basics


As this topic is too big for one post it will be a series on the FullCalendar project.  If you have not seen this control or visited the project site please go to http://arshaw.com/fullcalendar/ to get the details.

Getting started:

Beginning to use FullCalendar is really easy.  The most basic setup looks like this:


 
By default FullCalendar will cover the width of the browser so I put in a style of width:800px just to narrow it down a bit.  At first you have just a basic calendar on the page with no way to add or display events.  To allow editing on the calendar add the following code to the function:

 
The code will take you to the day view and allow you select a time range to “edit”.  But I forgot one step.  You need to format the calendar so that you can move back to the month view when you want.  To do this you would add the following code:

  
It will look like this on the page:

 
 
If you wanted to take the spaces out between month, week and day you would format the code to look like this:
 


This renders the calendar as:

 

 

In the next article I will show you how to add events to the calendar and methods for editing events with JQuery Dialog.

Wednesday, September 12, 2012

JQuery .sortable

One of the features we wanted to implement on our current project (www.homeschooloffice.com) was to allow users to keep and sort lists of information. I decided on a couple of features for which the sortable command in JQuery was a huge assist. The first request was to allow users to reorder their lists. The second request was to allow users to move items from one list to another. We will start with the first scenario, as it is the simplest, and work our way up to the second.

To sort items in a list you will need to start out with a list on your page and references to the jQuery and jQuery-ui libraries. Place the references to the libraries in the header section of your page.

<script type='text/javascript' src='/jquery/jquery-1.7.1.min.js'></script>

<script type='text/javascript' src="/jQuery/jquery-ui-1.8.18.custom.min.js"></script>

You will next need to include the javascript to tell jQuery which class or elements to address. In the example below we are telling jQuery to allow items that use the class sortableList to be sorted.

<script type="text/javascript">
$(function () {
$(".sortableList").sortable({});
$(".sortableList").disableSelection();
});
</script>

Copy and paste the following code to a text document, rename the extension to HTML and view it in a browser.

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type='text/javascript' src='http://www.homeschooloffice.com/jquery/jquery-1.7.1.min.js'></script>
<script type='text/javascript' src="http://www.homeschooloffice.com/jQuery/jquery-ui-1.8.18.custom.min.js"></script>
</head>
<body>

  <script type="text/javascript">
    $(function () {
      $(".sortable").sortable({});
      $(".sortable").disableSelection();
    });
  </script>

  <ul class="sortable">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>

</body>
</html>

While the example is quick and easy it really doesn’t do much for us. If we wanted to store the changes we would need to call back to our site and write the results to storage. AJAX is how I normally do this.  Here is an example:

$(function () {
$(".sortable").sortable({
  start: function (e, ui) {
  ui.placeholder.height(100);
},

update: function (e, ui) {
var item = ui.item;
var position = (ui.item).index();
var section = item.attr("id");
var queue = container.attr("Qid");

$.ajax({
  type: "POST",
  contentType: "application/json",
  url: "Default.aspx/SaveList",
  data: "{ ItemData: " + JSON.stringify({ Seq: position + 1, ItemID: section, ListID: queue }) + " }",
  dataType: "json",
  error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
},
success: function (feedback) {
}
});
}
});



$(".sortable").disableSelection();

Here is the corresponding list:

<div class="reorderList" style="width:90%;">
<ul id="List1" class="sortable" Qid="/wEFAjE5">

<li id="/wEFAjYw">Item 1</li>
<li id="/wEFAjYx">Item 2</li>
<li id="/wEFAjYy">Item 3</li>
</ul>

<ul id="List2" class="sortable" Qid="/wEFAjE5">

<li id="/wEFAjYa">Item 4</li>
<li id="/wEFAjYb">Item 5</li>
<li id="/wEFAjYc">Item 6</li>
</ul>

</div>

I cover many of the details on AJAX in my article jQuery AJAX, but here I want to go over the variables we are passing and where we store that information on the page.

var item: This is the entry in the list that we are moving from one point to another in the list(s).
var container: The source container for the list item to be moved.

var position = The new position of the item in the list.

var section = Id of the item being moved

var queue = List of the container to where the item was moved.



So with these variables, we can take an item from list 1, and move it to list 2 and store the information for a later day. Notice that as part of my data element I am passing the items back in an “object”. The codebehind equivalent looks like this:



public class TaskSequence

{

public int Seq { get; set; }
public string ItemID { get; set; }
public string ListID { get; set; }

}


This essentially allows my users to organize their information into visually distinct lists.

Thursday, August 30, 2012

jQuery AJAX


One of the more common items I use with jQuery is AJAX (Asynchronous JavaScript And XML).  Specifically, I tend to use it when I want to give the user some feedback from long lists (.autocomplete) or I want to record the change the user made on the webpage(.sortable).  What is nice is that the calls for each of these are very similar and easy to understand once you have worked with the code once or twice.

For .autocomplete

               source:
                  function (request, response) {
                      $.ajax
                  ({

                      url: " Default.aspx/GetNames",

                      data: "{name:" + JSON.stringify(request.term) + "}",

                      dataType: "json",

                      type: "POST",

                      contentType: "application/json; charset=utf-8",

                      success: function (data) {
                          response(data["d"]);                      },

                      error: function (xhr, callStatus, errorThrown) {
                          alert(callStatus);

                      }

                  });

                  }

For .sortable

                update: function (e, ui) {

                    var item = ui.item;

                    var container = item.parent();

                    var position = (ui.item).index();

                    var section = item.attr("id");

                    var queue = container.attr("listId");

 

                    $.ajax({

 

                        type: "POST",

                        contentType: "application/json",

                        url: "Default.aspx/SaveList",

                        data: "{ ItemData: " + JSON.stringify({ Seq: position + 1, ItemID: section, ListID: queue }) + " }",

                        dataType: "json",

                        error: function (XMLHttpRequest, textStatus, errorThrown) {

                            debugger;

                        },

                        success: function (feedback) {

 

                        }

                    });

                }

The main difference in the code is not in how the method is called but in what is returned.  So let’s break down the basics of what we are passing:

Type:  This will typically contain the value “POST” or “GET”.  I tend to use POST so that the information is contained in the body of the message, and not encoded in the URL by the browser.

contentType:  In the examples above we specify JSON as the data interchange format for the transaction.  This is nice in that it is in a human readable format that makes debugging easier.

url:  Where we will post the data.  Both the examples above post back to a WebMethod.  This is a pretty convenient way to handle the data, but if you choose, you could also post back to a webservice.

Web Method: url: "Default.aspx/SaveList",
Web Service: url: "Default.ashx?obj1=" item1 + "&obj2=" + item2",

data:  This is the data you are passing to the WebMethod.  In the examples above I have used two different techniques for handling the data but both really equate to the same thing.  The first example passes data to an individual parameter on the method.  The second passes a single parameter that corresponds to an object that the method is expecting.

data: "{ ItemData: " + JSON.stringify({ Seq: position + 1, ItemID: section, ListID: queue }) + " }",

This line corresponds to the following class which happens to be the object type the webmethod is expecting.  You may notice that while Seq is an int  but the other two IDs are both strings.  That is because I tend to encrypt all the ids on my forms.

 
public class ItemFromWeb
{
public int Seq {get; set;}
public string ItemID {get; set;}
public string ListID {get; set;}
}

 
[WebMethod]
public static bool SaveList(ItemFromWeb ItemData)
{
return true;
}

 
dataType:  This defines the type of data we are expecting back from the server. 

 
error:  Put in some error handling.

 
success:  Handle any data that was returned by the call.  This will be important in a later post where we will talk about how to handle appending items to the end of text in a textbox using autocomplete.