Posts Tagged DirectCast

Class to Simplify and Minimize Code for Stored Procedures and TSQL

First of all if you are using TSQL in your code you really need to get in a another line of work. It isn’t scalable, difficult to maintain and is generally a bad practice. But I know some of you still do it so I did include it. This class will allow you to in a few lines of code do your select, update, insert or delete statements in a very few lines of code. All that is required of the developer is to list the values in order (if you are using stored procedures) that are required. Also included is how to declare a new instance of a sqlparametercollection – which you aren’t suppose to be able to do. I ended up not needing it but included it just in case someone needs to do that someday. Also if you are using a strongly typed dataset there is a method included of how to do that. After the code is example of usage. Have a great day!

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;

using System.IO;

using System.Data.SqlClient;

public class clsData
{

    public SqlConnection sqlconn = new SqlConnection();
    public string Error_Message;
    public List<SqlParameter> ParamList = new List<SqlParameter>();
    public ArrayList ParamValues = new ArrayList();

    public int SQLExecuteNonQueryValue;
    public clsData()
   

    public enum SQLAction
    {
        SelectAction,
        UpdateInsertDeleteAction
    }

    public virtual DataTable DataAction(clsData.SQLAction Action, DataTable dt, string cmdtext, string ParamValues = “”)
    {
        SQLExecuteNonQueryValue = -1;
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = cmdtext;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = sqlconn;
        this.GetParameterList(cmdtext);
        if (!string.IsNullOrEmpty(Error_Message)) {
            return null;
        }
        if (!string.IsNullOrEmpty(ParamValues)) {
            this.ParseSQLParameterValues(ParamValues);
            for (i = 0; i <= this.ParamList.Count – 1; i++) {
                cmd.Parameters.AddWithValue(this.ParamList[i].ToString(), this.ParamValues[i].ToString());
            }
        }
        //Debug.WriteLine(cmd.CommandText)
        try {
            cmd.Connection.Open();
            switch (Action) {
                case SQLAction.SelectAction:
                    dt.Load(cmd.ExecuteReader());
                    break;
                case SQLAction.UpdateInsertDeleteAction:
                    //Check this value to make sure everything went ok
                    SQLExecuteNonQueryValue = cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                    return null;
            }
            cmd.Connection.Close();

        } catch (Exception ex) {
            Error_Message = “There was a problem with ” + cmdtext + “. “;
            return null;
        }

        //removing duplicate table from dataset
        for (i = 0; i <= ds_Copy.Tables.Count – 1; i++) {
            if (ds_Copy.Tables(i).TableName == dt.TableName) {
                ds_Copy.Tables(i).Clear();
                ds_Copy.Tables(i).Columns.Clear();
            }
        }

        //placing datatable in the dataset
        ds_Copy.Merge(dt, false, MissingSchemaAction.Add);
        Error_Message = “”;
        return dt;
    }

    public DataTable DataActionTSQL(clsData.SQLAction Action, DataTable dt, string sqlstring)
    {
        SQLExecuteNonQueryValue = -1;
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = sqlstring;
        cmd.Connection = sqlconn;
        try {
            cmd.Connection.Open();
            switch (Action) {
                case SQLAction.SelectAction:
                    dt.Load(cmd.ExecuteReader());
                    break;
                case SQLAction.UpdateInsertDeleteAction:
                    //Check this value to make sure everything went ok
                    SQLExecuteNonQueryValue = cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                    return null;
            }
            cmd.Connection.Close();

        } catch (Exception ex) {
            Error_Message = “There was a problem with ” + sqlstring + “. “;
            return null;
        }
        //removing duplicate table from dataset
        for (i = 0; i <= ds_Copy.Tables.Count – 1; i++) {
            if (ds_Copy.Tables(i).TableName == dt.TableName) {
                ds_Copy.Tables(i).Clear();
                ds_Copy.Tables(i).Columns.Clear();
            }
        }
        //placing datatable in the dataset
        ds_Copy.Merge(dt, false, MissingSchemaAction.Add);
        Error_Message = “”;
        return dt;
    }

    private List<SqlParameter> GetParameterList(string ProcName)
    {
        //Get the parameters for the selected stored procedure
        List<SqlParameter> inputParamList = new List<SqlParameter>();
        ParamList.Clear();

        using (SqlConnection cn = new SqlConnection()) {
            DispatcherTool.My.MySettings Settings = new DispatcherTool.My.MySettings();
            cn.ConnectionString = Settings.SRAConnectionString;
            SqlCommand myCommand = new SqlCommand();
            myCommand.Connection = cn;
            myCommand.CommandText = ProcName;
            myCommand.CommandType = System.Data.CommandType.StoredProcedure;
            try {
                cn.Open();
                SqlCommandBuilder.DeriveParameters(myCommand);
                cn.Close();
            } catch (Exception ex) {
                Error_Message = “There was a problem with the connection to the database.”;
                return null;
            }

            //Dim sqlparams As SqlParameterCollection = DirectCast(GetType(SqlParameterCollection).GetConstructor(BindingFlags.NonPublic Or BindingFlags.Instance, Nothing, Type.EmptyTypes, Nothing).Invoke(Nothing), SqlParameterCollection)

            foreach (SqlParameter param in myCommand.Parameters) {
                if (param.Direction == System.Data.ParameterDirection.Input || param.Direction == System.Data.ParameterDirection.InputOutput) {
                    //sqlparams.Add(param.ParameterName & ” – ” & param.SqlDbType.ToString())
                    //Debug.WriteLine(param.ParameterName & ” – ” & param.SqlDbType.ToString())
                    inputParamList.Add(param);
                    //Else
                    // sqlparams.Add(param.ParameterName & ” – ” & param.SqlDbType)
                    //Debug.WriteLine(param.ParameterName & ” -2 ” & param.SqlDbType)
                }
            }
        }
        this.ParamList = inputParamList;
        Error_Message = “”;
        return this.ParamList;
    }

    public void ParseSQLParameterValues(string ValueString)
    {
        ParamValues.Clear();
        string[] parts = ValueString.Split(new char[] { ‘,’ });
        string part = null;
        foreach (string part_loopVariable in parts) {
            part = part_loopVariable;
            ParamValues.Add(part);
        }
    }

    //’Public Shared Function ConvertToTypedDataTable(Of T As {Data.DataTable, New})(ByVal dtBase As Data.DataTable) As T
    //’    Dim dtTyped As New T
    //’    dtTyped.Merge(dtBase)
    //’    Return dtTyped
    //’End Function

}

And then it’s use…..

private void Button1_Click(System.Object sender, System.EventArgs e)
{
    Strongly_Typed_DataSet.usp_Your_Stored_Procedure dt = new Strongly_Typed_DataSet.usp_Your_Stored_Procedure();

    DataGridView1.DataSource = cn.DataAction(clsData.SQLAction.SelectAction, dt, ds.usp_Get_PrinterName_for_PickList_Printing.ToString, “Tubing”);

    //DataGridView1.DataSource = cn.DataActionTSQL(clsData.SQLAction.SelectAction, dt, “SELECT *FROM Your_Table”)

}


Join me on Facebook

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment

Save Control Settings with vb.net

What’s this you say? A new blog entry? If you haven’t completely deserted me …. well I don’t know what’s wrong with you! Smile jk. But anyway here is the latest. I am working for a national hotel chain in Memphis, TN. I got married, moved to New Jersey and am we are now separated. Yes it is a long story and no I am not going to bore you with the details!

Before I go any further, I actually write very little in vb.net anymore. The language is awesome. It’s just that very few people want that skill set now and if you want to be employed you need to write in C#. It’s just the way it is. However in this particular task, I found vb.net to be the tool of choice here. The reason is there is no C# equivalent to VB’s implicit ‘once only’ variable initialization within loops. I am not sure why that is but that is the case here. This code snippet is ideal when you want to allow the end user to dictate how a given control is to look or operate. Yes in my example I am using an Infragistic control so if you copy and paste this do NOT email me complaining about broken references please! I hope you find the code useful and thank you for showing up! Smile

Public Shared Sub SaveControl(ByVal StateName As String, ByVal ParamArray Controls As Control())
        Dim section As String = “”
        Dim appName As String = StringType.FromObject(Interaction.IIf((StringType.StrCmp(Application.ProductName, “”, False) = 0), “VSDesigner”, Application.ProductName))
        Dim control As Control
        For Each control In Controls
            If (Not control.FindForm Is Nothing) Then
                Dim form As Form
                If (StringType.StrCmp((StateName & “”), “”, False) > 0) Then
                    section = String.Concat(New String() { control.FindForm.Name, “.”, control.Name, “.”, StateName })
                Else
                    section = (control.FindForm.Name & “.” & control.Name)
                End If
                If TypeOf control Is Form Then
                    form = DirectCast(control, Form)
                    If (form.WindowState = FormWindowState.Normal) Then
                        Interaction.SaveSetting(appName, form.Name, “Top”, StringType.FromInteger(form.Top))
                        Interaction.SaveSetting(appName, form.Name, “Left”, StringType.FromInteger(form.Left))
                        Interaction.SaveSetting(appName, form.Name, “Height”, StringType.FromInteger(form.Height))
                        Interaction.SaveSetting(appName, form.Name, “Width”, StringType.FromInteger(form.Width))
                    End If
                    Interaction.SaveSetting(appName, form.Name, “WindowState”, StringType.FromInteger(CInt(form.WindowState)))
                ElseIf TypeOf control Is Splitter Then
                    form = control.FindForm
                    Dim splitter As Splitter = DirectCast(control, Splitter)
                    Interaction.SaveSetting(appName, section, “SplitPosition”, StringType.FromInteger(splitter.SplitPosition))
                ElseIf TypeOf control Is FilterListView Then
                    Dim view2 As FilterListView = DirectCast(control, FilterListView)
                    form = view2.FindForm
                    Interaction.SaveSetting(appName, section, “View”, StringType.FromInteger(CInt(view2.ListView.View)))
                    Dim header As ColumnHeader
                    For Each header In view2.ListView.Columns
                        Interaction.SaveSetting(appName, section, (“Column” & StringType.FromInteger(header.Index)), StringType.FromInteger(header.Width))
                    Next
                    Dim filter As FilterListViewFilter
                    For Each filter In view2.Filters
                        Dim tag As UserProfileSetting
                        If (filter.Tag Is Nothing) Then
                            tag = Context.User.Settings.NewItem
                            Dim setting2 As UserProfileSetting = tag
                            setting2.Type = UserProfileSettingTypeEnum.FilterListView
                            setting2.Name = section
                            setting2.Description = filter.Name
                            setting2.Value = filter.Filter
                            setting2 = Nothing
                            filter.Tag = tag
                        ElseIf filter.Deleted Then
                            tag = DirectCast(filter.Tag, UserProfileSetting)
                            If Context.User.Settings.Contains(tag) Then
                                Context.User.Settings.Remove(tag)
                            End If
                        Else
                            tag = DirectCast(filter.Tag, UserProfileSetting)
                            tag.Value = filter.Filter
                        End If
                    Next
                    Context.User.Settings.Save
                ElseIf (TypeOf control Is ListView Or TypeOf control Is SortListView) Then
                    form = control.FindForm
                    Dim view As ListView = DirectCast(control, ListView)
                    Interaction.SaveSetting(appName, section, “View”, StringType.FromInteger(CInt(view.View)))
                    Dim header As ColumnHeader
                    For Each header In view.Columns
                        Interaction.SaveSetting(appName, section, (“Column” & StringType.FromInteger(header.Index)), StringType.FromInteger(header.Width))
                    Next
                ElseIf TypeOf control Is TabControl Then
                    form = control.FindForm
                    Dim control2 As TabControl = DirectCast(control, TabControl)
                    Interaction.SaveSetting(appName, section, “View”, StringType.FromInteger(control2.SelectedIndex))
                ElseIf TypeOf control Is TextBox Then
                    form = control.FindForm
                    Dim box3 As TextBox = DirectCast(control, TextBox)
                    Interaction.SaveSetting(appName, section, “Text”, box3.Text)
                ElseIf TypeOf control Is ComboBox Then
                    form = control.FindForm
                    Dim box As ComboBox = DirectCast(control, ComboBox)
                    If (box.DropDownStyle = ComboBoxStyle.DropDown) Then
                        Interaction.SaveSetting(appName, section, “Text”, box.Text)
                    End If
                    Interaction.SaveSetting(appName, section, “SelectedIndex”, StringType.FromInteger(box.SelectedIndex))
                ElseIf TypeOf control Is CheckBox Then
                    form = control.FindForm
                    Dim box2 As CheckBox = DirectCast(control, CheckBox)
                    Interaction.SaveSetting(appName, section, “Checked”, StringType.FromBoolean(box2.Checked))
                ElseIf TypeOf control Is DataGrid Then
                    form = control.FindForm
                    Dim grid As DataGrid = DirectCast(control, DataGrid)
                    Dim num As Integer = 0
                    Dim style As DataGridTableStyle
                    For Each style In grid.TableStyles
                        Dim num2 As Integer = 0
                        Dim style2 As DataGridColumnStyle
                        For Each style2 In style.GridColumnStyles
                            Interaction.SaveSetting(appName, (section & StringType.FromInteger(num) & “.” & StringType.FromInteger(num2)), “Width”, StringType.FromInteger(style2.Width))
                            num2 += 1
                        Next
                        num += 1
                    Next
                ElseIf TypeOf control Is KeyedDropDown Then
                    form = control.FindForm
                    Dim down As KeyedDropDown = DirectCast(control, KeyedDropDown)
                    If (down.DropDownStyle = ComboBoxStyle.DropDown) Then
                        Interaction.SaveSetting(appName, section, “Text”, down.Text)
                    End If
                    Interaction.SaveSetting(appName, section, “SelectedIndex”, StringType.FromInteger(down.SelectedIndex))
                ElseIf TypeOf control Is UltraGrid Then
                    Dim grid2 As UltraGrid = DirectCast(control, UltraGrid)
                    Dim enumerator2 As BandEnumerator = grid2.DisplayLayout.Bands.GetEnumerator
                    Do While enumerator2.MoveNext
                        Dim current As UltraGridBand = enumerator2.Current
                        Dim enumerator As ColumnEnumerator = current.Columns.GetEnumerator
                        Do While enumerator.MoveNext
                            Dim column As UltraGridColumn = enumerator.Current
                            Interaction.SaveSetting(appName, section, (“Hidden.” & StringType.FromInteger(current.Index) & “.” & column.Key), StringType.FromBoolean(column.Hidden))
                            Interaction.SaveSetting(appName, section, (“Width.” & StringType.FromInteger(current.Index) & “.” & column.Key), StringType.FromInteger(column.Width))
                        Loop
                    Loop
                End If
            End If
        Next
    End Sub

Facebook

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment