Blog Archives

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); } 
        }
    }
}

system.windows.resourcedictionary. source threw an exception wpf c#

In general this issue is caused when a referenced resource cannot be found.

<Application x:Class="AppName.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

In my specific circumstance, as the xaml above details, this issue was caused by a reference to PresentationFramework.Aero DLL that was not contained in the output bin folder of the compiled project. Under references, setting Copy Local to true did the trick for me.

References
http://stackoverflow.com/questions/3747972/wpf-usercontrol-cannot-find-xaml-resource-in-referencing-project

Android Launch Browser from App to handle external URLs

Upon googling for this one, I found some good relevant links on stack overflow as well as the android webview documentation, but no singular solution that tied everything together.

First, I created a custom WebViewClient class. Note that this is optional as you can do inline class declarations in this environment.

package com.example.testapp;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.Intent;

public class MyWebViewClient extends WebViewClient {
@Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url != null &amp;amp;&amp;amp; url.startsWith('http://192.168.1.101')) {
            return false;
        } else {
        	view.getContext().startActivity(
                    new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
    }
}

Then, in the main activity, use code within onCreate to support for multiple windows and to set the web view client to your own custom client.

package com.example.testapp;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.net.Uri;

public class MainActivity extends Activity {

	private WebView webView;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	final Context context = this;
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    	webView = (WebView) findViewById(R.id.webView1);
    	webView.getSettings().setJavaScriptEnabled(true);
    	
    	webView.getSettings().setSupportMultipleWindows(true);

    	webView.setWebViewClient(new MyWebViewClient());
    	webView.loadUrl('http://192.168.1.1/login.aspx');
    }

If you want to use an inline class declaration instead of defining a seperate mywebviewclient class, you can also use something like:

    	webView.setWebViewClient(new WebViewClient() {
    	      @Override
    	      public boolean shouldOverrideUrlLoading(WebView view, String url) {
//etc, same code as above
    	      }
});

If you have not already addressed the question of handling the android back button within your webview, the android documentation has a good quick simple code reference on how to accomplish this.

Enjoy. :)

References
StackOverflow, http://stackoverflow.com/questions/5979361/android-open-url-in-a-new-window-without-leaving-app

StackOverflow, http://stackoverflow.com/questions/7028258/launch-browser-from-within-app-how-do-you-get-back-to-the-app

Android Documentation, http://developer.android.com/reference/android/webkit/WebView.html

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/

Simple Javascript CountDown timer and Page Redirect in HTML

<html>
<title>SiteName (test)</title>
<head>
<script type="text/javascript">
var ss = 10;
function countdown() {
ss = ss-1;
if (ss<0) {
window.location="http://www.sitename.com";
}
else {
document.getElementById("countdown").innerHTML=ss;
window.setTimeout("countdown()", 1000);
}
}
</script>
</head>
<body onload="countdown()">
<center>
<table width="100%" height="600px" style="text-align:center;">
<tr><td valign="center"><h3>Redirecting to <a href="http://www.sitename.com">www.sitename.com</a> (<span id="countdown" style="color:green;">10</span>)</h3></td></tr>
</table>
</center>
</body>
</html>

Get Current Directory in Objective-C

Since Mac OS X is a unix based system, you can always use “getcwd” from the standard C library, but in general if you want to stick within the context of Objective-C/Cocoa, see the examples below.

Here’s one snippet you will probably Google quickly, but ultimately not the solution I chose.

(original code from stackoverflow see reference below)

NSFileManager *filemgr;
NSString *currentpath;

filemgr = [[NSFileManager alloc] init];

currentpath = [filemgr currentDirectoryPath];

Solution

Using the “bundle path” rather than “executable path” turned out to work much better in my instance:

NSString *currentpath = [[[[NSBundle mainBundle] bundlePath] stringByDeletingPathExtension] stringByDeletingLastPathcomponent];
NSString *fileName = [NSString stringWithFormat:@"%@/%@/",currentpath,@"filename.pdf"];

References
stackoverflow.com, http://stackoverflow.com/questions/3692489/getting-current-directory-in-objective-c
friendlydeveloper.com, “NSFileManager”, http://www.friendlydeveloper.com/tag/nsfilemanager/
techtopia.com, “Working with Directories in Objective c”, http://www.techotopia.com/index.php/Working_with_Directories_in_Objective-C
Macrumors Forums, http://forums.macrumors.com/showthread.php?t=524754
stackoverflow, “Find Parent Directory of a path”, http://stackoverflow.com/questions/1309524/cocoa-objc-find-parent-directory-of-a-path

With Statement in C# .Net

If you’re stumbling across this article, chances are you may be looking for a replacement for VB .Net’s “with” statement.

Sadly, there is no exact replacement, but there are alternatives which are equally helpful.

Given a basic class “Robot” below:

public class Robot {
public string name {get;set;}
public int age {get;set;}
}

Variable Declaration

If you were using “With” simply for initial variable declaration so you didn’t have to specify long constructors, you can use the following instead:

public Robot MyRobot = new Robot() {name="Ronnie-5", age=3300};

If you were using “With” to stay within the context of an object while performing a specific task, then there is no direct equivalent, although I would definitely advise you to try “using” if you’re not already.

using (Robot MyRobot = new MyRobot()) {
MyRobot.name="Ronnie-5";
MyRobot.age=3300;

if (MyRobot.name=="something") {
//do something
}
//when finished it will automatically dispose for you
}

Extension Methods

Another approach, if your concern is code readability and brevity is to begin using some generic class extension methods in your project to help you simplify common tasks. (see example below)

(Kudos to Anay Kamat for clean and reusable code.)

public static class MetaExtensions
{
	public static void Set(this object obj,params Func<string,object>[] hash){
			foreach(Func<string,object> member in hash){
				var propertyName = member.Method.GetParameters()[0].Name;
				var propertyValue = member(string.Empty);
				obj.GetType()
					.GetProperty(propertyName)
						.SetValue(obj,propertyValue,null);
			};
	}
}

So you could also alternatively replace “With” by adding the above class extension method and simply doing:

var myrobot = new Robot();
myrobot.Set(
	name=> "Ronnie-5",
	age=> 3300
);

//or as a one-liner

myrobot.Set(name=>"othername",age=>otherage);

Now this is technically more lines of code than simply declaring initialization values in the first code snippet, but the upside is… well actually, I’m not sure of the upside, but it’s definitely cool. :)

References
Anay Kamat (blog), http://anaykamat.com/2009/08/09/simple-equivalent-of-with-statement-in-c-sharp/
MSDN (Extension Methods), http://msdn.microsoft.com/en-us/library/bb383977.aspx

URL Encode in .Net

C#: (ASP .Net)

System.Web.HttpUtility.UrlEncode()

C#: (Client/Server Environment)

Uri.EscapeUriString()

References
MSDN, WebUtility Classhttp://msdn.microsoft.com/en-us/library/system.net.webutility.aspx
MSDN, Uri Classhttp://msdn.microsoft.com/en-us/library/system.uri.escapeuristring.aspx
MSDN blogs, http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx

JQuery Grid Themes

Useful links to JQuery grids utilizing (mostly) standard UI themes and/or very little code.

Google!
http://jquery-ui.googlecode.com/svn/branches/labs/grid/tests/static/grid/default.html

Datatables.Net:
http://www.datatables.net/styling/themes/smoothness

Ke-Cai:
http://www.ke-cai.net/2010/01/theme-your-table-with-jquery-ui.html

Trirand:
http://www.trirand.com/blog/jqgrid/jqgrid.html

Stackoverflow:
http://stackoverflow.com/questions/2613632/jquery-ui-themes-and-html-tables

JQuery and Partial Postbacks

I recently came across an issue where JQuery bindings no longer functioned after a partial postback and stumbled upon some code that was helpful in most cases.

Javascript (JQuery):

Sys.Application.add_load(startJQuery); 

startJQuery() { 
//do JQ here
}

And alternatively..

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(){});

This code will not always work however, as was the case in my particular scenario, so I resolved using an alternate method.

RegisterStartupScript is great functionality, and can be useful for loading javascript dynamically on an as-needed basis.

The example below, based on prior code selects the correct JS file to use, then loads it using the registerstartupscript function. This is all within a code block which calls an update panel

C#:


int scriptnumber = 1;
string FilePath = String.Format("~/Scripts/Script_{0}.js",scriptnumber.ToString());
System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(FilePath));
            jqueryfileoutput = sr.ReadToEnd();

            upnlBodyContent.Update();

            ScriptManager.RegisterStartupScript(this, this.GetType(), "scriptname",
                "<script type=\"text/javascript\">" + jqueryfileoutput.ToString().Trim() + "</script>", false);
Follow

Get every new post delivered to your Inbox.