SimplyExpress New Mini Parser

Recently, I've been feeling like my C# skills have been slipping. So, I decided to implement a very "computer science-y" library. It's very simple and I've been trying to implement it for about 2 years now. Now has just been the only time where I could think straight and figure it out it seems like.

But, basically it's probably pretty close to being an operator-precedence parser. My reason for making it is that I have some beginning source code to a scripting engine lying around, but I never could get expression parsing such as x=5+10 implemented in a clean way.

Well, now I have it implemented. What it does is takes a stream of tokens. These tokens have either operations or values tied to them. SimplyExpress will tie all of these into a tree. And then, using given operator precedence and associativity values, it will reduce the tree 1 operation at a time. The tree is reduced by condensing a value(s) and an operation into just one value.

I wouldn't consider it advanced, but it does the hard part of parsing into a tree and then reducing that tree into a series of instructions with appropriate values. I'm also sure it's not too fast. I see some obvious ways to optimize it, but I just wanted a programming exercise :)

Anyway, this will probably part of another project I build, so I won't bother putting it into SVN. Here is a pastebin of the BSD licensed code though: http://pastebin.com/bu1QPcYK

Posted: 6/14/2012 1:35:48 AM

SQL Server User Store for FSCAuth

Well, I finally got around to writing a UserStore utilizing SQL Server. I did it without an ORM.. which is annoying at best, but regardless, I'd say it gets the job done and is sorta easy to extend for your own UserData class. SQL doesn't play well with inheritance though. It's quite difficult to write an easy to extend data class without using an ORM

Anyway, here is the code:

namespace Earlz.FSCAuth.Extensions
{
    public class SqlServerUserStore : IUserStore
    {
        private static SqlServerUserStore instance;
        private SqlServerUserStore() {}

        public static SqlServerUserStore Instance
        {
          get 
          {
             if (instance == null)
             {
                instance = new SqlServerUserStore();
             }
             return instance;
          }
        }
        /// <summary>
        /// Will get a user by username or email address
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        virtual public UserData GetUserByName(string name)
        {
            using (var con=GetConnection())
            {
                con.Open();
                var cmd = new SqlCommand();
                cmd.CommandText="select * from users left join Groups on"+
                    " groups.UserID=users.ID where username=@name or "+
                    " emailaddress=@name";
                cmd.Connection = con;
                cmd.Parameters.Add(new SqlParameter("@name", name));
                return ReaderToUserData(cmd.ExecuteReader());
            }
        }

        virtual public bool UpdateUserByID(UserData user)
        {
            var old = GetUserByName(user.Username);
            if (old == null)
            {
                return false;
            }
            using (var con = GetConnection())
            {
                con.Open();
                var cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandText="";
                if (old.Groups.TrueForAll(x => user.Groups.Contains(x)))
                {
                    //update groups as well.
                    //we're just going to do it messy and drop all groups
                    //and add them back in.
                    cmd.CommandText = "delete from groups where userid=@userid;";
                    foreach (var g in user.Groups)
                    {
                        cmd.CommandText += "insert into groups (name,userid)"+
                        " values('" + g.Replace("'", "''") + "',@userid);";
                    }
                }
                cmd.CommandText += "update users set emailaddress=@email, username=@username,"+
                " salt=@salt, passwordhash=@password ";
                cmd.CommandText += "where id=@userid;";
                cmd.Parameters.Add(new SqlParameter("@userid", user.UniqueID));
                cmd.Parameters.Add(new SqlParameter("@email",user.EmailAddress ?? ""));
                cmd.Parameters.Add(new SqlParameter("@username",user.Username));
                cmd.Parameters.Add(new SqlParameter("@salt",user.Salt));
                cmd.Parameters.Add(new SqlParameter("@password",user.PasswordHash));
                if (cmd.ExecuteNonQuery() > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

        }

        virtual public bool AddUser(UserData user)
        {
            using(var con=GetConnection())
            {
                con.Open();
                var cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandText = "declare @userid as integer;";
                cmd.CommandText += "insert into users (username,emailaddress,passwordhash,salt)"+
                " values (@username,@email,@password,@salt);";
                cmd.CommandText += "set @userid=scope_identity();";
                foreach (var g in user.Groups)
                {
                    cmd.CommandText += "insert into groups (name,userid) values "+
                    "('" + g.Replace("'", "''") + "',@userid);";
                }
                cmd.CommandText += "select @userid;";
                cmd.Parameters.Add(new SqlParameter("@email",user.EmailAddress ?? ""));
                cmd.Parameters.Add(new SqlParameter("@username",user.Username));
                cmd.Parameters.Add(new SqlParameter("@salt",user.Salt ?? ""));
                cmd.Parameters.Add(new SqlParameter("@password", user.PasswordHash ?? ""));
                try
                {
                    user.UniqueID = ((int)cmd.ExecuteScalar()).ToString();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

        virtual public bool DeleteUserByID(UserData user)
        {
            using (var con = GetConnection())
            {
                con.Open();
                var cmd = new SqlCommand();
                cmd.CommandText = "delete from groups where userid=@userid; delete from users where id=@userid";
                cmd.Connection = con;
                cmd.Parameters.Add(new SqlParameter("@userid", int.Parse(user.UniqueID)));
                if (cmd.ExecuteNonQuery() > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        virtual protected UserData ReaderToUserData(IDataReader rdr)
        {
            if (!rdr.Read())
            {
                return null;
            }
            var u = new UserData();
            u.EmailAddress = rdr["EmailAddress"] as string;
            u.PasswordHash = rdr["PasswordHash"] as string;
            u.Salt = rdr["Salt"] as string;
            u.UniqueID = ((int)rdr[0]).ToString(); //user.id
            u.Username = rdr["Username"] as string;
            u.Groups=new List<string>();
            if (rdr["Name"] != null && !(rdr["Name"] is DBNull))
            {
                u.Groups.Add(rdr["Name"] as string);
                while(rdr.Read()){
                    u.Groups.Add(rdr["Name"] as string);
                }
            }
            rdr.Close();
            return u;

        }
        protected virtual SqlConnection GetConnection()
        {
            string s=ConfigurationManager.ConnectionStrings["fscauth"].ConnectionString;
            var con = new SqlConnection(s);
            return con;
        }
    }
}

Also, BSD licensed again:

Copyright (c) 2011 Jordan "Earlz/hckr83" Earls http://lastyearswishes.com All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Posted: 6/12/2011 9:57:37 PM