Tuesday, August 12, 2008

You can do that in Javascript?

So found out yesterday that anonymous methods exist in javascript. Who knew?
 divToAdd.onmouseover = function() { picker.changeStyles(divToAdd, true); };
Where picker.changeStyles is a method on a class. Javascript is starting to grow on me.

Thursday, July 24, 2008

Yeah SessionTryParse

So I got tired of seeing If Session["SomeKey"] != null... blah blah blah and thought it would be a semi worthwhile task to create a TryParse method because I'm bad like that. Not a Bad Enough Dude to Save the President, but bad.
 public static Boolean SessionTryParse<K&gt;(HttpSessionState session, String key, out K itemToSet) where K : class
 {
     itemToSet = null;

     if (session[key] != null)
     {
        itemToSet = session[key] as K;
     }

     return itemToSet != null;
 }
And for structures... which I have to cheat and only allow them to be nullable.
public static Boolean SessionTryParse<K>(HttpSessionState session, String key, out K? itemToSet) where K : struct
{
     itemToSet = null;

     if (session[key] != null && session[key] is K)
     {
        itemToSet = (K)session[key];
     }

     return itemToSet != null;
}
The idea is simple, pull in the Session, the needed Session key, and something to throw the value in. After that, just check to see if the Session + Key is null and if Session + Key is the same type of said something. That's how it's done Detroit greater metropolitan area style... punk. USE THIS:
   using System;
   using System.Web.SessionState;

Tuesday, July 22, 2008

Like versus Contains

So have to figure this one out. Say you have:
private static Expression<Func<User, Boolean>> WhereLikeFirstNameLastNameUserName(String name)
{
  return currentUser => SqlMethods.Like(currentUser.UserName, "%" + name + "%")
  || SqlMethods.Like(currentUser.FirstName, "%" + name + "%")
  || SqlMethods.Like(currentUser.LastName, "%" + name + "%");
}
And
private static Expression <Func<User, Boolean>> WhereLikeFirstNameLastNameUserNameWithoutLike(String name)
{
  return currentUser => currentUser.UserName.Contains(name)
  || currentUser.FirstName.Contains(name)
  || currentUser.LastName.Contains(name);
}
The first one should look familiar, its part of the "dynamic" linq stuff I've been posting. Now guess which one gives me this SQL when profiled:
exec sp_executesql N
'SELECT
 [t0].[UserID],
 [t0].[FirstName],
 [t0].[LastName],
 [t0].[Password],
 [t0].[UserName],
 [t0].[UserTypeID]
FROM
 [dbo].[User] AS [t0]
WHERE
 ([t0].[UserName] LIKE @p0)
OR
 ([t0].[FirstName] LIKE @p1)
OR
 ([t0].[LastName] LIKE @p2)
ORDER BY
 [t0].[UserName]',

N'@p0 varchar(3),
 @p1 nvarchar(3),
 @p2 nvarchar(3)',
 @p0='%s%',
 @p1=N'%s%',
 @p2=N'%s%'
If you answered both, you are correct or you looked ahead for the answer and therefore are a tool. Now which do you think that...
query.ToList()
Produces the correct list? If you answered Contains, then you are correct again. If you are a tool, you probably looked ahead again... Why is this? I HAVE NO IDEA... Something I have to look into for sure.

Friday, July 18, 2008

Backtrack

Couple posts ago I said "It took me a minute to figure out how this works. I thought it was somehow in need of the property name to order by, but in reality it is looking for a list of strings to order by." when I was talking about how to create an order by expression. I thought about it more, and that doesn't make sense as far as the sql goes. What I was saying would mean it would get the list of strings and sort based on them. What I think actually happens is it takes the Expression (Hense the name) and derives the order by from the epression. Say I want tell the thing I will want to sort by user.UserName, it will take that expression and translate it into ORDER BY someAlias.UserName. Magic. I would like to know how it does this. Reflection and a ton of it I would assume.

I'm starting to worry about myself

So the "dynamic" linq query so far isn't just enough to stop. Oh no, now that I can have methods pass back expressions, what about a dictionary of order by expressions to allow an even more dynamic feel? Huh? How's about that kids? I hate myself too.
//Enum created for the dictionary key
public enum OrderByChoice
{
  FirstName,
  LastName,
  UserName
}

//dictionary of expressions
private static Dictionary<OrderByChoice, Expression<Func<User, String>>>  GetOrderByList()
{
  if(orderByList == null)
  {
    orderByList = new Dictionary<OrderByChoice,Expression<Func<User, String>>>();

    orderByList.Add(OrderByChoice.FirstName, currentUser => currentUser.FirstName);
    orderByList.Add(OrderByChoice.LastName, currentUser => currentUser.LastName);
    orderByList.Add(OrderByChoice.UserName, currentUser => currentUser.UserName);
  }
         
  return orderByList;
}   
That's right, I know. Silly, but I think it's cool. Now mind you, I could have methods that return expressions instead of the expressions themselves, but I wanted to show the expressions. And for the method call:
public static IList<User> GetUserList(OrderByChoice orderBy)
{
  return GetUserList(currentUser => true, GetOrderByList()[orderBy]).ToList();
}
And now you have an even more dynamicish call. I FORGOT THE USINGS!!!!
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq.Expressions;

Thursday, July 17, 2008

And some days I love programming

This is the newest edition of Linq madness. So I added an OrderBy to my lame dynamic query thing.
private static IQueryable<User> GetUserList(Expression<Func<User, Boolean>> whereClause, Expression<Func<User, String>> orderBy)
{
    var query = (from user in GetDataContext().Users
             select user).Where(whereClause).OrderBy(orderBy);

    return query;
}
Now you will notice there is a new Expression in town and it's name isn't Reggie Hammond. It is my order by Expression which uses a Func<User, String>. It took me a minute to figure out how this works. I thought it was somehow in need of the property name to order by, but in reality it is looking for a list of strings to order by. Simple. I could do something like: (Ignore the WhereLikeFirstNameLastNameUserName for now)
    return GetUserList
           (
            WhereLikeFirstNameLastNameUserName(name),
            currentUser => currentUser.UserName
           ).ToList();
But that's boring. I want to be able to pass a method that would give the correct string to orderby somewhat cleaner. In comes a method that returns an Expression. OooOoOOo.
private static Expression<Func<User, String>> SortOnUserName()
{
    return currentUser => currentUser.UserName;
}
So now it looks like:
public static IList<User> GetUserListByLikeName(String name)
{
   return GetUserList
          (
           WhereLikeFirstNameLastNameUserName(name),
           SortOnUserName()
          ).ToList();
}
Cleaner... Now what is WhereLikeFirstNameLastNameUserName? Simple, that is my where Expression just being returned in this method:
private static Expression<Func<User, Boolean>> WhereLikeFirstNameLastNameUserName(String name)
{
   return currentUser => SqlMethods.Like(currentUser.UserName, "%" + name + "%")
   || SqlMethods.Like(currentUser.FirstName, "%" + name + "%")
   || SqlMethods.Like(currentUser.LastName, "%" + name + "%");
}
By the way, SqlMethods.Like is just a built in method used only with Linq to Sql. Probably shouldn't have used it in this example but oh well. Live with it. OH NO NOT THE USINGS!!
using System;
using System.Collections.Generic;
using System.Data.Linq.SqlClient;
using System.Linq;
using System.Linq.Expressions;

Quick Linq thing... String to Number String

Really stupid little thing I came up with today... but I wanted to use Linq to strip any non number from a string and return the string with only numbers. I told you this was a stupid little thing.
public static String CreateNumberOnlyString(String textToCheck)
{
  String returnText;
               
  var queryForIntegers = from currentChar in textToCheck
                         where Char.IsNumber(currentChar)
                         select currentChar;
               
  returnText = new String(queryForIntegers.ToArray());
               
  return returnText;
}