Search This Blog

Thursday, December 30, 2010

How to create a list to store 2 variables

Define variables:

        string _tag;
        string _name;

Create list:

        //set list to store tag & name of menu item
        public static List<Tuple<string, string>> menuStructure = new List<Tuple<string, string>>();

Save variables to list:

        //save menu structure for future use in permissions granting program
        Session.menuStructure.Add(new Tuple<string, string>(_tag, _name));

Sort list by Name:

        //sort menu structure by name
        Session.menuStructure.Sort((a, b) => a.Item1.CompareTo(b.Item1));

Wednesday, December 29, 2010

Getting Started with iTextSharp

http://www.mikesdotnetting.com/Article/80/Create-PDFs-in-ASP.NET-getting-started-with-iTextSharp

Add Nodes to TreeView

using System;
using System.Drawing;
using System.Windows.Forms;
   
class SimpleTreeView: Form
{
     public static void Main()
     {
          Application.Run(new SimpleTreeView());
     }
     public SimpleTreeView()
     {
          Text = "Simple Tree View";
   
          TreeView tree = new TreeView();
          tree.Parent = this;
          tree.Dock = DockStyle.Fill;
   
          tree.Nodes.Add("Animal");
          tree.Nodes[0].Nodes.Add("A");
          tree.Nodes[0].Nodes[0].Nodes.Add("A1");
          tree.Nodes[0].Nodes[0].Nodes.Add("A2");
          tree.Nodes[0].Nodes[0].Nodes.Add("A3");
          tree.Nodes[0].Nodes.Add("B");
          tree.Nodes[0].Nodes[1].Nodes.Add("B1");
          tree.Nodes[0].Nodes[1].Nodes.Add("B2");
          tree.Nodes[0].Nodes.Add("C");
          tree.Nodes[0].Nodes[2].Nodes.Add("C1");
          tree.Nodes[0].Nodes[2].Nodes.Add("C2");
          tree.Nodes[0].Nodes[2].Nodes.Add("C3");
          tree.Nodes.Add("D");
          tree.Nodes[1].Nodes.Add("D1");
          tree.Nodes[1].Nodes.Add("D2");
          tree.Nodes[1].Nodes.Add("D3");
          tree.Nodes.Add("E");
          tree.Nodes[2].Nodes.Add("E1");
          tree.Nodes[2].Nodes.Add("E2");
          tree.Nodes[2].Nodes.Add("E3");
     }
}

Wednesday, December 22, 2010

SQL Queries

Level Separator



Sample of Queries

//SELECT LastMaintainedBy, EvidenceOfFundingRequired, DateStamp FROM BusinessUnit WHERE ID = 5
BusinessUnitQuery q = new q.LevelSeparator = LevelSeparator.AND; //If you want to change it to q.AddFilter(BusinessUnitQuery.ID, QueryComparison.Equals, 5,
q.AddFilter(BusinessUnitQuery.LastMaintainedBy, QueryComparison.Equals, "someUserID", q.AddFilter(BusinessUnitQuery.PaymentSummaryYTD, QueryComparison.Greater, 100, DataTable dt = this.dal.GetDataTable(q);

Not adding any columns selects all (select * from BusinessUnit WHERE ID = 5) 
            BusinessUnitQuery q = new BusinessUnitQuery();
            q.AddFilter(BusinessUnitQuery.ID, QueryComparison.Equals, 5);
            DataTable dt = this.dal.GetDataTable(q);
Quicker
            BusinessUnitQuery q = new BusinessUnitQuery(BusinessUnitQuery.ID, QueryComparison.Equals, 5);
            DataTable dt = this.dal.GetDataTable(q);

multiple filters (WHERE'S)

            //SELECT * FROM BusinessUnit
            //WHERE (ID=5 AND LastMaintainedBy='someUserID') OR (PaymentSummaryYTD > 100)
            BusinessUnitQuery q = new BusinessUnitQuery();
            q.AddFilter(BusinessUnitQuery.ID, QueryComparison.Equals, 5, 1);
            q.AddFilter(BusinessUnitQuery.LastMaintainedBy, QueryComparison.Equals, "someUserID", 1);
            q.AddFilter(BusinessUnitQuery.PaymentSummaryYTD, QueryComparison.Greater, 100, 2);
            DataTable dt = this.dal.GetDataTable(q);


Select RevisionNo From BusinessUnit Where ID = 2

            BusinessUnitQuery q = new BusinessUnitQuery();
            int revNo = this.dal.DataGet(q).SingleValue<int>(BusinessUnitQuery.RevisionNo, BusinessUnitQuery.ID, QueryComparison.Equals, 2);

Select Count(*) From BusinessUnit Where ID = 2

            BusinessUnitQuery q = new BusinessUnitQuery();
            bool exists = this.dal.DataGet(q).HasRecords(BusinessUnitQuery.ID, QueryComparison.Equals, 2);

Tuesday, December 21, 2010

Functions

All the string functions available are methods of the System.String object.

You'll also find some are static methods of the String class. EG String.Join()

string x = "Some String;Another One";
string[] array = x.Split(";");

with InStr you have: x.Contains("Another");

replace you have x.Replace("One", "One More");

c# doesn't have direct equivalents to Left or Right, You have to use x.Substring();

nor IsNumeric. But you can do a int.TryParse

        public static int ConvertToInt(string str)
        {
            int i = 0;
            int.TryParse(str, out i);
            return i;
        }

i use a function like this to determine if a string can be parsed as an int. if the function returns 0 then it cannot be parsed.

Although you may need to create a ConvertToDecimal() function as well. Decimal has a TryParse method as well.

FYI one .NET library i didn't discover until later was the System.IO.Path library. Whenever you need to work with filesystem paths this one is your friend.

Tuesday, December 7, 2010

C# Tutorial

http://www.csharp-station.com/Tutorial.aspx

How to Structure a C# Program

The application is split into 3 layers:
  • User Interface
  • Business Logic
  • Data Access
This is an industry standard way of structuring things. the layers are separated as projects.
The User Interface (UI) layer should only contain code that relates to the user interface - how form elements are structured. Its generally just talks to the Business Logic Layer.
The Business Logic (BL) layer contains the smarts of the application. It shouldn't connect to any datastore, strictly, it shouldn't even care where the data is coming from eg, SQLServer, MSAccess, Oracle, Or even XML Files. If it wants data it just talks to the Data Access Layer. 
The Data Access (DL) layer talks to the database- whatever it may be. 
However to begin with at least the lines between these layers will be a little blurred.
I've rewritten the DAL to have non static members so to access them you must instantiate it.
FYI: If a class has a static method (function) or property it can be called like this:
SomeClass.SomeMethod();
However to access the non static methods and properties of a class you will need to instantiate it first.
SomeClass someClass = new SomeClass();
someClass.SomeMethod();
So anyway the startup form is the Dashboard. however the login form is called before it is shown.
When the dal is instantiated it requires a connection string as a parameter to the constructor. 
However it also contains a method to change the connection string if required - which is what we do when selecting a new datasource from the Environment form.
You'll notice I've created a User class in the BLL. The idea here is anything you need to do with a user you use this class.
EG.
User user = new User(dal); //we pass to it an instance of the DAL class.
//There is also an overload for the constructor of this class to specify the userLogin.
User user = new User(dal, "john");
//Specifying a userLogin should then load the properties of the User object from the dal using the Load() method.
//so now we can retrieve properties of the user EG:
txtFirstName.Text =  user.FirstName;
txtLastName.Text = user.LastName;
//Later we need to create other methods for this User class like Save() and Delete();
EG:
user.FirstName = txtFirstName.Text;
user.LastName = txtLastName.Text;
user.Save();
Take a look at the Load() method on the User class it shows how you would interact with the dal.

Saturday, December 4, 2010

Creating Data Access Layer C# (Deborah's link)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace DataAccessLayer
{
    public class DAL
    {
        public static DataTable ExecuteDataTable(string storedProcedureName, params SqlParameter[] arrParam)
        {
            DataTable dt = new DataTable();

            // Open the connection
            using (SqlConnection cnn = new SqlConnection("Data Source=Provider=SQLOLEDB.1; Integrated Security=SSPI; Persist Security Info=False; User ID=EPU; Initial Catalog=EasyPay; Data Source=Home-PC\\SQLEXPRESS"))
            {
                cnn.Open();

                // Define the command
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = cnn;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = storedProcedureName;

                    // Handle the parameters
                    if (arrParam != null)
                    {
                        foreach (SqlParameter param in arrParam)
                            cmd.Parameters.Add(param);
                    }

                    // Define the data adapter and fill the dataset
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(dt);
                    }
                }
            }
            return dt;
        }

        public static int ExecuteNonQuery(string storedProcedureName, params SqlParameter[] arrParam)
            {
            int retVal=0;
            SqlParameter firstOutputParameter = null;

            // Open the connection
            using (SqlConnection cnn = new SqlConnection("Data Source=Provider=SQLOLEDB.1; Integrated Security=SSPI; Persist Security Info=False; User ID=EPU; Initial Catalog=EasyPay; Data Source=Home-PC\\SQLEXPRESS"))
            {
                cnn.Open();

                // Define the command
                using (SqlCommand cmd= new SqlCommand())
                {
                    cmd.Connection = cnn;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = storedProcedureName;

                    // Handle the parameters
                    if (arrParam != null)
                    {
                        foreach (SqlParameter param in arrParam)
                        {
                            cmd.Parameters.Add(param);
                            if (firstOutputParameter == null &&
                                param.Direction==ParameterDirection.Output &&
                                param.SqlDbType == SqlDbType.Int)
                                firstOutputParameter = param;
                        }
                    }

                    // Execute the stored procedure
                    cmd.ExecuteNonQuery();

                    // Return the first output parameter value
                    if (firstOutputParameter != null)
                        retVal = (int)firstOutputParameter.Value;
                }
            }
            return retVal;
            }
        }
    }

Pass value from one form to other form in c#.Net

STEP 1  
private static string _first;
private static string _last;
        public string First
        {
            get
            {
                return _first;
            }            
        }

        public string Last
        {
            get
            {
                return _last;
            }            
        } 
STEP 2 
private void btnSubmit_Click(object sender, EventArgs e)
        {
            //Setting properties
            _first = txtFirst.Text;
            _last = txtLast.Text;

            this.Hide();
            Form2 f2 = new Form2();
            f2.Show();
            f2.Activate();
        }
STEP 3 
Form1 f1 = new Form1();
            if (f1.First!=String.Empty || f1.Last!=String.Empty)
            {
                lblGet.Text = "Welcome "+f1.First + " " + f1.Last + "!";
            }
            else
            {
                lblGet.Text = "Oops! No Input Value Found.";
            }