Thursday, May 7, 2009

C# How To: Cascading dropdowns on a Formview for Country\Region selection

This is something most ASP.Net apps deal with regularly, but I couldn't find one solid solution on the interwebs. I needed a user to select a country and then have the "Region" dropdown be populated with the expected list of regions (states, provinces, etc)
I hope this helps. If not, at least I'll remember how it's done.

FYI, I've intentionally left out some details around data access since I am using ObjectDataSources and you can handle data access however u need. I also assume that you have a simple FormView control working that can update a record in your database.

Steps:
1: Make sure 'EnableViewState=true' is on your ASPX page or Masterpage.
2: Make sure you have a field like Country and Region in the DataTable you are editing and make sure you can update these values through an objectdatasource, if you want this example to work.

3: Create an objectdatasource (ie. odsCountries) that returns a list of Countries and bind to ddlCountry.

<asp:ObjectDataSource ID="odsCountries" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetCountries" TypeName="BLL">
</asp:ObjectDataSource>

4: Create an objectdatasource (ie. odsRegions) that returns a list of Regions with a Country parameter and bind to ddlCountry.

<asp:ObjectDataSource ID="odsRegions" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetRegions" TypeName="BLL">
<SelectParameters>
<asp:ControlParameter ControlID="editForm$ddlCountry" Name="Country"/>
</SelectParameters>
</asp:ObjectDataSource>


5: Add a Country dropdownlist to the Formview's edit template (ie. ddlCountry)

<asp:DropDownList ID="ddlCountry" runat="server" SelectedValue='<%# Bind("COUNTRY") %>' DataSourceID="odsCountries"
OnDataBound="ddlCountry_DataBound" DataTextField="Country" DataValueField="Country" AutoPostBack="True"></asp:DropDownList>


6: Add a Region dropdownlist to the Formview's edit template (ie. ddlRegion)

<asp:DropDownList ID="ddlRegion" DataSourceID="odsRegions" runat="server" AutoPostBack="True"
DataTextField="REGION" OnDataBound="ddlState_DataBound"/>


7: Create 2 DataBound EventHandlers for each DropDownlist

protected void ddlCountry_DataBound(object sender, EventArgs e)
{
DropDownList ddlCountry = (DropDownList)sender;
ListItem li = new ListItem("Choose a Country", "");
ddlCountry.Items.Insert(0, li);

FormView editForm = (FormView)ddlCountry.NamingContainer;
if (editForm.DataItem != null)
{
string strCountry = ((DataRowView)editForm.DataItem)["COUNTRY"].ToString();
ddlCountry.ClearSelection();
ListItem li2 = ddlCountry.Items.FindByValue(strCountry);
if (li2 != null) li2.Selected = true;
}
}

protected void ddlRegion_DataBound(object sender, EventArgs e)
{
DropDownList ddlRegion = (DropDownList)sender;
ListItem li = new ListItem("Choose a Region", "");
ddlRegion.Items.Insert(0, li);

FormView editForm = (FormView)ddlRegion.NamingContainer;
if (editForm.DataItem != null)
{
string strRegion = ((DataRowView)editForm.DataItem)["REGION"].ToString();
ddlRegion.ClearSelection();

ListItem li2 = ddlRegion.Items.FindByValue(strRegion);
if (li2 != null) li2.Selected = true;
}

}


8: Don't forget to add this to your Update\Insert parameters on the Objectdatasource for your formview. This is needed to properly find the Region ddl within the Formview

<asp:ControlParameter ControlID="editForm$ddlRegion" Name="Region" />

Thursday, March 26, 2009

C# How To: Create a simple "module" framework using ASCX UserControls

The concept is pretty basic, I simply want to re-use various ASCX user controls I've created within various ASPX Webforms that also happen to use MasterPages. I also want to handle error messages through a lable on the Webform. Another advantage of this is that you can organize your UI into a bunch of usercontrol files within a folder structure. It's not a groundbreaking design pattern, but works nicely for many small projects.

So, the end goal is to be able to pass a querystring to determine which control to load within the page. The URL would look like this: domain.com/Default.aspx?mod=grid

So, there are 4 items you need to create for my example: (in this order)
- /MasterPage.master (Master Page)
- /default.aspx (Webform)
- /default.aspx.cs (Webform codefile)
- /Modules (folder)
- /Modules/grid.ascx (UserControl)

Here's my default.aspx code:
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" CodeFile="Default.aspx.cs" Inherits="Default" %><asp:content id="Content1" runat="Server" contentplaceholderid="ContentPlaceHolder1"><asp:label id="ErrMsgLbl" runat="server"></asp:label></asp:content>

My Default.aspx.cs code:
public partial class Default : System.Web.UI.Page
{
string ModuleName = "";
protected void Page_Init(object sender, EventArgs e)
{
if (Request.QueryString["mod"] != null)
{
ModuleName = Request.QueryString["Mod"].ToString();
ContentPlaceHolder cph = this.Master.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;

try
{
UserControl usercontrol = this.LoadControl("~/Modules/" + ModuleName + ".ascx") as UserControl;
cph.Controls.Add(usercontrol);
}
catch (Exception ex){ErrMsgLbl.Text = ex.Message;}
}
}
My Grid.ascx code:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Grid.ascx.cs" Inherits="Modules_Grid" EnableViewState="False" %>...your controls go here...


Cheers!

Sunday, March 15, 2009

The only certainty is volatility. Get into short-term trading.

As you already know, the stock market in recent years has been a rollercoaster ride. If you started investing in blue chip stocks a few years ago, then you are probably among the millions who have been burned by the downturn that started in October of 2007 . The Dow went from an all-time high of 14,000+ to a 12-year low of 6,500 in less than 12 months. This was one of the greatest amount of wealth ever lost in U.S. history. In fact, over 25% of the U.S "millionaires club" were revoked of their membership cards and kicked to the curb.
So, what does this mean for the next 12 months? Well, as of today, the DOW is UP 9% for the past 5 days and actually DOWN 8% for the past month. But of course, people like Bernanke and the CEOs of Citigroup and Bank of America are telling us that this downturn may be on its way back up and that the banks are running at a profit again. I find it pretty hilarious that the market still responds positively to anything that these snake oil salesmen say. These are the same BS artists that have been lying about profits for years and got us into this mess.
My prediction is that the corruption on Wall St. is at an all-time high right now while bankers and the greediest of the greedy all scramble to save their own asses. This bear market rally, to me, reeks of an inside job and I am not convinced that 6500 will be the bottom.
Having said all that, I think there is still opportunity to make some profits this year. My strategy is stay as short term as possible with my trades and to buy into sectors when they get hit with bad news and then sell when they bounce off the bottom. One example trade I made was I bought Citigroup (3/6) @ $1.05 and sold it (3/10) @ $1.45 . Of course, I could have held it 2 more days and made another 20%, but I took my profit while I had the chance. Another example would be HealthSpring (HS), that fell to $5 after Obama announced medicare cutbacks and then Popped up to $6.50 3 trading days later.
So... if you wanna try your "luck" at this action there are a couple things you could do before risking your shirt. First, you can join http://www.updown.com/ and experiment with some trading techniques with zero risk and maybe even win some actual money. Then, once you have a handle on all the different types of trades\orders you can make go over to http://www.thinkorswim.com/ and give their trading application a try. Their desktop product is very professional and will take you from beginner trader to advanced. Also, they have a "paper money" account that lets you place virtual trades while you're getting the hang of their platform. I really like the advanced orders that you can place, like the many conditional orders. For example, I can have a BUY order automatically placed when a stock hits a certain Bid\Ask price and then after that order is filled, immediately place a SELL order placed at a specific price. You can even have a order placed if the DOW hits a certain level. All very handy when your trying to to do some profit taking and you don't have time to monitor all day long.
Lastly, don't forget to read about different trading strategies here: http://www.stta-consulting.com/TS/basic.htm
Good luck!

"The only constant is change, continuing change, inevitable change, that is the dominant factor in society today. No sensible decision can be made any longer without taking into account not only the world as it is, but the world as it will be." - Isaac Asimov

Tuesday, January 27, 2009

Active Directory properties (LDAP user attributes)

As I promised in my previous post: howto retreive logged on users email from AD
Below is a list of all the Active Directory properties (LDAP user attributes)

-CN
Common Name CN=Guy Thomas. Actually, this LDAP attribute is made up from givenName joined to SN.

-description
What you see in Active Directory Users and Computers. Not to be confused with displayName on the Users property sheet.

-displayName
displayName = Guy Thomas

-DN
also distinguishedName DN is simply the most important LDAP attribute.

-givenName
Firstname also called Christian name

-homeDrive
Home Folder

-name
name = Guy Thomas. same as CN.

-objectCategory
Defines the Active Directory Schema category. For example, objectClass = Person

-objectClass
objectClass = User. Also used for
Computer, organizationalUnit, even container. Important top level container.

-physicalDeliveryOfficeName
Office! on the user's General property sheet

-profilePath
Roamingprofilepath:connect

-sAMAccountName
sAMAccountName=guyt.OldNT4.0logon
name,must be unique in the domain. Can be confused with CN.

-SN
SN = Thomas. This would be referred to as
last name or surname.

-userAccountControl
Used to disable an account. A value of 514 disables the account, while 512 makes the account ready for logon.

-userPrincipalName
userPrincipalName = guyt@CP.com Often abbreviated to UPN, and looks like an email address.

-c
Country or Region

-company
Company or organization name

-department
Useful category to fill in and use for filtering

-homephone
Home Phone number, (Lots more phone LDAPs)

-l
(Lower case L) L = Location. City ( Maybe Office


-location
Important, particularly for printers.

-manager
Boss, manager

-mobile
Mobile Phone number

-ObjectClass
Usually, User, or Computer

-OU
Organizational unit

-postalCode
Zip or postal code

-st
State, Province or County

-streetAddress
First line of address

-telephoneNumber
Office Phone


Exchange Specific LDAP attributes
-mail
An easy, but important attribute. A simple SMTP address is all that is required

-mailNickname
Normally this is the same value as the sAMAccountName, but could be different if you wished. Needed for mail enabled contacts.

-mDBUseDefaults
Another straightforward field, just the
value to:True

-msExchHomeServerName
Exchange needs to know which server to deliver the mail.

-proxyAddresses
As the name 'proxy' suggests, it is possible for one recipient to have more than one email address. Note the plural spelling of proxyAddresses.

-targetAddress
SMTP:@ email address. Note that SMTP is case sensitive. All capitals means the default address.

Wednesday, January 14, 2009

W3GiftCards featured on KillerStartups

Today, W3GiftCards.com was featured on KillerStartups.com
Please visit the page and vote for us.

We need a few more votes to get the Top 10 Startup list.



Thanks for your support, don't forget to vote.

Friday, January 9, 2009

C# How to: Retreive the logged on users email from Active Directory

Below is a quick example on how to display information from a user's Active Directory profile into a web page. This example displays the AD users email address.

1. If you're using asp.net create a class file ADInfo.cs in your App_Code folder and insert the below code.

//---------ADInfo.cs--------------------------------
using System.DirectoryServices;

public class ADInfo
{

private DirectoryEntry GetDirectoryObject()
{
DirectoryEntry oDE;
oDE = new DirectoryEntry("LDAP://server/dc=w3portals,dc=com", @"W3\" + "adminuser", "password", AuthenticationTypes.Secure);
return oDE;
}

public DirectoryEntry GetUser(string UserName)
{
DirectoryEntry de = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;

deSearch.Filter = "(&(objectClass=user)(SAMAccountName=" + UserName + "))";
deSearch.SearchScope = SearchScope.Subtree;
SearchResult results = deSearch.FindOne();

if (!(results == null))
{
de = new DirectoryEntry(results.Path, "adminuser", "password", AuthenticationTypes.Secure);
return de;
}
else
{
return null;
}
}
//-----------------------------------------

2. Create a label on your aspx page called 'lblEmail'
3. In the codefile of your aspx page copy this code.


//------Default.aspx.cs---------

protected void Page_Load(object sender, EventArgs e)
{
string[] FullUserName = User.Identity.Name.ToString().Split('\\');
ADInfo adi = new ADInfo();
DirectoryEntry dirEntry = adi.GetUser(FullUserName[1].ToString());
lblEmail.Text = dirEntry.Properties["mail"].Value.ToString();
}

//----------------------------

Also, I plan to list other useful Active Directory user properties in my next post. Hope this is useful.

Friday, January 2, 2009

Start your own Hedge Fund in 5 steps for around $400

There's a lot of turn-key hedge fund solutions out there that will guide you through the process of starting a hedge fund. However, it's surprsingly easy to start one on your own and on the cheap... from the legal\regulatory perspective that is.

It really only comes down to accomplishing 2 things, creating an Limited Liability business entity and then becoming a Registered Investment Advisor (RIA). For all the steps to creating a startup company, refer to my previous post: Steps to get a Startup going (cost: ~$200)
After you have carefully gone through that process, you now have to simply go through the steps of becoming an RIA.

Step 1: Prepare for the Series 65 regulatory exam. This is a 140 question multiple choice exam which you just need to score a 69 on. Read through the Investment Advisors Act 0f 1940 and buy a book on the series 65 exam to prepare yourself. (Cost: ~$20)

Step 2: Take the exam by filling out the Form U10 and send in your check to FINRA (Cost: $135.) (Which is conveniently located at 7th & Market Sts in Phila. PA)

Step 3: Register your RIA with the Investment Adviser Registration Depository (IARD). Find instructions on www.IARD.com (Cost: $0)

Step 4: Register your new RIA firm with the Financial Industry Regulatory Authority (FINRA) by filling out the 28 page Form U-4. (Cost: $30)

Step 5: Register your "offering" with the SEC under Rule 506 of Regulation D of the Securities Act of 1933. You need to do this to get a CIK number from the SEC and file Form D with the SEC and with each state in which you plan to offer or sell interests. (Cost: $0)

I'm sure this sounds easier than it really is, but at least this gives a perspective on working through the red tape, and illustrates how simple it is to actually set up one of the most lucrative business models in the world. God Bless America!

Also, if you need any help with your corporate identity, web design, e-marketing, etc., please visit www.W3Portals.com

Lastly, after you've done all this, now comes the hard part...selling your fund to investors.
Start hedging your bets!!

Thursday, December 18, 2008

Enabling SSL on your asp.net website

I would explain how do this in my own manner, but Dan Petri does a great job explaining How to setup SSL on IIS for your website

I would only take it a step forward with instructions on obtaining an SSL certificate. And for that, you can just go to Godaddy.com They have, by far the cheapest SSL certs I've ever seen.