Category Archives: Language References

ASP .NET Code Contracts Examples

//contract.requires
public void Withdraw(Account account, decimal amount)
{
	Contract.Requires(account != null, "account cannot be null");
	Contract.Requires(amount > 0, "amount must be greater than zero");
	...
}

//contract.ensures
public double CalculateDiscount(int originalAmount, string discountCode)
{
	Contract.Ensures(Contract.Result<double>() >= 0);

	return -32;
}

Reference
http://visualstudiomagazine.com/articles/2010/06/23/code-contracts.aspx

http://msdn.microsoft.com/en-us/library/dd264808(v=vs.110).aspx

TPL Task Parrallel Library .net 4.0 parallel programming multi thread threading task queue user work item

//simple parallel function call
Parallel.Invoke(() => somefunc1(), () => somefunc2());

//parallel foreach with two lists
new List<List> tasks = new List<List>()
{
  new List() { new DataSource1ProcessorA() },
  new List() { new DataSource2ProcessorA(), new DataSource2ProcessorB() }
}

Parallel.ForEach(tasks, (items) =>
{
    foreach (var item in items)
    {
        item.GetData();
        item.Process();
    }
});

//new task static factory method approach
Task.Factory.StartNew(() => { data.GetData(); data.Process(); })
.ContinueWith(t => Logger.Error("An exception occurred while processing. Check the inner exception for details", t.Exception),
TaskContinuationOptions.OnlyOnFaulted);

//explicit object oriented
   // Create a task and supply a user delegate by using a lambda expression. 
        Task taskA = new Task( () => Console.WriteLine("Hello from taskA."));
        // Start the task.
        taskA.Start();
        // Output a message from the calling thread.
        Console.WriteLine("Hello from thread '{0}'.", 
                          Thread.CurrentThread.Name);
        taskA.Wait();

//using task run
  Thread.CurrentThread.Name = "Main";
      // Define and run the task.
      Task taskA = Task.Run( () => Console.WriteLine("Hello from taskA."));
      // Output a message from the calling thread.
      Console.WriteLine("Hello from thread '{0}'.", 
                          Thread.CurrentThread.Name);
      taskA.Wait();

References
http://msdn.microsoft.com/en-us/library/dd460705.aspx

(added 20121023 good comprehensive resource with illustrative examples)
http://www.codeproject.com/Articles/362996/Multi-core-programming-using-Task-Parallel-Library

http://www.codeproject.com/KB/threads/ParallelTasks.aspx

Optimize Managed Code For Multi-Core Machines
http://msdn.microsoft.com/en-us/magazine/cc163340.aspx

good blog
http://www.codethinked.com/net-40-and-systemthreadingtasks

queueuserworkitem
http://msdn.microsoft.com/en-us/library/4yd16hza.aspx

threadpool class
http://msdn.microsoft.com/en-us/library/y5htx827.aspx

task class
http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx

task parrallelism
http://msdn.microsoft.com/en-us/library/dd537609.aspx

How to: Use Parallel.Invoke to Execute Parallel Operations
http://msdn.microsoft.com/en-us/library/dd460705.aspx

Custom DAL Class SQL ORM ASP .NET

(common.DataObject may be of your choosing or may simply replace with dynamic)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Data.SqlClient;

using AIS.Common; //this is a common namespace I use in examples throughout my site
using System.Reflection;
using System.Dynamic;

//TODO: consider returning ienumerable in sp return values for lazy eval vs .tolist immediate eval
namespace AIS.DAL.AppName
{
    public static class StoredProcedures
    {
        public delegate void ErrorHandler(Exception ex);
        /// <summary>
        /// If no custom error handling is bound to this event, exceptions will be thrown back up to the calling function.
        /// If custom handling is bound to this event, ensure it does not perform a redirect or kill the thread unless you intend to abort the procedural
        /// steps following the method/function call which threw the error.
        /// </summary>
        public static event ErrorHandler HandleError;

        #region Unique Procedures
        public static List<Common.DataObject> LoadUserSessions_All(dynamic o)
        {
            return ExecuteRead("an_get_db_fn1", o);
        }

        public static List<Common.DataObject> LoadUserSessionsDetails_LiveStream(dynamic o)
        {
            return ExecuteRead("an_get_db_fn2", o);
        }

        public static List<Common.DataObject> LoadUserSessionsDetails_Live(dynamic o)
        {
            return ExecuteRead("an_get_db_fn3", o);
        }

        public static int LogChat()
        {
            return ExecuteScalar("an_get_db_fn4", null);
        }

        public static int LogError()
        {
            return ExecuteScalar("an_get_db_fn5", null);
        }
        #endregion

        //TODO: consider hiding from external assemblies which would require strong mappings above
        #region Execution Logic
        public static List<Common.DataObject> ExecuteRead(string procedurename, dynamic param)
        {
            try
            {
                SqlDataSource sds = new SqlDataSource();
                sds.ConnectionString = ConfigValues.TrainingPortalConnectionString;
                sds.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
                sds.SelectCommand = procedurename;

                if (param != null)
                {
                    foreach (PropertyInfo pi in param.GetType().GetProperties())
                    {
                        object pval = pi.GetValue(param, null);
                        if (pval != null)
                        {
                            sds.SelectParameters.Add(pi.Name, pval.ToString());
                        }
                    }
                }

                List<Common.DataObject> results = new List<Common.DataObject>();
                //sds.Select(new DataSourceSelectArguments()).Cast<DataRowView>().ToList().ForEach(o => Load_AddResult<dynamic>(o, ref results));
                sds.Select(new DataSourceSelectArguments()).Cast<DataRowView>().ToList().ForEach(o => Load_AddResult<Common.DataObject>(o, ref results));

                return results;
            }
            catch (Exception ex)
            {
                HandleError_Condensed(ex);
                return null;
            }
        }

        public static void Load_AddResult<t>(Common.DataObject o, ref List<t> results)
        {
            try
            {
                t r = (t)Activator.CreateInstance(typeof(t));

                foreach (PropertyInfo pi in typeof(t).GetProperties())
                {
                    object v = o[pi.Name].ToString();
                    Type pt = Type.GetType(pi.PropertyType.FullName);
                    //try { pi.SetValue(r, Convert.ChangeType(v, pt), null); }
                    //catch (Exception ex) { HandleError_Condensed(ex); }

                    o.Add(pi.Name, Convert.ChangeType(v, pt));
                }

                results.Add(r);
            }
            catch (Exception ex)
            {
                HandleError_Condensed(ex);
            }
        }

        //public static void Load_AddResult<t>(dynamic o, ref List<t> results)
        //{
        //    try
        //    {
        //        t r = (t)Activator.CreateInstance(typeof(t));

        //        foreach (PropertyInfo pi in typeof(t).GetProperties())
        //        {
        //            object v = o[pi.Name].ToString();
        //            Type pt = Type.GetType(pi.PropertyType.FullName);
        //            try { pi.SetValue(r, Convert.ChangeType(v, pt), null); }
        //            catch (Exception ex) { HandleError_Condensed(ex); }
        //        }

        //        results.Add(r);
        //    }
        //    catch (Exception ex)
        //    {
        //        HandleError_Condensed(ex);
        //    }
        //}

        public static void ExecuteNonScalar(string procedurename, dynamic param)
        {
            try
            {
                ExecuteScalar(procedurename, param);
            }
            catch (Exception ex)
            {
                HandleError_Condensed(ex);
            }
        }

        public static int ExecuteScalar(string procedurename, dynamic param)
        {
            try
            {
                SqlDataSource sds = new SqlDataSource();
                sds.ConnectionString = ConfigValues.TrainingPortalConnectionString;
                sds.UpdateCommandType = SqlDataSourceCommandType.StoredProcedure;
                sds.UpdateCommand = procedurename;

                if (param != null)
                {
                    foreach (PropertyInfo pi in param.GetType().GetProperties())
                    {
                        object pval = pi.GetValue(param, null);
                        if (pval != null)
                        {
                            sds.SelectParameters.Add(pi.Name, pval.ToString());
                        }
                    }
                }

                return sds.Update();
            }
            catch (Exception ex)
            {
                HandleError_Condensed(ex);
                return 1; //1 signifies error in tsql
            }
        }
        #endregion

        private static void HandleError_Condensed(Exception ex)
        {
            if (HandleError != null) { HandleError(ex); } else { throw new Exception(ex.Message, ex); } 
        }
    }
}

Custom AWS S3 Helper Class AWSSDK Wrapper

Implements some very commonly used AWS S3 functionality. (need to merge with my other AWS wrapper classes, Route53, EC2, etc)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.IO;
using System.Collections.Specialized;
using System.Configuration;

//uses AWSSDK.dll from amazon
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;

using System.Xml.Linq;
using System.Xml;

using System.Data;

namespace AIS.Common
{
    public static class AWSHelper
    {
        private static List<S3Bucket> LoadS3Buckets()
        {
            System.Collections.Specialized.NameValueCollection appConfig = System.Configuration.ConfigurationManager.AppSettings;
            using (var s3client = Amazon.AWSClientFactory.CreateAmazonS3Client(ConfigValues.AWSAccessKey, ConfigValues.AWSSecretKey))
            {
                return s3client.ListBuckets().Buckets;
            }
        }

        private static List<S3Object> LoadS3Objects(string bucketname)
        {
            System.Collections.Specialized.NameValueCollection appConfig = System.Configuration.ConfigurationManager.AppSettings;
            using (var s3client = Amazon.AWSClientFactory.CreateAmazonS3Client(ConfigValues.AWSAccessKey, ConfigValues.AWSSecretKey))
            {
                return s3client.ListObjects(new ListObjectsRequest() { BucketName = bucketname }).S3Objects;
            }
        }

        private static void LoadS3File(string bucketname, string keyname, HttpResponse response, string contenttype)
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;


            using (var s3client = Amazon.AWSClientFactory.CreateAmazonS3Client(ConfigValues.AWSAccessKey, ConfigValues.AWSSecretKey))
            {

                GetObjectRequest s3request = new GetObjectRequest()
                    .WithBucketName(bucketname).WithKey(keyname);

                using (GetObjectResponse s3response = s3client.GetObject(s3request))
                {
                    string title = s3response.Metadata["x-amz-meta-title"];

                    response.Clear();

                    //Response.Write(string.Format("The object's title is {0}", title));
                    //Response.AddHeader
                    //Response.ContentType="application/swf";
                    ////Response.ContentType="contenttype";

                    response.ContentType = s3response.ContentType; //s3response.Headers["Content-Length"];
                    long filesize = s3response.ContentLength;

                    byte[] buffer = new byte[(int)filesize];

                    response.BinaryWrite(ConvertStreamToBytes(s3response.ResponseStream, filesize));

                    response.Flush();
                    response.Close();
                }
            }
        }

        public static string GetS3UrlToVideo(string bucketname, string keyname)
        {
            System.Collections.Specialized.NameValueCollection appConfig = System.Configuration.ConfigurationManager.AppSettings;
            string url = "";
            using (var s3client = Amazon.AWSClientFactory.CreateAmazonS3Client(ConfigValues.AWSAccessKey, ConfigValues.AWSSecretKey))
            {
                Amazon.S3.Model.GetPreSignedUrlRequest request = new Amazon.S3.Model.GetPreSignedUrlRequest()
                    .WithBucketName(bucketname)
                    .WithKey(keyname)
                    .WithProtocol(Amazon.S3.Model.Protocol.HTTP)
                    .WithVerb(HttpVerb.GET)
                .WithExpires(DateTime.Now.AddMinutes(ConfigValues.VideoURLExpiration));

                Amazon.S3.Model.GetPreSignedUrlRequest r = new GetPreSignedUrlRequest();

                url = s3client.GetPreSignedURL(request);

                url= "https://s3.amazonaws.com/" + bucketname + keyname;
            }

            //return System.Xml.XmlConvert.EncodeName(url);
            return url;
        }

        public static byte[] ConvertStreamToBytes(Stream input, long filesize)
        {
            byte[] buffer = new byte[(int)filesize];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }
    }
}

Custom Web.Config Wrapper Class ASP .NET

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

namespace AIS.Common
{
    public class ConfigValues
    {
        #region appSettings
        public static string SomeStringOne { get { return getval("SomeStringOne "); } }
        public static string SomeStringTwo { get { return getval("SomeStringTwo "); } }
        public static string Env { get { return getval("env"); } } //keep in mind case sensitivity
        public static string LastManualRefresh { get { return getval("date_last_manual_refresh"); } } //useful for manual site refresh/reload
        public static double SomeDouble { get { return Convert.ToDouble(getval("some_static_double")); } }
        #endregion

        #region connectionStrings - update web.config env variable to toggle between dev and prd
        public static string YourDBOneConnectionString { get { return getcstr("win_web_db"); } }

//also read only implementation like above, but illustrates environment variable usage specific in web.config useful if you have many environments
        public static string YourDBTwoConnectionString 
        {
            get
            {
                if (Env.ToLower().ToString() != "filesystem")
                {
                    return getcstr("static_string" + Env.ToLower().ToString());
                }
                return "";
            }
        }
        #endregion

        /// <summary>
        /// Retrieve Connection String for specified provided key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private static string getcstr(string key)
        {
            try
            {
                return ConfigurationManager.ConnectionStrings[key].ConnectionString;
            }
            catch (Exception ex)
            {
                Shared.HandleError(ex); //TODO: change to throw error event handle instead of direct call for reusability
                return "Error retrieving value";
            }
        }

        /// <summary>
        /// Retrieve appSettings value for provided specified key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private static string getval(string key)
        {
            try
            {
                return ConfigurationManager.AppSettings[key];
            }
            catch (Exception ex)
            {
                Shared.HandleError(ex); //TODO: change to throw error event handle instead of direct call for reusability
                return "Error retrieving value";
            }
        }
    }
}

Custom URLRewriting with XML and Global.asax

utilizes my custom DocParser class here http://ronniediaz.com/2013/08/23/parse-xml-to-dynamic-expandoobject-c-net-4-0/

 void Application_BeginRequest(object sender, EventArgs e)
    {
        //string path = Request.Url.ToString();
        string path = Request.Path;

        if (Regex.IsMatch(path.ToLower(), ".*[.](jpg|png|gif|css|js|pdf|ico|woff|svg|eot|ttf)$"))
        {
            //var h = Regex.Replace(path.ToLower(), ".*/(.*)/(.*)$", "~/$1/$2", RegexOptions.Singleline);
            //Context.RewritePath(path);
            return;
        }
        
        //TODO: authorize user/request
 DocParser dp = new DocParser(Server.MapPath("~/rewrite.xml"));
        var rules = dp.GetElements("*/rule");
        
        foreach (var r in rules)
        {
            if (string.IsNullOrEmpty(r.match_url)) {
                Shared.HandleError("Global.asax::null or empty match_url encountered");
            }

            if (string.IsNullOrEmpty(r.action_url))
            {
                Shared.HandleError("Global.asax::null or empty action_url encountered");
            }
            
            if (Regex.IsMatch(path, r.match_url,RegexOptions.IgnoreCase))
            {
                List<object> qsvars = new List<object>();

                foreach (Match m in Regex.Matches(path, r.match_url, RegexOptions.IgnoreCase))
                {
                    for (int i=1;i<m.Groups.Count;i++)
                    {
                        qsvars.Add(m.Groups[i].Value);
                    }
                }
                //Context.RewritePath(string.Format(r.action_url,qsvars.ToArray()) + "&rewrite=1");
                Context.RewritePath(string.Format(r.action_url, qsvars.ToArray()));
            }
        }
}

rewrite.xml examples

<?xml version="1.0" encoding="utf-8" ?>
<rules>
  <rule match_url="^/home" action_url="~/home.aspx" />
  <rule match_url="^/login" action_url="~/default.aspx" />
  <rule match_url="^/register" action_url="~/welcome/register.aspx" />
  <rule match_url="^/logout" action_url="~/logout.aspx" />
  <rule match_url="^/default/(.*)" action_url="~/default.aspx?q={0}" />
  <rule match_url="^/test/(.*)/(.*)" action_url="~/test.aspx?q={0}&amp;r={1}" />
</rules>

Common functions asp .net static shared library

references custom encryption class here http://ronniediaz.com/2011/01/13/quick-net-encryption-reference/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using System.Text;
using System.Net;
using System.IO;

namespace AIS.Common
{
    public static class Shared
    {
        //TODO: add local, dev, prd
        public static string basehref { get { return HttpContext.Current.Request.ApplicationPath; } }

        //TODO: change to json serialized object reference to prevent manipulation of pipe delimeters
        public static string SetSecureQueryString(object o)
        {
            string ct = Crypto.Rijndael.Encrypt(o.ToString(), "static_or_dynamic_string");
            return HttpUtility.UrlEncode(ct);
        }

        //TODO: change to json (same as above)
        public static string SetSecureQueryString(object a, object b, object c, object d, object e, object f, object g, object h)
        {
            string ct = Crypto.Rijndael.Encrypt(a.ToString() + "|" + b.ToString() + "|" + c.ToString() + "|" + d.ToString() + "|" + e.ToString() + "|" + f.ToString() + "|" + g.ToString() + "|" + h.ToString(), "livestream");
            return HttpUtility.UrlEncode(ct);
        }

        public static string GetSecureQueryString(string q)
        {
            try
            {
                //automatically decodes querystring in request
                return Crypto.Rijndael.Decrypt(q, "static_or_dynamic_string");
            }
            catch (Exception ex)
            {
                return "";
            }
        }

//retrieves content from web url and returns as string
        public static string DownloadString(string url, NetworkCredential nc=null)
        {
            System.Net.WebClient wc = new WebClient();
            if (nc != null)
            {
                wc.UseDefaultCredentials = true;
                wc.Credentials = nc;
            }

            return wc.DownloadString(url);
        }

        //http://mayur.gondaliya.com/programming-languages/c-sharp/samples/fetching-url-contents-into-a-string-using-httpwebrequest-72.html
//same as above function, different approach with more detail
        public static string DownloadPage(string url)
        {

            const int bufSizeMax = 65536; // max read buffer size conserves memory
            const int bufSizeMin = 8192; // min size prevents numerous small reads
            StringBuilder sb;

            // A WebException is thrown if HTTP request fails
            try
            {

                // Create an HttpWebRequest using WebRequest.Create (see .NET docs)!
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                request.Method = WebRequestMethods.Http.Get;

                // Execute the request and obtain the response stream
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();

                // Content-Length header is not trustable, but makes a good hint.
                // Responses longer than int size will throw an exception here!
                int length = (int)response.ContentLength;

                // Use Content-Length if between bufSizeMax and bufSizeMin
                int bufSize = bufSizeMin;
                if (length > bufSize)
                    bufSize = length > bufSizeMax ? bufSizeMax : length;

                // Allocate buffer and StringBuilder for reading response
                byte[] buf = new byte[bufSize];
                sb = new StringBuilder(bufSize);

                // Read response stream until end
                while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
                    sb.Append(Encoding.UTF8.GetString(buf, 0, length));

                return sb.ToString();

            }
            catch (Exception ex)
            {
                sb = new StringBuilder(ex.Message);
                return sb.ToString();
            }

        }

//one approach using filesystem. will only work depending on permissions otherwise url parsing is needed
        public static string GetCurrentPageName()
        {
            string spath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
            System.IO.FileInfo oInfo = new System.IO.FileInfo(spath);
            string spagename = oInfo.Name;
            return spagename;
        }

//get titlecase string
        public static string GetTitleCase(object str)
        {
            try
            {
                return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToString().ToLower());
            }
            catch (Exception ex)
            {
                Shared.HandleError(ex);
                return "Other";
            }
        }

        #region handleerror
        public static void HandleError(Exception ex)
        {
            HandleError(ex.ToString());
        }

        //TODO: send error to error handler
        public static void HandleError(string details)
        {
            SendEmail(details);
        }

        public static void HandleError(Page p, Exception ex)
        {
            HandleError(p, ex.ToString());
        }

        public static void HandleError(Page p, string details)
        {
            //MessageBox.Show(hwnd, details);
            SendEmail(details);
        }

        //TODO: replace with call to error manager or hook to event for compatibility
        public static void SendEmail(string details)  {
        //throw new HttpUnhandledException(details);
            if (Shared.GetCurrentPageName().Replace("/", "") != "error.aspx") //TODO: remove. temporary resolution for unhandled session timeouts. PROTOTYPE
            {
                //HttpContext.Current.Response.Redirect("~/error.aspx");
                //TODO: global error log and local
            }
        }
        #endregion
    }
}

MSSQL User Defined Functions vs Stored Procedures

I received this question earlier today, and thought it was a valid question often misunderstood, and deserving of a small write-up:
“Should a User Defined Function be your first choice instead of a Stored Procedure?”

While there are many pros and cons of each not covered in this write-up (review your versions on MSDN for details), including some features which may not be apparent until you have an issue to troubleshoot (such as sp_who filtering), you can generally ask yourself a single question up front that can help you determine which you should use.

Simply, if the db functionality you need to implement in the function/procedure requires
any DML (insert/update/delete), then go with a stored procedure. Advanced selects and/or filters are best left up to views/table valued functions.

Additionally, do not be afraid to use a combination of functions and procedures especially if there is a goal of re-usability, in accordance with the design considering the planned growth of your db as your software & db architecture permits. On that note, consider and test the performance differences of these implementations, as a compiled/cached function/procedure containing more logic internally may outperform one utilizing logic that is spread throughout.

References
SP_who filtering UDF vs SP, http://stackoverflow.com/questions/2567141/use-sql-to-filter-the-results-of-a-stored-procedure
Data Manipulation Language, http://en.wikipedia.org/wiki/Data_manipulation_language
(Some) Differences (about.com), http://databases.about.com/od/sqlserver/a/procs_vs_functs.htm
(Some) Differences (stackoverflow), http://stackoverflow.com/questions/2039936/difference-between-stored-procedures-and-user-defined-functions

Intro to git

git is essentially decentralized, which seems to be the direction everything is going, so I decided to take a shot at it.

I’ve used cvs, VSS, TFS, SVN and now git and I’ve got to say it is definitely pretty cool (and free).

The main difference I have noticed between git and these other guys is git allows you to make commits to your local machine and push them later. This means faster commits, more commits and therefore more versioning and finer details on revisions, and no need to worry about potential connectivity issues.

Behind the scenes git is also much cleaner on everything from its transmission protocols to its storage mechanism, so overall it is a more evolved product.

I haven’t fully explored all of its features yet, so I’ll keep revisiting this article to keep it updated from time to time.

First of all, you will have to decide upon a remote repository. You could setup your own, but that is currently out of scope of this article. In this scenario I chose projectlocker.

I left all projectlocker settings as default and using ssh as the communication protocol. http(s) is available as well, but ssh rocks :).

If you’re on Windows, download and install Cygwin and make sure you select OpenSSH. Cygwin will give you a nice little linux shell for us to do our work from. If you were hoping for a GUI, try this route first, you might be surprised at the simplicity of the command line.

Open cygwin to create a public key to authenticate to the remote server. Enter ssh-keygen and press enter. Keep pressing enter on all prompts and skip the password.

cd to the ~/.ssh folder where it likely created your key enter cat id_rsa.pub. This will dump the contents of your public key file. Right click on the command prompt title bar of the window and select mark then grab your dumped file and paste in your remote repo service. Make sure the username has no spaces and matches your pc name and is also listed in the file dump.

Save changes in remote service then go back to cygwin. To test you did the above step correctly do “ssh -v [your git without specifying port of \reponame.git]“. It shouldn’t connect fully, but should give you enough status to verify it’s working. If it prompts for password then it was unable to verify public key which the -v output should indicate.

Once the above is good, identify yourself with:
git config –global user.name “yourname”
git config –global user.email “youremail@yourdomain.com”

Then download the remote repository (which may or may not be empty, that’s ok).
git clone [yourauthpart@yourdomainpart:yourreponame.git]

To add in a project I already had in my local, I did the above steps first within C:\git then copied my project folder in C:\git\projectname. cd into git then use this command to add any files within:
git add [filename or wildcard * for all]
git commit -m “my first commit!”

Then to push up to repo at any point simply use:
git push origin master

And that’s it!

(Optional: If you get an error on push origin or skipped clone then first do):
git init
git remote add origin [yourauthpart@yourdomainpart:yourreponame.git]
git pull origin master

So to sum up the steps we have:
1) setup repo on remote service
2) install cygwin and openssh (skip this step on *nix)
3) ssh-keygen (enter on all prompts)
4) cat public key and enter in remote repo service
5) test key setup is correct using ssh
6) identify your user and email to git
7) clone the repo and begin adding, committing and pushing!

Rock and roll!

References
cforcoding.com (blog), http://www.cforcoding.com/2009/09/windows-git-tutorial-cygwin-ssh-and.html
git-svn crash course, http://git.or.cz/course/svn.html
bahrenbugs (blog), http://blog.bahrenburgs.com/2010/01/using-git-with-projectlocker-on-mac.html
projectlocker, http://projectlocker.com/
cygwin, http://www.cygwin.com/

How to Create secure relational databases in SQL

The first step to a secure DB, is a well structured DB and the application layers that access it.

Take the following example of a table containing factories and the robots they produce.

FACTORYNAME ROBOTNAME
FACTORY1 Ron
FACTORY1 John
FACTORY2 Bob
FACOTRY2 Bill

This serves a good purpose by itself, and allows for easy manipulation and viewing of the stored data, but this table could very quickly grow out of hand. What if you needed to store the parts that are required to make each robot? Or if some factories share the types of robots that they can create?

First, lets separate the data into two separate tables of factories and robots:

“SP_GET_FACTORIES”

FACTORYID FACTORYNAME
1 FACTORY1
2 FACTORY2

“SP_GET_ROBOTS”

ROBOTID ROBOTNAME
1 Ron
2 John
3 Bob
4 Bill

In order to group these two together. we now require a mapping table.
“FactoryRobotMapping”

FACTORYID ROBOTID
1 1
1 2
2 3
2 4

To see this data in a single set, like your original table, you would run a select statement with a join. Some programmers put these statements with joins directly in their code as plain text while others keep them in the database.

Relatively newer technologies, such as Microsoft Linq or Ruby have their own syntax for performing these joins and queries which is ultimately translated to plain sql behind the scenes.

Unfortunately, this often leads to a common misconception that because you are using Linq, Ruby or another data access layer that your work ends there.

Consider the following scenario:
App A->retrieves a join of factories and robots
App B->also retrieves the same join

To make this simpler, you create a new project (this would be your data access layer) and add a new method called “GetRobotsInFactories” which uses Linq, plain sql, ROR or some other technology to run the select with the join.

So now you have:
App A->DAL->GetRobotsInFactories
App B->DAL->GetRobotsInFactories

For future changes, simply modify GetRobotsInFactories, upload the DLL and that’s it! Or is it?

What if a new business change now requires you to only get robots in factories after specific manufacture dates?

You could just add an optional parameter to GetRobotsInFactories, but now you have to code in conditional logic to your function checking if the parameter is null, and forming a different query based on this. If there are 10 more parameters like this, your function could now very quickly become much more troublesome to support, especially when certain combinations of parameters may be required.

This creates a weaker structure, and therefore opens the door to security vulnerabilities. The approach on separating the DAL into a new project and wrapping everything in here is great, but you must be very careful on how your DAL accesses the DB.

What’s the alternative?

Views are joins

For starters, creating views in the database for your joins will save you from having to constantly type out select statements with joins and improve your productivity in database debugging greatly.

An example of such join for our above is:

“VW_JOIN_FACTORIES_ROBOTS”

select * from factories inner join robots on 
factories.factoryid = robots.robotid

This now also allows you to perform specific select statements against the view, which will look very similar to your first table you created before segregating the data.

Cool, now what?

You might consider plugging in a simple “select * from VW_JOIN_FACTORIES_ROBOTS” into that GetRobotsInFactories function, but not done yet.

Stored Procedures offer security

Many developers understand the minimal amount of SQL required to power their app, or have heard of or created and modified views as well as stored procedures, but often are not aware of the security benefits.

Stored procedures encapsulate the data you need to retrieve. This allows you to control not only the tables being modified, but the way they are modified, dependencies, constraints, parameters and even database permissions on who can execute or modify which stored procedures and ultimately obfuscate your underlying data from would be attackers or meddlers.

Consider the following stored procedure:

“SP_GET_ROBOTS_IN_FACTORIES”

USE [RobotCo]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIED ON
GO
CREATE PROCEDURE [dbo].[RobotCo] (@MfgDate datetime)
AS
BEGIN
SET NOCOUNT ON;
select * from VW_JOIN_FACTORIES_ROBOTS where datetime between @MdfDate and getdate()
END

You can now change your “GetRobotsInFactories” function to call “SP_GET_ROBOTS_IN_FACTORIES” and simply pass in date as a parameter to the SP. Future changes will only require you to add parameters to the SP and then simply update the DAL/dbml or definition if you’re using linq/ror/etc.

Locking it down

All structures are already in place! You’re next steps are to make sure the applications have their own SQL user accounts with only access to execute the specified stored procedures.

Without direct access to the view or the tables, exploitation of the app will prevent attackers from retrieving or manipulating the data directly.

Hopefully this offered some insight on database level security, as well as understanding some of the benefits of view and SP utilization for better overall software architecture.

References
Microsoft Linq, http://msdn.microsoft.com/en-us/netframework/aa904594
Ruby on Rails, http://rubyonrails.org/

Follow

Get every new post delivered to your Inbox.