Thursday, May 29, 2014

A Few SQLite Tips

 
 SQLite http://sqlite.org/ is an open source database that is written in C.  It is similar to say an access .mdb file or a Microsoft SQL Server CE file only databases in that it is a file and runs in the same process (well, some caviots here with newer mods to SQLite but I'm not familiar enough there to comment) as your deployed program.  It is used by Firefox, Chrome, a lot of phone app developers, and now by me.  SQL Server is overkill for many of the little web applications I write and although I like SQL Server Compact Edition it looks like it is dead in the water [LINK].

1) Once you have created a table in SQLite, you cannot add a new column to that table with the alter command that has a default value [LINK].

2) It seems like time for SQLite is defaulted to GMT, which in my opinion is a good thing.  For default dates in tables, use CURRENT_TIMESTAMP.

3) SQLite-Net looks really cool, but I haven't been able to hack it to work for web development.  If you are using Windows 8 and developing APPS or Desktop applications, take a look at it. [LINK].

4) A really great and free GUI manager for SQLite is a plugin for Firefox called SQLite Manager. Look for it in the Firefox Plugins.  More info [LINK].

5) It looks like the main .Net SQLite Data Connection enabler is System.Data.Sqlite.  The full Nuget package contains Linq and Entity Framework support.  More info [LINK].

6) There is a version of SQLite written in managed .net code, but it looks like it is no longer being revised.  Maybe Microsoft will pick it up.  Info [LINK].  You might be able to hack SQLite-net to use this version, as it looks like it was originally intended to use it.  I tried for a few hours but gave up.  Maybe I'll take another stab at it.

7) There are no stored procs with SQLite (although I believe there is a fork in development that supports that, but I'm not sure how stable it is).  You can however create user defined functions.

8) When to use SQLite [LINK].

9) Interestingly, if you try to connect to a SQLite DB that doesn't exist the SQLite Connection object will create a new blank DB file for you with the name that you were looking for.  This actually caused me some confusion as has an extra character in my connection string and suddenly I couldn't query any of my tables...duh, they didn't exist because I was querying a new database.

10) If you are familiar with Transact SQL and Microsoft SQL Server (or MySQL, Postgress, Oracle) I don't think you will have any problems using SQLite.

11) Data types on columns are more recommendations than set and fast.  I believe if you try you can save strings in int fields and mix and match.  This might have changed with the 3.x version but from what I have been reading this at lest used to be very true.  Who knows in some cases this could be a good thing, but in most if you aren't careful this might cause havoc.

12) For bulk inserts you want to use SQLite transactions else SQLite will be very slow [LINK]

13) SQLite select queries are CASE SENSITIVE by default.  You can get around this by using COLLATE NOCASE after your where condition like select * from mytable where colum1 = @somevalue COLLATE NOCASE.  A post explaining the particulars can be found [HERE].

14) There is no "Select top * or Select top 10" in SQLite.  Instead use limit. Example: "Select blah from mytable where blah order by blah limit 10"

I got my start in web development using classic ASP and Access MDB databases.  I could crank stuff out FAST.  I think now for some of my projects using MVC (thought without most of the MVC, just using Razor pages almost like development with WebMatrix) and SQLite might be a sweet spot for me as far as making development fun and productive.  I plan to update this page as I find more little quirks using SQLite with ASP.Net.  I also will be posting some source code examples.

Tuesday, May 27, 2014

Fixing Telerik's RadToolTip After Latest Releases Broke It

Scenario


Ok, so I had the following scenario.  I was using a Telerik Radgrid with a gridtemplate column that displayed user comments.  Often the comments were long so I would truncate the comment text that would be displayed, and then I add a RadToolTip with the target of the comment label in the grid that on hover would display the full comment text in a tool tip.  But then something happened...the latest changes broke the tool tip so that if I did anything on the grid like sort, update a row, whatever often the comment tool tip would become blank.  I read that it has something to do with how the radtooltip now stores it's content in the viewstate...well that was the excuse, but IMHO it is broke as it worked before and it doesn't work now.

The Fix


Step 1) Add a RadToolTipManager to your page, outside of your update pannels.  Here is an example


   <telerik:RadToolTipManager ID="RadToolTipManager1" runat="server" OnAjaxUpdate="RadToolTipManager1_AjaxUpdate"  
    RelativeTo="Element" Position="TopLeft" Width="450" ManualClose="True" ShowDelay="600"  
    Title="Comments">  
   </telerik:RadToolTipManager>  

Notice there is an OnAjaxUpdate method.  You will have to add that in your code behind, but let's worry about that in a second.

Step 2: Add a or update an existing RadGrid ItemDataBound event so we can add a tool tip on to each comment field.


 if ( e.Item.OwnerTableView.Name == "MasterTableName" && ( e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem ) )  
    {  
     Control cntl = e.Item.FindControl ( "mylabelintemplatecontrolidwithtruncatedtext" );  
     if ( cntl != null )  
     {  
      if ( this.RadToolTipManager1 != null )  
      {  
       this.RadToolTipManager1.TargetControls.Add ( cntl.ClientID, true );  
      }  
     }  
    }  

Note: I'm doing the e.Item.OwnerTableView.Name check because I'm using a grid with detail tables. If you don't have any detail tables you can skip that part of the check.  You might also add in a check to make sure the Radgrid is in read only mode, I didn't but I might go back and do that just to make it more efficient.

Step 3) Add your RadToolTipManager Ajax update method.


   protected void RadToolTipManager1_AjaxUpdate ( object sender, Telerik.Web.UI.ToolTipUpdateEventArgs e )  
   {  
    for ( int i = 0 ; i < MyGridView.Items.Count ; i++ )  
    {  
     if ( MyGridView.Items[ i ].OwnerTableView.Name == "MasterTableName" && ( MyGridView.Items[ i ].ItemType == GridItemType.Item || MyGridView.Items[ i ].ItemType == GridItemType.AlternatingItem ) )  
     {  
      /* unfortunately only get client ID back on ajax method, so we have to loop to find matching client ID */  
      Control cntl = MyGridView.Items[ i ].FindControl ( "mylabelintemplatecontrolidwithtruncatedtext" );  
      if ( cntl != null && cntl.ClientID == e.TargetControlID )  
      {  
       /* get row ID number */  
       int myID = Convert.ToInt32(MyGridView.Items[ i ].GetDataKeyValue ( "myID" ));  
        /* now get full comment text out of the database */  
        var rv = ( from myrow in ( (DataView)MyDataSet.Select ( DataSourceSelectArguments.Empty ) ).ToTable ().AsEnumerable ()  
              where ( myrow.Field<int> ( "myID" ) == myID )  
              select myrow ).FirstOrDefault ();  
       Label lblInsideToolTip = new Label ();  
       lblInsideToolTip.Text = rv[ "mycommenttextfield" ].ToString ();  
       e.UpdatePanel.ContentTemplateContainer.Controls.Add ( lblInsideToolTip );  
      }  
     }  
    }  
   }  

Ok, a few comments on Step 3.  I could only get the ClientID of the target control from the Telerik.Web.UI.ToolTipUpdateEventArgs object, so I had to loop through all of my RadGrid items and then try match client ID's of the column I was looking for.  Kind of a bummer. I elected to grab the comment text from the Dataset itself.  There are other ways of doing this.  Also this is just demo code, you might want to add this in a big try catch or at least check for more nulls.

Conclusion


This seems to work.  I can sort, edit, insert rows and now the comment field's tool tip is always current.  I hope this code helps. Also be sure to add the using System.Linq at the top of the page in your code behind if it isn't there.


Tuesday, May 13, 2014

Web API 2 CRUD Basic Example

Here is a basic Microsoft Web API 2 CRUD example.  The Source code is [HERE] (this gives you the full directory and list of files, just File->Download to download the full zipped project).  I used Visual Studio 2013 and local DB.  I'm not using MVC or any ORM / Entity Framework stuff...this is a very basic example to help get you going.

You will need to change the database path in the web.config file.



Happy Coding!

Monday, May 12, 2014

SQL Dates in Where Clauses

I always forget how to do this, so I'm making a post more for my quick reference than anyone else's.  Anyway, this format should work not matter what culture you format your dates in...using Microsoft SQL Server variants anyway...

WHERE datetime_column BETWEEN '20081220 00:00:00.000'
                          AND '20081220 23:59:59.997'

'YYYYMMDD HH:MM:SS:XXX' xxx being milliseconds.

More information here-

http://stackoverflow.com/questions/1947436/datetime-in-where-clause

Thursday, April 24, 2014

Javascript GUIDs

It seems a lot of bright people have come up with Javascript implementations of GUIDs. The problem with them all seems to be the way Javascript handles both time and randomness. Also different browsers have their hang ups. Anyway, here is a solution that though not perfect has a good chance of generating SQL compliant GUIDs in Javascript with a very low (but not impossible) chance of collisions. Comments welcome.

 function generateUUID(){  
   var d = new Date().getTime();  
   var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {  
     var r = (d + Math.random()*16)%16 | 0;  
     d = Math.floor(d/16);  
     return (c=='x' ? r : (r&0x7|0x8)).toString(16);  
   });  
   return uuid;  
 };  

The above var d = new Date().getTime() can be improved by some modern Javascript features, but I'm not sure how supported they are. Here are some additional links with good information about Javascript GUIDs and problems with cryptography, randomness, and collisions.

http://slavik.meltser.info/the-efficient-way-to-create-guid-uuid-in-javascript-with-explanation/
http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
http://stackoverflow.com/questions/6906916/collisions-when-generating-uuids-in-javascript
http://af-design.com/blog/2008/09/05/updated-javascript-uuid-generator-v03/



Tuesday, March 25, 2014

Telerik UI Designer Fix for Asp.Net Ajax

Having trouble with Telerik UI in design mode (btw, I don't usually even look at web form pages in design mode anymore, but some still do).  If you get some weird stuff happening, this might be your fix.

Go to whatever visual studio version you are using and open the visual studio command prompt in admin mode (right click the shortcut, run as administrator...the command prompt might be named something slightly different depending on what version of VS you are using).

Then copy / paste this into the command prompt (changing this slightly for whatever version of the .net framework telerik version your have installed, if you have multiple versions installed do this for each one). Also note depending on what version of the Telerik controls you have installed, you might have to change the "UI for ASP.Net...." path to whatever path your telerik bin lies in.


 gacutil /i "C:\Program Files (x86)\Telerik\UI for ASP.NET AJAX Q1 2014\Bin40\Telerik.Web.Design.dll  

I hope this helps someone, credit goes to my boss for finding this.

Sunday, March 16, 2014

Software Tip: HWMonitor from CPUID

In the process of upgrading my laptop's hard drive I had noticed that my machine was running a little hotter than it should be.  In the process of trying to diagnose why I found this little utility for Windows machines called HWMonitor, which comes in a free and pay for version.  It gives you nice real time stats on voltage, temp, and wear and tear on your laptop's battery.

http://www.cpuid.com/softwares/hwmonitor.html

Samsung SSD 840 EVO 250 GB Upgrade



Update! See gotcha at the end.

Why the Upgrade


So I have been putting my laptop through it's paces.  It is on about 14 hours a day 7 days a week.  I think on several occasions I've packed it up and accidentally left it on.  I recently noticed the hard drive start to "click".  I ran some utilities on the hard drive and everything came back as the drive was healthy, but I noticed my drive starting hang coming out of sleep mode.  Rather than take the risk of being down for a while, I decided to install a new drive.  I selected a Samsung SSD 840 EVO.  I didn't want to spend too much money so I went with a 250 GB model, which I now kind of regret.  I wish I would have ponied up for a 500 GB version, but that is what I get for being frugal.  I believe Seagate makes a hybrid SSD drive that cost a lot less per Gigabyte that might be worth looking into.  I went vanity and wanted to get a full SSD though.

Why the Samsung SSD 840 EVO 

  •  Samsung had the lowest failure rate (from the data I could find) out of all the manufactures.  I also saw some videos online about the predicted failure rate of this SSD was into decades even with heavy use per day.
  • I've had great luck with Samsung products in the past.
  • The drive came with some cloning software.
  • The drive came with a mounting kit for desktops (in the future) and a USB 2 to Sata cable.
  • I couldn't afford the pro version, but both versions had very fast read and write rates compared to other SSD's.
I paid a little bit more (about $50) for the Samsung but with the cloning software and USB 2 to Sata cable I figured the price was about even.

Upgrade Walkthrough

  1. I backed up all my critical data (just in case) on both an external and a flash thumb drive
  2. Install the included software (one gotcha, the "Samsung Magician" software seemed to hang at the end of install, but I reinstalled it and everything was fine).
  3. I plugged in the Samsung SSD to a USB port.
  4. I fired up the cloning software.  Essentially you hit start, click a few things, and then let it rip.  The first time I ran it it seemed to hang and I got impatient and cancelled.  I rebooted and ran the "Data Migration" (the cloning part of the software) again and it hung at the same spot.  I let it run this time and eventually the cloning completed (A little over two hours for about 196 gigs).
  5. I shut down, swapped the SSD for my current hard drive, then rebooted.
  6. The SSD did not boot as it said there was a boot error on boot up.  This had something to do with Windows 7 copy protection.  So I found a Windows 7 install disk and booted off it, and ran repair.  That took about five minutes and then I rebooted.  This time the SSD booted normally.  Done!

A Few Gotchas and Suggestions

  • If you can afford it, get the 500 gig version if you are on the fence.  I ended up getting a 128 Gig USB 3.0 drive to keep some of my junk files in, I realize now I should have just got the 500 gig version of the SSD.  Oh well.
  • Buying a Sata to USB 3 cable (comes with some drive enclosures I think) the cloning can be done probably a lot faster.
  • You do need a Windows install disk if you are using modern versions of Windows so you can run the system repair after cloning the drive.
  • Before cloning the drive, I would remove all the junk you can off your drive (delete or move to external) so the cloning will go faster (if using USB 2).
  • I originally tried to clone the drive with 230 gigs, the cloning software said that was too large.  So even though you are buying a 250 GB drive what you can clone is probably closer to 200 gigs.

Result


Is my computer faster now?  Yes.  It boots up faster, and applications load faster compared to my old 5400 RPM drive.  I haven't done any heavy 3D rendering, gaming, or video editing yet so I can't really say how much faster doing that with an SSD vs a 5400 RPM hard drive is. My laptop is a lot quieter now (though some of that is due to me blowing out the fan duct).  As far as battery life, I would expect to gain a little but my batter is in pretty bad shape so I can can't accurately say.  Make sure you have a Windows install disk (you probably need the same Operating System version, but not necessarily the same version (I fixed my boot problems on my 64 bit Windows Home Premium laptop using a Windows 7 Ultimate DVD).  I will say this, I was dreading having to rebuild my machine from scratch, the cloning was sure nice.  Sure, on Windows boxes the conventional wisdom is that you need to rebuild your machine every year or two anyway, but I've had this laptop for two years running Windows 7 and it seems to be doing fine, so that cloning software sure came in handy.  Sure you can buy Norton Ghost or try to use Clonix, but the Samsung Data Migration software was nearly idiot proof and worked well.  


I am happy, I just wish I would have gotten the 500 Gig drive. Check out the Amazon prices.

Samsung Electronics 840 EVO-Series 250GB 2.5-Inch SATA III Single Unit Version Internal Solid State Drive MZ-7TE250BW

Samsung Electronics 840 EVO-Series 500GB 2.5-Inch SATA III Single Unit Version Internal Solid State Drive MZ-7TE500BW


Gotcha

One important note.  You will have to turn on system restore auto saves on your new cloned drive!

Saturday, March 15, 2014

Software Tip: Clonezilla

I've had really good luck with my latest HP laptop...but I did a few stupid things with it and now the hard drive is occasionally "clicking" and becoming unresponsive, a bad sign.  So I decided to get a new drive.  In the process of researching I found an open source alternative to Norton Ghost called Clonezilla.  Some of you might find it useful.

http://clonezilla.org/

Thursday, March 06, 2014

India and China Dominate World Programming (By Search Term Anyway)

I decided to go on a rampage and do gather some Google Trends data over the last year on keyword searches related to programming.  Globally this is what I found-

Search Term Top 3 Cities Globally
ASP.Net New Okhla Industrial Development Area, Hyderabad, Gurgaon
SQL New Okhla Industrial Development Area, Gurgaon, Hyderabad
C# New Okhla Industrial Development Area, Hyderabad, Chennai
MySQL Beijing, New Okhla Industrial Development Area, Shanghai
iOS Singapore, Ho Chi Minh City, Hanoi (San Francisco 6th, New York 9th)
Actionscript Beijing, Seoul, Saint Petersburg (San Francisco 9th)
Android Tehrān, Jakarta, Surabaya
Java Bangalore, Hyderabad, Chennai
Microsoft SQL Server New Okhla Industrial Development Area, Gurgaon, Hyderabad
Photoshop Manila, Ho Chi Minh City, Surabaya
javascript New Okhla Industrial Development Area, Beijing, Hyderabad
Node.js Beijing, Shanghai, Seoul (San Jose 4rth, San Francisco 5th, Seattle 7th, Austin 8th)
AngularJS Beijing, New Okhla Industrial Development Area, Shanghai (San Francisco 4th, San Jose 7th)
PHP Dhaka, Ahmedabad, Chennai
C++ Beijing, Shanghai, Bangalore
HTML5 New Okhla Industrial Development Area, Hyderabad, Chennai

What does this mean? It means to me that most of the world's programming is being done in India and Asia. I no longer think this is due to outsourcing from the West but I'm sure that plays a big role. In my book the future will always belong to those who have the skills and know-how to make things happen. If Google programming search term trends are any indicator, the future is belonging to India and Asia more and more. I also compared some base programming languages to each other to see how they stacked up as far as traffic.

From the data Android OS programmers in India will rule the world :)

Wednesday, March 05, 2014

Web Forms: Radio and Checkbox List Javascript Selection / Checked Manipulation

Yes, I know web forms aren't cool and all the hip kids are using MVC. Some of us are stuck enhancing existing applications (I don't want to call applications that bring in 100's of thousands of dollars "legacy").

Anyway, here is the scenario.  I've got a checkboxlist control.  I also have a radiobuttonlist with two entries, "All" and "None".  When I click on the radiobuttonlist I want to either check all the items in the checkboxlist control or uncheck all the items in the checkboxlist control.  I also wanted the checkboxlist control set so once individual items are checked the two options in the radiolistbuttonlist to be deselected / unchecked. I'm using Telerik controls so I can use a limited subset of jQuery, so I used it.

Step 1: Code Behind

On my page load I did this-

     ListItem lst1 = new ListItem ( Classes.Utility.Translate ( "AllLabel" ), "A" );  
     ListItem lst2 = new ListItem ( Classes.Utility.Translate ( "NoneLabel" ), "N" );  
     lst1.Attributes.Add ( "onclick", "SetClear(true)" );  
     lst2.Attributes.Add ( "onclick", "SetClear(false)" );  
     rdoOptions.Items.Add ( lst1 );  
     rdoOptions.Items.Add ( lst2 );  
     chkList.Attributes.Add ( "onclick", "return ClearRadioButtonList()" );  

The translate stuff don't worry about.  Just the way I do translation on the fly (for another post).  Note if you set the onclick event for each item or for all items by setting the onclick for the control rather than the items.

Step 2: Client Side

Here are a few Javascript functions I added-

  function ClearRadioButtonList() {  
     $("#<%= rdoOptions.ClientID %> input[type=radio]").prop('checked', false);  
    }  
    function SetClear(b) {  
     $("#<%= chkList.ClientID %> input[type=checkbox]").prop('checked', b);  
    }  

And it works!  I hope this helps someone.  These two pages were helpful to me figuring this out-

https://stackoverflow.com/questions/12482532/clear-radiobutton-list-selection-using-jquery
http://forums.asp.net/p/1303486/2549201.aspx


Wednesday, February 26, 2014

Web Forms: Getting the Bound DataRow Values of a Grid Row While in Read Only Mode

OK, I had a Telerik gridview, and I wanted to add a right click event on the rows that would pop a window.  I also wanted to pass some of the data elements on the row clicked in the URL string of the popup window.

On the MasterTableView I had the Primary Key ID in the DataKeyNames property, so I could get the primary key ID from the clicked row using this technique-

http://www.telerik.com/forums/how-to-create-dynamic-context-menu-in-hierarchy-grid

But what about the rest of the data?  I could try to get at the data in it's label form on the grid row, but what I really wanted was the underlying data that was bound to the grid.  After tweaking a using a little bit if Linq, I came up with this-


  protected void GridContextMenu_ItemClick ( object sender, RadMenuEventArgs e )  
   {  
    try  
    {  
     string radGridClickedRowIndex = Request.Form[ "radGridClickedRowIndex" ]; //hidden form field  
     int RowIndex = -1;  
     RowIndex = Convert.ToInt32 ( radGridClickedRowIndex );  
     GridDataItem gridRow = GridView.Items[ RowIndex ] as GridDataItem;  
     int ID = Convert.ToInt32(gridRow.GetDataKeyValue ( "ID" ).ToString ());  
     var rv = ( from myrow in ((DataView)GRIDDataSet.Select ( DataSourceSelectArguments.Empty )).ToTable().AsEnumerable ()  
           where ( myrow.Field<int> ( "ID" ) == ID )  
           select myrow ).FirstOrDefault ();  
      ...  

And then you can access items in the bound data row like this

string myvalue = rv["column_name"].ToString();


Some of you will not get what I'm talking about.  But to a certain group of people I hope this is useful. Remember to include the System.Linq namespaces at the top of the code behind page.

Friday, February 21, 2014

American IT Job Market

So every once in a while I go to dice.com and do key word searches to kind of get an idea an idea of what is hot in the job market.  I'm not looking for a new job, but I like to keep track of what employers are actually looking for.

These are the numbers that I found on my latest searches.  The take aways are up to you.

I did my search on February 20th, 2014. Listed below is the keyword I searched on and the number of jobs that were listed for the USA in the last 30 days.

Java 16109
java developer 10015
UX Developer 1024
HTML 5 2780

Flash 716
javascript 11260
c# 8240
php 3568
Objective C 1893
.net 9332
Ruby on Rails 951

iOS 2584
mobile 9230
Android 2557
Rest 3466
WPF 824
metro 640
Linux 10941
ubuntu 288

Developer 27002
Administrator 8357
Network Administrator 2988
Security 16247
Telecommute 716
cisco 4370
DBA 2569

Monday, February 03, 2014

Firefox Not Working With Visual Studio 2012 / 2013

I did the new Visual Studio 2012/13's options to select which browser you want to debug in...but I ran into a snag lately.

When Firing up a website in Visual Studio 2012 using Firefox a few weird things happened.  First, I had to login...second I got an NT/Anonymous login error...all bad.

So after a few minutes of searching I found the fix.  Left here for reference and hopefully it might help you.  The underlying problem is actually with how Firefox handles SQL authentication.  The fix is opening up about:config in Firefox and changing a few entries.  Use the instructions in the link below and add "localhost".

[Link]


Wednesday, January 22, 2014

Avoid Common CSS Problems

Here is a useful link in avoiding common CSS problems when you are creating CSS from scratch.

Problems addressed are pushing your footer to the bottom and padding issues.  Basic but if you aren't in CSS everyday but when you are you like to start from scratch this is useful.

http://helabs.com.br/blog/2014/01/21/prevent-common-problems-when-writing-css-from-scratch/

Wednesday, January 08, 2014

Combo Boxes in Windows Forms

OK, I know windows forms are viewed as ancient technology by many, but my company still uses windows forms for harnesses to test things sometimes.  It has been awhile since I used windows forms, so I ran into a slight issue in using windows forms combo boxes.

Firstly, the data binding is done slightly differently, as the combo boxes can also be bound easily to objects as well as a traditional say SQL data source.  Example of it being done in code behind on a form.

/* I got my datatable the traditional with a query to the database using a SqlDataAdapter */

mycombobox.DataSource = myDataTable;
mycombobox.DisplayMember = "description"; // your description field from your dataset
mycombobox.ValueMember = "value";  // your key field from your dataset

Slightly different mark up than the web.  Also note there is no databind() needed.

Second, getting the selected value of that combo box has a non-obvious (to me anyways) way of  getting it.  I ended up with something like this-

string selectedvalue  = ((DataRowView)mycombobox.SelectedItem).Row["value"].ToString(); //value = ValueMember

The having to cast the SelectedItem as a DataRowView makes sense when you think about it, but not something that just jumped out at me at first.

So, I hope that helps someone (including me next time I fire up an ancient windows form project).

This threat was helpful on getting the selected value http://www.xtremedotnettalk.com/showthread.php?t=93882


Friday, January 03, 2014

Building the Ultimate Dashboard

This dashboard slide deck is targeting marketing and sales people, but dashboards are useful everywhere, even in games.


45 Useful Javascript Tips

Flippin' Awesome has compiled a list of 45 useful Javascript tips in one useful spot.  Well worth checking out.

[Link]

Friday, December 27, 2013

Mobile First / Responsive Design Slide Deck

Here is a decent slide deck that talks about mobile first / responsive design.  Worth a look though.

https://app.box.com/s/guafk5lj69sxfy2g6hqr

Source: Matt Duffield

Thursday, December 19, 2013

Pondering Making Money with Google Adsense

The Goal

So here is a scenario.  You want to make 60,000 USD per year using Google Adsense.  Note this is the pre-tax amount.  Let's break down the numbers.
  • A good conversion rate would be gaining a $1 of ad revenue per 1000 hits.  The click through rate from what I've read is about 20%, and the rate you receive per click is dependent on your specific niche, but for our purposes let's shoot low and say that 200 click throughs results in one dollar of revenue.
  • So using simple match, we are going to need 60 million hits a year to generate the income we are targeting. That is 5 million hits a month, and taking an average month being 30 days that means we need about 167,000 thousand hits A DAY.

Getting Real - Part Time Blogging Revenue 

For most of us generating that many hits probably isn't going to happen.  Let's look at a more realistic scenario.
  • You generate a 1000 hits a day, 365 days a year.
  • This gives you a yearly income of $365 USD  a year.
Now the question is how much time does it take to generate a 1000 hits on a blog a day?
  • You are going to have write content fairly often , say at least 5 times a week, spending at least 5 hours a week doing so.
  • You are going to have to spend sometime engaging in promotion using social media.  Say you spend another hour doing this per week.
  • So, saying you do this 50 weeks a year, you are making a total of $365 dollars year by spending 350 hours of labor.  You will be making just slightly over a dollar an hour...
  • But remember this is pre-tax income.  So obviously you aren't going to live of $365 dollars a year, so you will have to work another job.  Both Google and Paypal report your earnings to the federal government, so they are going to take a bite out of that $365 bucks, depending on how much money you make at your other job.  Also Paypal (if you get pain by Google through them) are going to take a 3% cut (roughly) in transaction fees.  So you most likely will be netting under 300 dollars for 350 hours of labor.  NOT WORTH IT.

Additional Scenarios 

OK, let's say you invest instead of 7 hours a week, 49 hours a week in generating content.  That, using the current formula above, would generate you a little over $2500 bucks a year.  That, combined with government assistance or a third world life style in some of the lesser developed nations might be sustainable. But for most of you who might read this it absolutely isn't.  

Now let's say you get a better niche, where you actually make something along the lines of $5 per 1000 clicks.  Well that would help, you would only need about 34,000 hits a day to reach that 60,000 dollar net income mark.  With our 7 hours a week / 1000 hits a day scenario that would generate a little over $1800 bucks a year, that would increase your net pay to about $5.14 an hour before taxes.

So, for the vast majority of us it isn't even worth our time to embrace Google Adsense.  How could we still make this work?  What are we missing?

Changing the Equation

  • Some content has a long tail, and even after the content is published, it will continue to generate hits.  From my experience blogging anyway only a few articles will be long tail ones.  But if you can find a niche where the subject you write about is fairly static, you might be able to boost your weekly revenue with existing articles.
  • Things like posting quick links to other people's content, acting like a meta directory of info in some circumstances might boost the number of post that you get.
  • Some how getting people to write post for free, maybe because they have a passion for the subject, will create additional post.
  • Ways to automate detecting and posting links to other articles might help.
Let's say you do fairly well, and get 3000 hits a day at a 7 dollar per 1000 hits range. You would have to work part time at this, say 20 hours a week for 50 weeks or about 1000 hours of labor.  This would bring you about 7700 bucks of revenue.  Or would bring your pre-tax pay rate to about $7.7 an hour.  In most cities in America this is roughly about minimum wage.

Conclusion

Most of us are better off getting a part time job in the service sector than trying to use Google Adsense as a primary or even secondary revenue source.

Wednesday, November 13, 2013

Mobile

We all know mobile is the next big thing (has been for about 5 years and just getting bigger).  This slide deck lays it out nicely though if you still have doubts.  Social will be a big part of the mix.


Happy coding.

Friday, October 04, 2013

Tuesday, September 03, 2013

JavaScript Scope and IIFEs

I ran into an issue I've never run into before.  I have some JavaScript files included in most pages on a website. These files define objects and populate them with properties like user options, site root URLs, an ajax callback function, etc...  Well there were a few pages that end up being pop ups on modals, and in that case one of the JavaScript objects wasn't getting created, so I was getting undefined errors.

Initially I created an immediately invoked function on the offending pages that I would pass the object into to make sure it existed and if not populate it.  However you cannot pass a variable or object to an IIF if it isn't defined.  The solution to the problem was simple, but I'd never done this before.  In any function you have access to the window object, which is where all the globals are kept, so you can actually declare global variables in functions without having to declare them outside a function first like I had been doing for years.



 (function () {  
       if (typeof window.SomeObj == 'undefined') {  
        window["SomeObj"] = {};  
        window["SomeObj"].property1 = 'blah blah';  
        window["SomeObj"].property2 = 'some option';  
       }  
 })();  


While I will probably circle back at one point an fix the scripts so that this little hack will not be needed, I thought it was cool you could do this and it had never occurred to me to try it.  Probably not a best practice, and most likely JavaScript 101 to those who develop JavaScript aps, but to me it was new and interesting.  I hope this technique helps someone else as well.

Update

For nested objects, this code snip might be of value as well http://jsfiddle.net/EGZxJ/ which came from http://joonhachu.blogspot.com/ though I haven't tested this yet.

Wednesday, June 19, 2013

HTML 5 Game Tutorial

Here is a link to a great HTML 5 game creation tutorial.  Even if you are not a game creator there are still some Javascript object creating techniques that I think are worth looking at.

http://blog.sklambert.com/html5-canvas-game-html5-audio-and-finishing-touches/

The link is to the final tutorial in the five part series, but I would suggest starting from the first part and walking through the code through till the last part.

Wednesday, May 29, 2013

Mind Mapping Software Review

OK, I'm on a "Gotta get a side business going again.  I like to hash out ideas with mind mapping software.  I usually use FreeMind but I decided to take a look at what is out there. I was looking for something free or low cost that was still full featured.  For reference my main research sites where these-

Wikipedia List of concept- and mind-mapping software
Hive Five: Five Best Mind Mapping Applications
http://mindmappingsoftwareblog.com/

Well, the skinny of it is I'm keeping FreeMind but I might play with TheBrain.  Honorable mention is bubble.us for quick and simple mind maps.

  • It looks like for the open source world, the FreeMind file type has become a standard, with multiple mind mapping web and desktop applications exporting and importing the FreeMind file type.
As far as software-
  • Google now has entered the fray, with their not so advertised "Coggle" software.  I use a lot of Google products, so this looked interesting.  But after getting burned with Google's RSS reader going away I think I'll stay away from Google's fringe products for a bit.  Coggle is not as nearly as full featured as the alternative I will present here either.
  • Mindmeister looked promising.  It is web based and looks nice, both pluses, but it didn't seem to have a lot to it yet.
  • If you just need to do simple mind maps and would like to make them "in the cloud", the winner would be Bubbl.us hands down.  Very simple web interface and has all the basic stuff you need.  I might use it in a pinch.
  • TheBrain looks really cool.  It is a desktop app but there are versions of it for the big three OS's (Linux, Windows, Mac).  You can link any kind of files directly into your mind maps which I found interesting.  I held off because it is a download the pro version download and then after 30 days TheBrain downgrades itself to the free version.  I might test it out later but Idon't want to get sucked into buying stuff when I don't have to, as my budget for my business is very, ah, lean...
  • FreeMind reigns supreme right now still.  I don't like that it is a desktop application and I don't like that it has a Java dependency.  It doesn't look quiet as cool as say Mindmeiser or TheBrain.  But it works for my purposes for now I guess.  Maybe I'll revisit this in the future.
There are other tools out there, most of them cost $$$ or didn't look as promising as the above.  Disagree? Know a better tool?  If so let me know in the comments.

Monday, May 06, 2013

Webmatrix 3: Hold Off

I found a bug with Webmatrix 3 that may only happen to specific machine setups, which is this

http://stackoverflow.com/questions/16392844/webmatrix-3-sql-server-ce-4-busted


Not saying this will happen to you, I've read a bit and apparently most people claim everything is working great for them with Webmatrix 3.  But to be honest unless you are doing a lot with Azure or non razor development I would HOLD OFF installation of Webmatrix 3 just in case.

More info here http://forums.asp.net/t/1903867.aspx/1?WebMatrix+3+SQL+Server+CE+Database+Read+Only+ID+Column+Cannot+be+Modified


Monday, April 08, 2013

SQL Server Join Hints

Here is a link to a great article explaining SQL Server Join hints...the how, the when, and the why to use them.

http://www.mssqltips.com/sqlservertip/2917/sql-server-join-hints/

From the article-


"In summary, here's when to use the various types of join:

LOOP JOIN
Query has a small table on the left side of the join
One or both tables are indexed on the JOIN predicate

HASH JOIN
Tables are fairly evenly-sized or are large
Indexes practically irrelevant unless filtering on additional WHERE clauses, good for heaps
Arguably most versatile form of join

REMOTE JOIN
Same as hash join, but good where right side is geographically distant
Only suitable for INNER JOINs
Not suitable for local tables, will be ignored.

MERGE JOIN
Tables are fairly even in size
Works best when tables are well-indexed or pre-sorted
Uses very efficient sort algorithm for fast results
Unlike hash join, no memory reallocation, good for parallel execution

And if in doubt - let the optimizer decide!"

Wednesday, March 20, 2013

HTML 5 DataList Key Value Work Around

I like the new HTML 5 datalist element.  But most of the time when I deal with autocomplete drop down type stuff it is usually in key value pairs read from a database.  The datalist doesn't (too my knowledge) support this out of the box.  But you can add an attribute of say id to each option in your datalist, and then use a little jQuery to grab that id value for pushing back up to the server onsubmit.  Here is a basic example just to get you going.



 <!DOCTYPE html>  
 <html lang="en">  
   <head>  
     <meta charset="utf-8" />  
     <title></title>  
     <script src="http://code.jquery.com/jquery-latest.min.js"></script>  
   </head>  
   <body>  
     <form name="test" method="post" action="">  
     <input id="datalisttestinput" list="stuff" ></input>  
       <datalist id="stuff">  
         <option data-id="3" value="Collin" >  
         <option data-id="5" value="Carl">  
         <option data-id="1" value="Amy" >  
         <option data-id="2" value="Kristal">  
       </datalist>  
     <br /><br />  
       <a href="javascript:GetValue();">test</a>  
     </form>  
     <script>  
       function GetValue() {  
         var x = $('#datalisttestinput').val();  
         var z = $('#stuff');  
         var val = $(z).find('option[value="' + x + '"]');  
         var endval = val.attr('data-id');  
         alert(endval);  
       }  
     </script>  
   </body>  
 </html>  
Update: You can also do <option value="3">Collin</option> like you would expect on some browsers, hopefully all soon.

Friday, January 18, 2013

Sharepoint 2013

If you are an old SharePoint hack, the latest release of SharePoint 2013 might be exciting for you.  If you are coming into SharePoint as a complete noobie, I'd advise taking a pass. I've been fooling around with it for a few weeks off and on now, and so far I'm very under impressed.

I've run into all sorts of configuration issues that cause needed admin menu links (like to the design manager) to be missing or some features to not even work at all.  I'm having a hard time getting simple jQuery plugins to work even though 2013 SharePoint is advertised as being HTML 5 / Javascript friendly.  I'm sure I'm doing things wrong, but it shouldn't be as hard as it is.  Sometimes if things seem to have a steep learning curve to get hello world working I lose enthusiasm for them quickly.  Might be my bad I guess.  As I get older I just want things to work as advertised and not have to f**k with them to get basic functionality going.



Wednesday, January 02, 2013

Tired of Metro

I haven't tried this yet, but I'm not a big fan of the metro interface for desktops and servers.  This might help.

http://virtualizationreview.com/blogs/virtual-insider/2012/08/windows-2012-traditional.aspx



Wednesday, November 28, 2012

Digital Signature pfx Blues and Fix

Update:  This does the same thing w/o having to use a visual studio extension/plug in.  http://www.slickit.ca/2010/09/fix-cannot-import-following-key-file.html

------------------------

Yes, it was machine migration time again. So I downloaded all my projects from team foundation server and went to debug...and...blam. Mycompany.pfx throws build errors. Now I know the password for the digital signature file (which is what the pfx files are) but I don't remember how they were setup. You can right click and install them, but there is a bunch of options that I'm not sure which of is correct. So I google, and I find this nifty little VS2010 extension-

http://visualstudiogallery.msdn.microsoft.com/d491911d-97f3-4cf6-87b0-6a2882120acf?SRC=Featured

I closed Visual Studio, downloaded and installed the extension, then restarted visual studio and opened my project that was giving me the pfx error.

Hit debug, build failed, right clicked the error in the error list window, and now there is an option called "Apply Fix." Right clicked it, a command window opened up asking me what the pfx password was, which I supplied, and got a confirmation that the pfx certificate was now installed.  Started up the project in debug, and everything worked!

Note, this utility only works for Visual Studio 2010 Pro version or above. There might be a 2008 version, and the 2010 version might work with Visual Studio 2012, but I haven't tried it yet.

More info on pfx issues here-

http://stackoverflow.com/questions/2815366/cannot-import-the-following-keyfile-blah-pfx-the-keyfile-may-be-password-prote

Note, it turns out this plugin isn't free.


Pro Application Lifecycle Management With Visual Studio By Rossberg, Joachim/ Olausson, Mathias (Google Affiliate Ad)

Tuesday, October 30, 2012

Localized Month From an Int (1-12)

Demo of getting localized month string from a number (note I'm passing the number in as a string and then TryParsing it this case (modify to suit).



Essential C# 4.0 By Michaelis, Mark (Google Affiliate Ad)

Monday, October 29, 2012

Tuesday, October 23, 2012

Using Bit Flags in SQL

Using bit flags is a great way to store a lot of information in a single place that can be used in a variety of ways, of which the most common I've seen is to use big flagging for permission checks. I could write the following post myself, but I don't think I could add much to the following excellently done reply to a question on StackOverflow about using bit flags in SQL, so here you go-

[Link]

Also if you are a little rusty on using bit flags in .Net, here is a refresher article link-

[Link]

Tuesday, July 10, 2012

Cross posted at http://steamunderground.blogspot.com/

At the core of any game application is going to be a random number generator.  I found out that using .Net's base random class is fine for a one off or limited set of random numbers needing to generated, but once you start beating on the .Net random class you start seeing some funky results.  So for a little game demo I'm working on I put together a static class that generates random numbers based on the System.Security.Cryptography.RNGCryptoServiceProvider which seems work well even if it is a tad slow.

Here is the class.  Note the static method GetD6Successes.  This is meant to mimic the "exploding" D6 die pool mechanic used in some table top RPG's.  I like the concept as in theory a lone peasant has a chance, though a very very very small chance, of slaying a dragon with this mechanic.  Let me know what you think.


Friday, May 18, 2012

Quick Trick, Splitting on Multiple Characters

This is more of a Junior Varsity post, as I'm sure the .Net gods have figured this technique out a long time ago.  But for the rest of us, if you ever wanted to split a string on more than one character, this is how it is done in .Net, or at least one of possibly many ways it can be done. In this example I want to split on new line breaks and space characters.


string mybiglongstringwithlotsofnewlines = "a whole bunch of characters";
List < char > lst = Environment.NewLine.ToList < char > ;
lst.Add(' ');
string[] myarray = mybiglongstringwithlotsofnewlines.Split(lst.ToArray());


Happy coding!

Tuesday, April 10, 2012

Following Facebook Pages Through RSS

 
I love RSS, but it isn't really catching on like I thought it would. But most web applications, including Facebook, have ways of getting at content updates through RSS, you just have to hunt a little bit harder since RSS seems to not be hitting the mainstream.  Here is a helpful link on how to follow Facebook updates (pages and users) via RSS, and without even logging into Facebook (which should give you a little pause actually).

http://sem-group.net/


Sunday, January 29, 2012

Fix for Chrome Crashing with Youtube on Closing

Here is a temp fix for the issue when you are watching a youtube video in Chrome and then you try to fix it, Chrome crashes. Unfortunately the fix is to disable the two Flash dll's.  Chrome is working on a fix.  These two dll's can easily be re-enabled as needed.

* In the chrome URL window type about:plugins
* Click show details
* do a find on gcswf32.dll and NPSWF32.dll, disable them both.


For reference-
http://www.google.com/support/forum/p/Chrome/thread?hl=en&tid=1fe8d66c8677d694



Thursday, October 27, 2011

Big Bad Malware: One Helpful program.

I know several people now (including my wife) that have had their machines get infected with malware that is very hard to remove.  Microsoft recently released a tool that might be helpful.

http://connect.microsoft.com/systemsweeper


Good luck!

Thursday, October 13, 2011

Free Windows Virtual Desktop Manager

I've been using an ancient virtual desktop manager called Yodem3D.  It works OK, but it is beginning to show its age lately.

So the 4SysOps blog had an article on a few to try (see comments too)-

[Link]

I tried Windows Pager http://sourceforge.net/projects/windowspager/ and it works OK.  Another mentioned is http://virtuawin.sourceforge.net/ that looks like it might be better.  I'll give that one a shot later. If you know of any better ones please let me know in the comments! Thanks.

Tuesday, August 30, 2011

Regions in Visual Studio for Javascript

I can't believe I didn't find this earlier. Collapsible regions for Javascript in Visual Studio 2010-

[LINK]

Friday, August 19, 2011

.Net Generate QR Codes on the Fly

Pretty cool instructable tidbit on how to generate QR codes with .Net through an open source library.

http://www.jphellemons.nl/post/Generate-QR-Codes-with-AspNet-C.aspx

For one off's there are a few sites where you can generate QR's. Here is a link to one-

http://qrcode.kaywa.com/

And a way to decode QR codes online (if you don't have a smart phone app handy) -

http://zxing.org/w/decode.jspx

Some Useful Bookmarklets

Here is a bookmarklet that allows you to check out what font's are used on a website-

http://fount.artequalswork.com/

Here is another that allows you to add live notes to a web page-

http://markup.io/

I use the Share on Twitter bookmarklet all the time-

https://dev.twitter.com/docs/share-bookmarklet

Want to encrypt a message on Facebook or Twitter? Try this (Bookmarklet to the left of the page)

https://encipher.it/email-encryption

Thursday, August 18, 2011

HTML 5 Web Application Demo Worth Looking At

Dan Wahlin and a host of other .Net all stars created a demo HTML 5 web application that I suggest web developers look at (regardless of what server code you use on the back end, lots to be gleaned here). Here is a screen shot linked directly from Wahlin's blog-


Here is a list of the technologies used. There should be something to glean for everyone-

You can read about the application architecture and download it here-

Monday, August 01, 2011

Blizzard Goes User Based Micro Transactions

Very interesting...I like this model.  Diablo III will build it's revenue stream by taking a cut of micro transactions between players. The future is coming.

http://tobolds.blogspot.com/2011/08/blizzard-invents-new-business-model.html

Thursday, July 21, 2011

The Canvas Tag

I'm taking my much belated first stabs at using the HTML 5 canvas tag from scratch, and I found a great site I thought I would share to get you going on the basics.

http://www.html5canvastutorials.com/

The basic elements of Canvas seem easy enough, putting it all together to make something unique and useful might be a different story.


And there are lots of great Canvas libraries out there, but I figured I'd start low level and work my way upward.

Wednesday, July 13, 2011

Remembering the COMBGuids

The new SQL Server 2005+ NewSequentialID() function is great because you can use GUIDs for primary key's without suffering the the query performance hit normally associated with using random values for primary keys due to ordering in tables. But...you have to create these NewSequentialID's on the SQL side of things, which means that you have to pass them back to your web application, and sometimes that is problematic. It is much easier to create a GUID on the Web side of things before doing the insert, so that you have the key on the web side to access the just inserted data without having to have that key generated and then passed back to you.

For some of you what I'm saying will make absolutely no sense. For others, you see where I'm going. But with a technique known as COMBGuids, you can create sequential GUIDs for IDs on the web side and then pass them into your database.

Here is an implementation of COMBGuids that I've used in the past.

Tuesday, July 05, 2011

Using A ValidationSummary Control's ShowMessageBox (kinda) with Telerik Controls in Medium Trust

 I guess there is an issue with Validation Summaries and Telerik Controls.  If your site is running under Medium trust, you can't use the ShowMessageBox and instead you have to use the ShowSummary method.  I noticed this through off the styling of some of my controls once the error summary was rendered so I came up with a work around. Note be careful where you call this code else you will get an error, this worked for me using the FormView_ItemCommand.


ValidationSummary vs =
(ValidationSummary)MyFormView.Row.FindControl ( "myvalidationsummaryname" );
if ( vs != null )
{
  string sErr = vs.HeaderText  + "\\n";
  for ( int i = 0 ; i < this.Validators.Count ; i++ )
  {
    if ( !this.Validators[ i ].IsValid )
      sErr += "* " + this.Validators[ i ].ErrorMessage + "\\n";
  }
  myRadAjaxManager.ResponseScripts.Add ("alert('" + sErr + "');" );
}

That should get you going.

Tuesday, June 28, 2011

Populating a Telerik RadListBox with JSON on the Client Side

Ok, this is the poor man's way to do this. I'm actually not calling a web service to pull my jSON string back from the server, but rather a RadScriptManager, but this will get you going.

My approach. Note it assumed that you have a Telerik RadAjaxScriptManager on your page (or master page that you will need to access).

Step 1 Include the Following Namespace in Page Code Behind Class

using System.Web.Script.Serialization;

Step 2 Create a Class Object to be Serialized in the Page Code Behind Class

[Serializable]
public class itm
{
   public string val { get; set; }
   public string txt { get; set; }
}

Step 3 Create a Serialization Method in the Page Code Behind Class

public string ToJSON ( object obj )
{
  JavaScriptSerializer serializer = new JavaScriptSerializer ();
  return serializer.Serialize ( obj );
}

Step 4 Create a Method in the Page Code Behind Class That Will Take Data, Populate a list of itms,Serialize that list into a jSON string, then call the RadAjaxManager's ResponseScripts.Add method to pass the jSON string to the client side.

A few notes here. One you could use AJAX to make a call to a web service to accomplish the same thing, for my example was just doing a basic test so I didn't bother. Also note that you will need to call this method somewhere (on a databind of a form view, Page_Load, whatever, inorder for the method to do anything). Note I'm doing a very lazy and inefficient way to get my data out of the database, I actually defined a sql datasource on my aspx page, and then reference it in the code behind. You probably will want to get your data another way...

void JSONListBoxItems ( hsRadListBox lst, SqlDataSource ds, string txt, string val )
  {
  lst.Items.Clear ();
  List<itm> itms = new List<itm> ();
  if ( lst == null || ds == null || string.IsNullOrEmpty ( txt ) || string.IsNullOrEmpty ( val ) )
  {
   ;
  }
  else
  {
    DataView view = (DataView)ds.Select ( DataSourceSelectArguments.Empty );
    if ( view != null && view.ToTable () != null )
    {
      DataTable table = view.ToTable ();
      for ( int i = 0 ; i< table.Rows.Count ; i++ )
      {
       itm t = new itm ();
       t.txt = table.Rows[ i ][ txt ].ToString ();
       t.val = table.Rows[ i ][ val ].ToString ();
       itms.Add ( t );
      }
    }
   }
   myRadAjaxManager.ResponseScripts.Add ("POPRadListBX('" + lst.ClientID.ToString () + "'," + ToJSON ( itms ) + ");" );
 }

Step 5, Add the Following Javascript on the ASPX page.

function POPRadListBX(tid, js) {
        var lst = $find(tid);
        if (lst != null) {
          var zzz = lst.get_items();
          lst.trackChanges();
          for (var i = 0; i < js.length; i++) {
            var item = new Telerik.Web.UI.RadListBoxItem();
            item.set_text(js[i].txt);
            item.set_value(js[i].val);
            zzz.add(item);
          }
          lst.commitChanges();
        }
      }


Done. If I have time I'll circle back and make a downloadable example.

Monday, May 23, 2011

Test Data

I found a test data generator site that was useful. Here is the link.

http://www.generatedata.com/

Friday, May 20, 2011

Web Forms Bloat

When .Net web forms first came out I hated them. Then I got used to them. Now MVC is out, and if I would have skipped web forms I would have loved MVC I think, but because there are some great web form tools out there I find looking to doing something similar in MVC to be not worth it, at least at this point for me. But, web forms do have their draw backs. Look at the line number of this error...


Now I'm hoping this is a faulty line number, but unfortunately I don't think it is. MS Ajax -> Telerik generated Javascript handlers -> 200 lines of Javascript on a page with 5 web grids = a bazillion lines of code I guess.

I bet with MVC this would be about 1/20th of the line number...interesting.

By the way, here is how to do a global Javascript catch if debugging tools aren't working for you-

 window.onerror=function(m, u, ln){
       alert('Error: '+m+'\nURL: '+u+'\nLine: '+ln)
       return true
      }


More info here http://www.javascriptkit.com/

Wednesday, May 11, 2011

Passing Client Side Dates to Server Side Vars With Telerik Rad Controls

Ok, sometimes you need to pass a client side datetime value from a Raddatetimepicker up to the server side for use. Sometimes with localization this can get kind of tricky, but Telerik introduced a new method to make this somewhat less painless.

in javascript
var dt = $telerik.findDatePicker("controlID", null);
  var dtValue = dt.get_selectedDate().format("yyyy/MM/dd");


This method will put your datetime value in a format that is SQL server friendly. Happy coding.

Sunday, February 20, 2011

Remembering Page Methods

Ok, I know ASP.Net web forms are all out of style now, even though if you are in a heavily data centric environment (one where you have grids upon grids upon grids) web forms still make the most sense in a lot of scenarios. So a lot of us are stuck with web forms and will be for as long as they are supported.

Anyway, one of the must under utilized capabilities in web form .Net apps are page methods. I sometimes forget the even exist in our jQuery / Ajax centered world. The preferred "best practice" method I'm sure would be to build a web service in WCF that you connect to through jQuery to do an Ajax call without a post back, but sometimes the quick and dirty approach that page methods offer is still useful.

So Zeeshan Umar has a good blog post about good old Page Methods here that the following code snip is based on.

http://zeeshanumardotnet.blogspot.com/2010/11/pagemethod-easier-and-faster-approach.html

I didn't add much to his example, so feel free to go right to his, but here is my own quick demo that I worked through just to remind myself that page methods still exists and how to use them based on Zeeshan's post.


The sample is just one aspx page with its code behind. This example demos submitting a registration form similar to what Zeeshan did-

The PageMethodsTest.aspx page (scroll bar at bottom, highlight all to copy/paste)



The PageMethodsTest.aspx.cs code behind.



Simple! Thanks for the reminder and quick code demo Zeeshan.

Bonus! Of course you can do all this with jQuery. One bonus using jQuery instead of Microsoft's ASP.Net AJAX is that you can leave the script manager off of your page. You can also easily call page methods ON OTHER PAGES (within the same project anyway), so then page methods really do become a poor man's quick and dirty alternative to WCF and ASMX for small task.

Here is an example HTML page that calls the above PageMethodTest.aspx RegUser method-

CallPageMethodsOnPageWJQuery.htm


Here is a useful blog post from Encosia for more info on jQuery / page method calls-

http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/


Thursday, February 17, 2011

JavaScript: Available Window Height and Width

Ok, here is another junior varsity tip for using Javascript to get the true available window height and width. Note I stole this code from somewhere (though I tweaked it). I'd give credit if I remembered where I got it from, I don't.

function HSAvailWidth() {
  if (typeof window.innerWidth != 'undefined')
    return window.innerWidth;
  if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth !== 0)
    return document.documentElement.clientWidth;
  return document.getElementsByTagName('body')[0].clientWidth;
}
function HSAvailHeight() {
  if (typeof window.innerHeight != 'undefined')
    return window.innerHeight;
  if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientHeight != 'undefined' && document.documentElement.clientHeight !== 0)
    return document.documentElement.clientHeight;
  return document.getElementsByTagName('body')[0].clientHeight;
}



Or with jQuery...

$(window).height(); $(window).width();

Note: different browsers will have different available viewport height/widths because the browser tool bars very is size.


More here...

http://api.jquery.com/height/

Tuesday, February 15, 2011

Very Cool jQuery Sorting/Suffling Plugin called Isotope

Check this jQuery plugin called Isotope out.

http://isotope.metafizzy.co/

It has some pretty cool animation features, worth a look.

This Looks Interesting

A new Javascript/jQuery framework called the iX Framework looks pretty cool. It looks like it can do a lot (but not all) of what Telerik controls can do (though without the back end .Net integration). Might be work a look. $99 bucks for now.

http://www.intelligentexpert.net/


Friday, February 04, 2011

Quick Tip: Generate Unique ID's in Javascript

Here is a little code snippet I use to create unique id's in Javascript when I'm dynamically adding dom elements.

function HSCreateID(apd) {
  return apd + '' + new Date().getTime();
}

More on the Date().getTime() function in Javascript-

http://www.w3schools.com/jsref/jsref_getTime.asp


Tuesday, January 25, 2011

Basic Polling Web jQuery Chat Example Using WebMatrix

*** Update: I had a bunch of junk comments left over from testing in the sdf database, some were kind of crude. I removed them from the source. Numbers 32:23 in action :) ***

Ok, here is a VERY rudimentary example to help you get web chat functionality going in a webmatrix site. I'm not getting fancy at all here, just three pages and a SQL CE database -> Chatpage.cshtml, pull.cshtml, push.cshtml. Essentially I've got my chat page that uses jQuery to poll a "pull" page every 1.5 seconds. I keep track of what data to return by using session time variables. And there is a simple jQuery post method to post new chat messages.

Note! This is just meant to help get you going, not meant to be production code (no SQL injection defense, might need to watch out for Chars in Javascript that might throw things off, not styled at all, yadda yadda yadda). But there is enough here to get you going. Also be warned that you need to test this with two different types of browsers if you are testing the code on your local machine (else a same browser just different windows will share the same session and messages will start disappearing).

Here is the [Source Code]. Or you can look at each page's source individually (scroll bars at the bottom of the code if it over flows).

Here is the ChatPage.cshtml


Here is the Push.cshtml page source


Here is the Pull.cshtml page source

Here is a picture of the database schema

Tuesday, December 07, 2010

Using SQL Server Dates Without Time

I often find myself in a scenario where I want customers to be able to select dates, delete items by setting an inactive date to today rather than actually removing something from a database, etc...

Sometimes it helps to only deal in dates, rather than in date/time. Using the GetDate() function in SQL brings back a full date with the time string, but here is a great method to fix that.

declare @somedate = cast(floor(cast(GetDate() as float)) as DateTime)

There are a few other ways to do this, but this one seems to perform the best. Tested with SQL 2008 and works great.

Hat tip too Ben Nadal's blog, more info here-

http://www.bennadel.com/blog/122-Getting-Only-the-Date-Part-of-a-Date-Time-Stamp-in-SQL-Server.htm

Sunday, November 28, 2010

Google Ads


For the very few of you that straggle across this blog every now and then you might notice that I succumbed and put up some Google ads. I resisted for awhile, but I'm poor, so I figured what the heck. Hey, I made a whopping 20 cents my first week!

But 20 cents is 20 cents. I figure a little sugar will invigorate me to write and post articles that have relevance to folks with code and links that line programmers will find of value. Maybe I can boost that 20 cents to a dollar a week. Multiply that by x number of other blogs and web sites that I have just dying on the vine that I might start working on, and I might make 50 bucks or so. That pays for a few domain names, maybe a book or PDF here or there, and some low end 3D software now and again. I will write/code/post for about six months and see what I can get going.

If ads piss you off I'm with you, they piss me off too. But when in Rome...oh well.

Happy Thanksgiving every one. I had a great one, hope you did too.

Monday, November 01, 2010

AWS Free Usage Tier

The cloud battle heats up! Who benefits? Us! AWS Free Usage Tier

Microsoft HTML5 Tooling...Meet Glimmer

Just found this, haven't played with it, but it is a start of Microsoft's efforts to provide tooling for HTML 5.

Meet Glimmer


Sunday, October 24, 2010

Web Developers / Designers: Who Are we?

I'm not sure how this data was gathered, and I don't vouch for it's accuracy, but I bet it is somewhat ballpark. Take a peak at this web infographic to figure out who all us web designers/developers are

Tuesday, October 19, 2010

Very Cool Web Annotator

I like this. Drag a bookmark to your bookmark bar, and then when you are over any given website, click the link, and start annotating the site.

http://markup.io/

Cool.

Sunday, October 17, 2010

Decent Rundown of YouTube Software

Wanting to do a little video online are you? Check out Web distortion 's list of useful video software.

Friday, October 15, 2010

Basic Silverlight/.Net Twitter Jason Example

OK, some I'm back into Silverlight again. It actually isn't as bad as I thought, and I'm starting to get jazzed about working with it again. To get my feet wet I found a really basic example of adding some twitter search items to a Silverlight Listbox. After looking at it, ugly XML stared at me defiantly. I like XML for some things, like bloating my code a lot.

I know Twitter can return data in JSON, so I I hacked out the following example of consuming a Twitter search JSON result.

Note you need to add a few namespaces, System.Collections.ObjectModel and the new System.Json namespace.

Here is the meat of a click button even that consumes the Json





You can download the base Silverlight 4 project here-


Download project on 4shared.com


Thursday, October 14, 2010

My Comments on Silverlight

I was originally going to post this on some blog, but I decided not to for now. So I'll post it here.

First, I'm not a great developer. I'm not a bad developer, I'm a middle of the pack dude. I do some fancy stuff sometimes, actually innovate occasionally, but most often I'm stuck in the day to day duldrums of retrieving data and displaying it in some meaningful way on a screen, and taking a user response and saving it to a data store. A little bling is always good, but often I can only provide two of three things (functionality, quick delivery, and "bling"). Usually the bling suffers under the two of three constraints that I often find myself in. Silverlight and Flash, as far as my world generally goes, are bling.

I love what people do with Flash, but we are Microsoft shop so for RIA we play in the Silverlight world. I built a demo project in Silverlight three, even throwing in some Telerik Silverlight controls for EXTRA bling, and it didn't thrill me. I'm facing doing some serious Silverlight 4 development and now and although I will put my head down, crank the music, and code conquer it, it doesn't thrill me. What does thrill me is compiled Javascript, hardware acceleration for HTML 5, web sockets, etc... I don't really know why that thrills me more. It shouldn't, but it does. I think I for better or for worse represent your average high end Mort low end Elvis developer that Silverlight has to thrill if it is going to survive. It just isn't there yet, maybe version 5 will do it. All I know is that after hacking away in version 3 and walking away from it for a bit, I'm finding myself feet dragging a bit in starting a new project in Silverlight 4. Yesterday in my down time I wrote a little adventure game using javascript, crappy animated gif's, and some CSS in a few hours. I just can't wait to get some more spare time to add sockets and make it multiplayer, add ai/pathing, dialogs, etc... That thrilled the heck out of me. Heck I might even use Silverlight as a bridge for the sockets, I wouldn't mind doing that. But if I tried to do the same thing with Silverlight, I would spend hours and hours in Silverlight 4 and it will not thrill me because I would be less productive and constantly running into issues. I guess it is just me.

Maybe in a few days hacking stuff out I will be in love with Silverlight, but for some reason I have my doubts. Don't get me wrong either. I love Microsoft products. Wouldn't want to be coding in anything else but Visual Studio 2010. Love the new Razor syntax. Everyone hates web forms including myself but I've done some cool stuff with them. But for whatever reason, Silverlight to me (currently) was/is a drag.

I'm really looking forward to see what IE 9 / Google 6 / Firefox 4 come up with.