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

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

How to Create a new Java Applet in Netbeans

First create a new project. Make sure you select “Java Application” not Desktop Application or other types.

On the left hand of the screen you should see “Source Packages” and your project name in lower case underneath. If you don’t see this in the little window on the left, expand the coffee icon with your project name.

20121130_java_01

Right click your package (mine is javafileuploader in the screenshot above) and select New->Java Class.

Make sure your new class is selected, and then referencing my code snippet below, import java.applet.* and java.awt.* then add new functions for “paint” and “init”.

(code snippet courtesy of ehow link in references)

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javafileuploader;

import java.applet.*;
import java.awt.*;

/**
 *
 * @author fedora
 */
public class NewClass extends Applet {
int m_height, m_width;

public void paint(Graphics m) {
m.setColor(Color.black);
for (int i=0; i<10; ++i)m.drawLine(m_width,m_height,i*m_width/10,0);
}

public void init() {
    m_width=getSize().width;
    m_height=getSize().height;
    setBackground(Color.green);
}
}

Once you have this typed/pasted in, select run->file and voila! you should see a little applet window appear with a green background and oblique lines. You’re now ready to begin. Enjoy!
20121130_java_02

References
ehow.comhttp://www.ehow.com/how_6210608_create-java-applet-netbeans.html

Non-static method requires a target

In my specific situation where I received this error, I was able to resolve it by simply changing “null” to the object containing the method which needed to be call.

This error indicates a use of reflections that can easily be confusing, but is very simple to resolve.

The specific resolution in the (StackOverflow) example in the referenced link below did not apply to my situation, but helped me quickly understand what caused the error and come to quick resolution by simply reading through the responses.

Example code from reference below:

public static T Test<T>(MyClass myClass) where T : MyClass2, new()
{
    var result = new T();
    //...
}

For specific code example where I encountered this message and how I was able to resolve, see the snippet below or my full post Call Parent Page from User Control.

Quick comparison where I encountered the error:

if (mi!=null) mi.Invoke(null, new Object[] {sender,e }); //throws indicated error

if (mi!=null) mi.Invoke(this.Page, new Object[] {sender,e }); //runs through clean

References
“Call Parent Page from User Control”, https://ronniediaz.com/2011/07/15/call-parent-page-from-user-control/
StackOverflow, http://stackoverflow.com/questions/3577407/non-static-method-requires-a-target-in-propertyinfo-setvalue

Bind Control to an Object in Windows Forms

Simple solution for basic binding in Windows Forms app. This would NOT be recommended if you are using ASP .Net, Silverlight, WCF, RIA or any other services to retrieve the data as these project types have much better support for binding to controls.

C#:

static class dataaccess {
static mytype object;
}

//on app load
object = new mytype();

//on form load
tbField1.DataBindings.Add("Text", dataaccess.object.property, "Field1")

Encryption 101 and Security for the Paranoid

Asymmetric Cryptography

Asymmetric Cryptography

Modern day television, cinemas and news have created a big hype around security, especially computer security, usually without any good explanation.

I’m not going to tell you that hype is false, there is definitely a growing need to be careful in these areas, but in order to make informed decisions you need to become knowledgeable about the subject.

Unfortunately most literature and content that comes from these media outlets glances on these topics just enough to make a cautious viewer paranoid, but are not necessarily informative.

Fact:
Computer security issues are increasing as well as personal safety in general with regards to technology, such as card swiping, identity theft, etc. (Source: US GOVT).

Fiction:
By spending all your money on expensive antivirus software, home security systems, identity theft protection and specialized credit cards you will be completely safe and can rest soundly.

The reality is the best protection you can really offer yourself is mostly common sense and can be remembered with a simple timeless phrase…

Never put all your eggs in one basket.

24 Security Tips for the Paranoid

(that don’t require emptying your wallet)

(see glossary below for any terms you are unfamiliar with)

[1]

If there’s a little flashing icon in the bottom of your screen that says viruses have been found on your PC, or notifications offering to help you “fix” your PC, DON’T CLICK ON IT. 75% of all computer repairs I handle were victims of this circumstance. Well known vendors such as Norton, AVG and CA allow you to run timed and manual scans. If you’re not sure where this flashing little icon came from, Google it.. or email me. 🙂

[2]

If you’re concerned about online credit card theft, get a separate credit card just for online purchases with a very low spending limit.

[3]

Try to use common checkout methods you are familiar with such as Paypal and Google Checkout. Google and paypal have certain specifications for these methods that in many cases make them more secure than the standard method on a particular site.

[4]

Keep track of sites where you store your credit card numbers (if you choose to store them at all). In the event of compromise from online purchases this will help you identify the point of breach and you were likely not the only person affected.

[5]

Research pre-paid cards which aren’t necessarily tied to a long term account and already have many built in securities.

[6]

Memorize important numbers that do not change, such as your SS, Bank and Routing. Don’t write them down and especially don’t store them electronically.

[7]

It’s hard to memorize all your passwords, so write down hints instead. If your password is related to the date you bought your first $animal (<- dog), write down something obscure like the last name of your $animal veterinarian or something even harder to relate like just a number representing the age of your animal (in $animal years).

[8]

Visit only well known websites and be careful of links from blogs 😉 and places your friends may refer you to which could unknowingly be compromised. Social networks, much like school, are an easy place to pick up germs. Secure ecommerce sites should certify that they are PCI compliant.

[9]

Learn how basic encryption works. Many applications such as outlook contain plugins for popular encryption techniques such as GPG.

[10]

Be wary of public terminals, airports and coffee shops. Even if you’re on your smart phone and browsing the WiFi at your favorite Starbucks or even JFK, the entire location or an individual access point could have been compromised or an attacker could be snooping and that cool remote banking app on your phone could open up a can of worms.

[11]

Similar to the above, always use https and/or secure networks only (esp. if wireless) whenever possible. Learn how to add Mac address filtering on your local wireless network or call your favorite local IT guy (me!) and ask them what you could do to lock down.

[12]

If possible, keep a small safety net. While disputing fraud or identity theft, you may need funds temporarily to cover bills and other perishables until the issue is resolved.

[13]

If you’re loaning money to your son/daughter/family member or close friend, give them cash or a prepaid credit card which you can refill as needed or transfer money to their bank. Loaning credit cards can be very dangerous especially if the one you are helping doesn’t follow similar security tips as these.

[14]

If you’re traveling or visiting somewhere you don’t go very often, such as a business or personal family trip, or a not frequently visited restaurant – use cash. Most types of fraud occur overseas and on long-distance trips. (Source: US GOVT).

[15]

If you lose your cell phone or wallet, make sure to cancel any and all cards and identification contained within or have numbers re-issued. This will be a hassle, but it’s worth it.

[16]

Always lock or password protect your computer and electronic devices whenever possible. A lost cellphone or laptop could contain personal information and lead to compromise. In addition, many devices such as smartphones contain security countermeasures which allow you to remotely wipe the device if it is lost.

[17]

Own at least two forms of photo identification and only carry at most one on your person if possible. Whether it is military ID, state ID, drivers license or passport, if you happen to lose one it is often easier to re-obtain if you still have the other.

[18]

When you’re leaving the house, only bring the necessities. You should probably always carry your drivers license, especially if you’re pulled over for speeding ;). You or a relative’s social security card and other non-critical credit cards may not always need to be in your possession however. If you frequently use checks, keep a few in your wallet or purse, but don’t bring the whole checkbook.

[19]

Don’t share passwords or accounts! Your husband or spouse might be the exception, but make sure he/she is also familiar with these tips if you do.

[20]

If you’re concerned about home invasion, theft or burglary, purchase or make a sign which indicates the home is under surveillance and protected. Even if no such protection exists, this will often ward would-be attackers casing your home. If one or more of your neighbors has the same protection, they will likely avoid your neighborhood altogether permanently.

[21]

When traveling and away from home for a long period, a webcam can be setup as basic home surveillance. Keep in mind, this could also open up the possibility of your webcam becoming compromised so make sure they are setup in places such as the main room or doors and entry ways and do not make them accessible over the internet unless you first tunnel through a VPN.

[22]

Place anything important in a safe whenever possible. Jewelry or belongings which are rarely used fall into this category.

[23]

For home based businesses or small business owners – Beware of dumpster diving and make sure you have locked filing cabinets and shred any documents you don’t need. Old documents can be scanned and archived electronically and stored onto tape or other persistent media which can be encrypted. This can also be helpful in the event of a flood or fire.

[24]

If you’re extremely paranoid and worried that basic antivirus and a home alarm system or sign/neighborhood watch won’t be enough, purchase DIY home booby traps, watch every Home Alone movie in one sitting, and be prepared to lose all friend and family relations. Get ready for a long and lonely life. 😛

Glossary of Terms:

safety net – An alternative bank account, safe or separately managed funds to help you pay for expenses while recovering from fraud or any other event which could affect your existing assets.

SSL – A protocol which wraps your connection to a website inside a “secure socket layer” of encryption.

Dumpster Diving – Bad guys going through your trash looking for information.

VPN – Virtual Private Network. A secure way of accessing your home remotely. Call your local IT guy or do some Googling to set one up.

Casing – Bad guys driving through your neighborhood looking for targets. To prevent, talk to your neighbors, or put a sign and/or camera in front of the house.

skim / skimming / swiping – This is when bad guys posing as good guys, at your local restaurant or favorite retail store in the city, illicitly obtain your credit card number. Remember the tips regarding credit cards above as this crime is likely to increase over the next few years.

snoop / snooping / sniffing – In the context of computer security, this is usually when another user on the network is listening or capturing all information going to and from. Stick to SSL sites and secure wireless networks only.

encrypt / decrypt – Encryption is the process of transforming content from plaintext into ciphertext. decryption is the reverse; from ciphertext to plaintext.

plaintext / ciphertext – plaintext is human readable. like your email or the text messages on your phone. ciphertext is garbled and in many cases not even alphanumeric characters. writing in pig-latin or through a mirror is not making ciphertext. ciphertext requires someone to either know or guess the key, password, passphrase and/or vectors and apply a specific type of decryption to reverse.

key / password / passphrase / vector – These are all roughly synonymous with password and are sometimes stored in files instead of being typed in. Research encryption for more info on vectors.

TDES / AES / Rijndael / 128bit /block cipher – If you see or hear any words like this, they are talking about encryption and cryptography. These are different types. Read more on Wikipedia or my other pages.

bit (strength) – In the context of computer security or encryption this usually is in reference to the strength of the security, measured in bits. This can also apply to SSL strength since this utilizes encryption. Common values include 40bit, 64bit, 128bit, 256bit and 512bit.

asymmetric / symmetric – This identifies the process a particular encryption method uses, generally with regards to how information is communicated between two or more parties. It doesn’t necessarily govern HOW the data is encrypted, just the process flow of the data itself from beginning to end. See references below and research GPG for examples on how this might be usable in your everyday life.

pci compliance – Payment Card Industry standard on how personal data should be stored, processed and transmitted. Very important and might be better to understand for your general knowledge than you might think. See references for links.

Conclusion

For a technical illustration, take a look at my quick net encryption reference for a working example in Microsoft .Net which illustrates asymmetric key encryption.

See articles on encryption at Wikipedia and similarly linked articles for a more complete reference.

References:
Wikipedia, Encryption, http://en.wikipedia.org/wiki/Encryption
U.S. CERT, http://www.us-cert.gov/cas/tips/
GPG, http://www.gnupg.org/
PCI DSS, https://www.pcisecuritystandards.org/security_standards/index.php