Tuesday, June 16, 2009

JavaScript & CSS Modal Loading DIV

Things I've used in this:
What I do here is build a DIV element and show it on the page while Prototype's Ajax Request object is loading. Then, when the Request is finished, the DIV is removed from the document.

Here is the script necessary to make a request and build/show/remove the DIV.

   1:  /** Main.js
   2:   * @author Jim Schubert
   3:   * (c) 2009
   4:   */
   5:   
   6:  function showContent(file){
   7:      var content = new Ajax.Request(file,
   8:          {
   9:              method:'get',
  10:              onLoading: showLoading(),
  11:              onSuccess: function(request)
  12:              {
  13:                  var contentDIV = document.getElementById('content');
  14:                  contentDIV.innerHTML = "";
  15:                  contentDIV.innerHTML = request.responseText;    
  16:                  
  17:                  closeLoading();                        
  18:              },
  19:              onFailure: function(){ alert('Cannot process your request.');}
  20:              // onComplete: closeLoading()
  21:          });
  22:  };
  23:   
  24:  function onImgError(source) {
  25:    source.src = "img/img_error.png";
  26:    // disable onerror to prevent endless loop
  27:    source.onerror = "";
  28:    return true;
  29:  };        
  30:   
  31:  function showLoading() {
  32:      // create div element
  33:      var overlayDIV = document.createElement('div');
  34:      var loadingDIV = document.createElement('div');
  35:      overlayDIV.setAttribute('id', 'overlay');
  36:      overlayDIV.setAttribute('class', 'overlay');
  37:      overlayDIV.style.visibility = 'visible';
  38:      
  39:      loadingDIV.setAttribute('id', 'loading');
  40:      loadingDIV.setAttribute('class', 'modalPopup');
  41:      loadingDIV.innerHTML = '<center><img src="img/ajax-loader.gif"><br>Loading...</center>';
  42:          
  43:      overlayDIV.appendChild(loadingDIV);
  44:      var content = document.getElementById('bodyDocument');
  45:      if (content) {
  46:          content.appendChild(overlayDIV);
  47:          var overlay = document.getElementById('overlay');
  48:          if (overlay) {
  49:              overlay.style.visibility = 'visible';
  50:              overlay.style.height = '100%';
  51:          }
  52:      }
  53:      
  54:      return true;
  55:  };
  56:   
  57:  function closeLoading(){
  58:      var overlayDIV = document.getElementById('overlay');
  59:      var loadingDIV = document.getElementById('loading');
  60:      
  61:      if (overlayDIV) {
  62:          if (loadingDIV) {
  63:              overlayDIV.removeChild(loadingDIV);
  64:              document.getElementById('bodyDocument').removeChild(overlayDIV);
  65:          }
  66:          // else {alert("can't find loadingDIV")}
  67:      }
  68:      // else{ alert("Can't find overlay.");}
  69:      
  70:      return true;
  71:  };


Here is the stylesheet needed to make the dialog "modal".
   1:  .overlay {
   2:      visibility: hidden;
   3:      position: absolute;
   4:      left: 0px;
   5:      top: 0px;
   6:      width:100%;
   7:      height:100%;
   8:      text-align:center;
   9:      z-index: 1000;    
  10:      filter:alpha(opacity=70) !important;
  11:      opacity:0.8 !important;
  12:      elevation:above !important;
  13:      /* background-color:Gray !important; */
  14:      background-image: url(../img/overlay.png);
  15:  }
  16:   
  17:  .modalPopup 
  18:  {
  19:      display: block;
  20:      margin-left: auto;
  21:      margin-right: auto;    
  22:      width:180px;
  23:      margin: 100px auto;
  24:      background-color:#F1F1F1 !important;
  25:      border:1px solid #000;
  26:      padding:15px;
  27:      text-align:center;
  28:      elevation:above !important;
  29:  }

In order to use this code, you'll have to give your body tag an id of 'bodyDocument', and the div tag to receive your ajax request should be called 'content'.
I've also included an image error detecting script, which replaces broken images with a default image. Unfortunately, if you're trying to produce 100% compliant HTML documents, this won't be compliant unless you're using HTML5. In order to use this, you'll have to do something like <img src='asdf.gif' onerror='javascript:onImgError(this)' alt='image'>
I've left some code commented out, which will help in debugging your efforts. And, in the stylesheet, you have the option of using a flat background instead of a PNG with transparency.

Monday, May 18, 2009

Example Ruby code

I decided to do some of those Facebook puzzles in Ruby. I won't post everything I do, because I would consider that cheating (after all, you can win prizes!).

However, considering this is a very simple script, and I'm doing it more for learning Ruby than to enter into Facebook's puzzles, I will post this one.

This is the first puzzle, called Hoppity Hop:

private
@file_exists = false
def get_integer(filename)
    if File::exists?(filename)
        file = File.open(filename) 
        line = file.gets.strip!
        file.close
        @file_exists = true
        return line.to_i
    else
        @file_exists = false
        return 0 #zero files present
    end
end

def get_string(num)
    if(num%3 == 0 && num%5 == 0)
        print "Hop\n"
    elsif num%3 == 0
        print "Hoppity\n"
    elsif num%5 == 0
        print "Hophop\n"
    else
        return #nothing
    end    
end

def hip_hop(arg)
    num = get_integer(arg)
    if(num > 0 && @file_exists)        
        for i in 1..num.to_i
            get_string(i)
        end
    else
        puts "File not found"
    end
end

public

arg = ARGV[0].to_s # this is the name of the file
if(/\D/ =~ arg)
    puts "Please enter a positive integer as the filename."
else
    unless arg == nil
        hip_hop(arg)
    end
end

Saturday, May 9, 2009

Ruby on Rails, Aptana Studio

This weekend, I decided to give Ruby on Rails a go, considering I just finished school and I'll have plenty of free time to explore.
I downloaded Aptana Studio and installed Ruby, Rails, PHP, and a few extra ruby gems for fun. Then, I went over to the Rails Guide to follow along and do some learnin'. At the end of the guide, I ran the completed blog application and received errors. A little googling helped me find the solution.
Apparently, Aptana doesn't install the latest build of gems from its repositories, and the guide was written for the newest version.
As noodlygod writes on the forum linked above:
Hello, I just thought I'd post something as I had the same problem on Windows.
I tried running the command "gem install rails --source http://gem.rubyonrails.org" but I received the error: "actionpack requires rack (>= 0.9.0, runtime)"
So I ran "gem install rack" which installed something And then "gem install rails --source http://gem.rubyonrails.org" and it installed 2.3.0 just fine.
Based on this post: http://railsforum.com/viewtopic.php?pid=89050 I also changed my rails version in environment.rb to "2.3.0" and renamed "application.rb" to "application_controller.rb" and everything is working. Thanks a bunch for the info!

Thursday, April 30, 2009

Useful Serialization Methods of LINQ to SQL objects

I am just going through a project for my senior "Projects in Information Systems" class, commenting most of the complex logic.  I came across these two methods I wrote to serialze LINQ to SQL objects.  They came in pretty handy, so I thought I'd share even though they don't have error-handling.  I'm not too embarrassed. 
The way I used them was pretty ghetto, I was having troubles getting the objects I needed to serialize to be used in a Session object (I thnk it had something to do with an Order_Details table having two foreign keys to the same table, Ledger, for an IN and OUT field).  Anyway, I serialed the object to XML and just stored the whole string into a listBox's value.  I know that's begging for poor performance, and overriding the data validation checks is opening the ASP.NET page up for security issues, but the only people who are going to use this are me and my instructor.  So, it was a quick work around. I could have stored it in a Session Object as a string, but then I would have had to call some funky work around for the listBox.  Anyway, enough about that.
   1:   
   2:          /// <summary>
   3:          /// Serializes a LINQ object to an XML string
   4:          /// </summary>
   5:          /// <typeparam name="T">Type of the Object</typeparam>
   6:          /// <param name="linqObject">The LINQ object to convert</param>
   7:          /// <returns>string</returns>
   8:          public static string SerializeLINQtoXML<T>(T linqObject)
   9:          {
  10:              // see http://msdn.microsoft.com/en-us/library/bb546184.aspx
  11:              DataContractSerializer dcs = new DataContractSerializer(linqObject.GetType());
  12:   
  13:              StringBuilder sb = new StringBuilder();
  14:              XmlWriter writer = XmlWriter.Create(sb);
  15:              dcs.WriteObject(writer, linqObject);
  16:              writer.Close();
  17:   
  18:              return sb.ToString();
  19:          }
  20:   
  21:          /// <summary>
  22:          /// Deserializes an XML string to a LINQ object
  23:          /// </summary>
  24:          /// <typeparam name="T">The type of the LINQ Object</typeparam>
  25:          /// <param name="input">XML input</param>
  26:          /// <returns>Type of the LINQ Object</returns>
  27:          public static T DeserializeLINQfromXML<T>(string input)
  28:          {
  29:              DataContractSerializer dcs = new DataContractSerializer(typeof(T));
  30:   
  31:              TextReader treader = new StringReader(input);
  32:              XmlReader reader = XmlReader.Create(treader);
  33:              T linqObject = (T)dcs.ReadObject(reader, true);
  34:              reader.Close();
  35:   
  36:              return linqObject;
  37:          }
  38:   

Saturday, April 25, 2009

Storing Generics in ASP.NET Profile object

Sometimes, I'll come across a problem that I research for an hour or two. When I find the solution, I think "Wow, that should have been the first thing I tried!"
This is one of those occasions. 

I decided to use the ASP.NET profile instead of Session objects to store a list of products.  So, in web.config, I tried a number of "work-arounds" that I found online, including:

   1:  <profile>
   2:  ...
   3:        <properties>
   4:          <add name="RecentlyViewed" allowAnonymous="false" type="System.Collections.Generic.List`1[Model.Product]" serializeAs="Xml"/>
   5:        </properties>
   6:  </profile>


The problem I was having, and it seems a lot of people are having, is that System.Collections.Generic.List`1[Model.Product] throws an error. For some people, it seems to work. Well, I tried changing the lt and gt in the generic list so the XML would parse it as it is written in the code-behind. That didnt work.

The solution: Create a class which inherits from List<Model.Product>

For instance:

   1:  using System;
   2:  using System.Collections.Generic;
   3:   
   4:  namespace Model
   5:  {
   6:      /// <summary>
   7:      /// This class wraps the Generic List into a class to serialize in Profile provider
   8:      /// </summary>
   9:      [Serializable]
  10:      public class RecentlyViewed : List<Model.Product>
  11:      {
  12:          public RecentlyViewed()
  13:          {
  14:          }
  15:      }
  16:  }

This works beautifully! Now, in web.config, you can do the following:

   1:  <profile>
   2:  ...
   3:        <properties>
   4:          <add name="RecentlyViewed" allowAnonymous="false" type="Model.RecentlyViewed" serializeAs="Xml"/>
   5:        </properties>
   6:  </profile>

Tuesday, April 14, 2009

Displaying multiple fields in a Dropdownlist's DataTextField

I've encountered this problem on occasion, where I want to display more than one field in a dropdownlist's DataTextField property.  In the past, I've overcome this problem by rewriting a SQL statement, or adding another column in the database itself to accomodate my needs.

In one of my classes (INFO 465: Projects in Information Systems @ VCU), we're working from a database which we're not allowed to change.  The reason we can't change it is because the instructor uses the same database for his examples.  I could just write another method into my business logic layer, but it would get cluttered pretty quickly.
So, I decided to make use of LINQ and found the following solution:

   1:  ddlUsers.DataSource = BLL.Employee.GetEmployees()
   2:                  .Select(be => 
   3:                      new { 
   4:                          ID = be.Id, 
   5:                          FullName = String.Format("{0}{1}{2}", 
   6:                                      be.LastName,
   7:                                      (!string.IsNullOrEmpty(be.FirstName) ? ", " : string.Empty),
   8:                                      be.FirstName)
   9:                          }).AsEnumerable();


This takes the List of Business Entity objects and uses the LINQ select statement to generate an implicit/anonymous object from that. The only downfall to this method is that the new object only has local scope. But, since I'm only using this in a dropdown, it's a pretty nifty trick.

Wednesday, April 1, 2009

T-SQL Multi-Table Delete

I was trying to run a DELETE query on multiple tables and I kept getting this error: The DELETE statement conflicted with the REFERENCE constraint
I'm not that great with SQL, but I can get by.  DELETEs have always been somethng that have given me trouble.  So, I thought I'd share this simple fix.
DELETE FROM PRODUCT
FROM BOOK
WHERE BOOK.ID = PRODUCT.BOOK_ID
AND BOOK.ID = @BOOK_ID


You just have to make sure you put the table with the FK as the first table in the query.
I guess I should have paid a little more attention in Database class.  We learned Oracle, which is different from Microsoft's SQL in many ways.

Saturday, March 28, 2009

LINQ: more like "Luckily I Never Quit"

I've been using LINQ quite a bit lately. As the blog title says: luckily, I never quit.

There are a lot of things to get used to with LINQ. For one, it uses deferred queries. When you make a change, you must submit changes before the change is reflected in the database. Yes, this mirrors the actions when working directly with a database (COMMIT), but when you're thinking of it as application logic, it seems counter-intuitive.

<aside>

At school, I'm in a class called INFO 465: Projects in Information Systems. The class is slow-going. At VCU, there are three tracks of studies in Information Systems: Application Development, Business Analysis, and Network Administration. Unfortunately, most of the people in BA and Networking are there because they don't want to do any programming at all. You would think a class geared to using your course skills would accommodate each track equally?

That's not the case in this class. There are two projects. One is individual work and the other is group work. The individual project is really just a large programming assignment to create an "Enterprise System" for a landscaping company. Luckily, the company consists of the landscaper, a truck, and his helper.

Anyway, to get back on track, we're allowed to do our project any way we want. Most of the people in the class chose to do Windows Forms using VB.NET examples provided by the teacher. Good luck with that! I chose to use ASP.NET, AJAX, Web Services, and LINQ. I chose this route because I wanted this class to be a learning experience, not just a copy-paste session for 3 hours a week.

</aside>

Back to LINQ. To be quick about development, I've decided to use GridViews, DetailsViews, and LinqDataSources. Every time I try to link a LinqDataSource to a GridView's selected key, I get this message:

Operator '==' incompatible with operand types 'Int32' and 'Object'

Here is an example of the LinqDataSource that throws this error:

<asp:LinqDataSource ID="srcSelectedOrder" runat="server" 
        ContextTypeName="INFO465_First_Web.DatabaseMaps.OrdersDataContext" 
        EnableDelete="True" EnableInsert="True" EnableUpdate="True" TableName="Orders" 
        Where="Id == @Id">
        <WhereParameters>
            <asp:ControlParameter ControlID="GridView1" Name="Id" 
                PropertyName="SelectedValue" Type="Int32" />
        </WhereParameters>
    </asp:LinqDataSource>
The problem is where you have the Where clause "Id == @Id". For some reason, the data source thinks @Id is an object instead of an Int32, even though Type="Int32" in the WhereParameters.

The fix is the change this to Where="Id == Int32?(@Id)". I don't know why this is. I mean, if you're taking a primary key as the DataKeyName, it is being passed as Int32 in the WhereParameters, why do you have to cast it? Maybe the LinqDataSource automatically converts Id == @Id to an SQL query that would look like "Id == '2'", and you have to cast to Int32 explicitly so it will look like "Id == 2" in the query? Again, this is another place that LINQ just seems backwards.

Here is the fixed data source:

<asp:LinqDataSource ID="srcSelectedOrder" runat="server" 
        ContextTypeName="INFO465_First_Web.DatabaseMaps.OrdersDataContext" 
        EnableDelete="True" EnableInsert="True" EnableUpdate="True" TableName="Orders" 
        Where="Id == Int32?(@Id)">
        <WhereParameters>
            <asp:ControlParameter ControlID="GridView1" Name="Id" 
                PropertyName="SelectedValue" Type="Int32" />
        </WhereParameters>
    </asp:LinqDataSource>

(I always format my code with http://www.manoli.net/csharpformat/)

Thursday, March 19, 2009

C++ Templated QuickSort Algorithm

It has been over a month since I posted. I've been really busy with all of my classes. So, instead of going too in depth with anything, I'm just going to share some code we've written. This is a QuickSort Algorithm that we adapted from the MIT Intro to Algorithms book. We just finished it last night (less than 12 hours ago), so it's not fully tested.
   1:  #ifndef _QUICKSORT_H
   2:  #define _QUICKSORT_H
   3:   
   4:  #include <vector>
   5:   
   6:  using namespace std;
   7:   
   8:  namespace QuickSort
   9:  {
  10:      
  11:  /* 
  12:      QuickSort Algorithm using Templates
  13:  
  14:      Algorithm was adapted from:
  15:          Introduction to Algorithms
  16:          By Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein
  17:          Contributor Thomas H. Cormen
  18:          Edition: 2, illustrated
  19:          Published by MIT Press, 2001
  20:          ISBN 0262032937, 9780262032933
  21:          1180 pages
  22:      Accessed March 2009
  23:      via http://books.google.com/books?id=NLngYyWFl_YC
  24:      See pages 145-147
  25:  
  26:  */
  27:      template<class T>
  28:      class QuickSort
  29:      {
  30:      public:
  31:          vector<T> *sortingArray;
  32:          int left;
  33:          int right;
  34:   
  35:          // Constructors
  36:          QuickSort();
  37:          QuickSort(vector<T> *sortArray);
  38:          QuickSort(vector<T> *sortArray, int startIndex, int endIndex);
  39:   
  40:          /**********************************************************************
  41:          * Partition and Swap Functions
  42:          **********************************************************************/
  43:          int Partition(vector<T> *sortArray, int startIndex, int endIndex);
  44:          void Swap(int l, int k);
  45:   
  46:      };
  47:   
  48:      template<class T>
  49:      QuickSort<T>::QuickSort()
  50:      {
  51:          sortingArray = new vector<T>();
  52:          left = 0;
  53:          right = 0;
  54:      }
  55:   
  56:      template<class T>
  57:      QuickSort<T>::QuickSort(vector<T> *sortArray)
  58:      {
  59:          int startIndex = 0;
  60:          int endIndex = 0;
  61:   
  62:          endIndex = (int)(*sortArray).size() - 1;
  63:   
  64:          QuickSort(sortArray, startIndex, endIndex);
  65:      }
  66:   
  67:      template<class T>
  68:      QuickSort<T>::QuickSort(vector<T> *sortArray, int startIndex, int endIndex)
  69:      {
  70:          if(startIndex >= endIndex)
  71:          {
  72:              return;
  73:          }
  74:   
  75:          // *initialize* the array
  76:          sortingArray = sortArray;
  77:   
  78:          // For instance: 1..n
  79:          left = startIndex;
  80:          right = endIndex;
  81:   
  82:          if(left < right)
  83:          {
  84:              // get pivot
  85:              int pivot = Partition(sortingArray, left, right);
  86:   
  87:              // sort left side
  88:              QuickSort(sortingArray, left, (pivot-1));
  89:   
  90:              // sort right side
  91:              QuickSort(sortingArray, (pivot+1), right);
  92:          }
  93:      }
  94:   
  95:      template<class T>
  96:      int QuickSort<T>::Partition(vector<T> *sortArray, int startIndex, int endIndex)
  97:      {        
  98:          // initially this start - 1 when startIndex is 0.
  99:          int l = startIndex - 1;
 100:          int k = endIndex;
 101:   
 102:          for(int i = startIndex; i <= k - 1; i++)
 103:          {
 104:              // Go until you find a value smaller than the last value.
 105:              if((*sortArray)[i] <= (*sortArray)[k])
 106:              {
 107:                  // increment l
 108:                  l++;
 109:   
 110:                  // swap i and j
 111:                  // NOTE: this is supposed to swap j with itself the first time.
 112:                  Swap(l, i);        
 113:              }
 114:          }    
 115:          
 116:          // when loop is finished, swap 
 117:          Swap(l + 1, k);
 118:   
 119:          return l + 1;
 120:      }
 121:   
 122:      template<class T>
 123:      void QuickSort<T>::Swap(int l, int k)
 124:      {
 125:          // create temp variable
 126:          T tmp;
 127:          
 128:          // store first element in temp
 129:          tmp =(*sortingArray)[l];
 130:   
 131:          // swap second element to first element
 132:          (*sortingArray)[l] = (*sortingArray)[k];
 133:   
 134:          // put temp variable in second element
 135:          (*sortingArray)[k] = tmp;
 136:      }
 137:   
 138:  }
 139:   
 140:  #endif

Archive