Tuesday, August 12, 2014

How to add TreeViewItem dynamically in TreeView control in WPF?

How to add TreeViewItem dynamically in TreeView control in WPF. Here is the coding example given below to add TreeViewItem in TreeView control.


public TreeViewItem CreateTreeViewItem(string nodeName, string headerText, string frontImagePath, string tailImagePath, bool isCheckBoxRequired)
        {
            TreeViewItem treeViewItem = new TreeViewItem();
            try
            {
                StackPanel stackPanel = new StackPanel();
                Label lblHeaderText = new Label();
                Image imgFrontIcon, imgTailIcon;
                imgFrontIcon = new Image(); imgTailIcon = new Image();

                stackPanel.Orientation = Orientation.Horizontal;
                if (isCheckBoxRequired)
                {
                    CheckBox chkbox = new CheckBox();
                    chkbox.Name = IDPrefixForControls.Chk_.ToString() + nodeName;
                    chkbox.HorizontalAlignment = HorizontalAlignment.Center;
                    chkbox.VerticalAlignment = VerticalAlignment.Center;
                    stackPanel.Children.Add(chkbox);
                }
                if (frontImagePath != null && frontImagePath != string.Empty)
                {
                    Uri uri = new Uri(ConstantVariables.UriString + frontImagePath);
                    BitmapImage bitMapSource = new BitmapImage();
                    bitMapSource.BeginInit();
                    bitMapSource.UriSource = uri;
                    bitMapSource.EndInit();
                    imgFrontIcon.Source = bitMapSource;
                }
                if (tailImagePath != null && tailImagePath != string.Empty)
                {
                    Uri uri = new Uri(ConstantVariables.UriString + tailImagePath);
                    BitmapImage bitMapSource = new BitmapImage();
                    bitMapSource.BeginInit();
                    bitMapSource.UriSource = uri;
                    bitMapSource.EndInit();
                    imgTailIcon.Source = bitMapSource;
                }
                lblHeaderText.Content = headerText;
                stackPanel.Children.Add(imgFrontIcon);
                stackPanel.Children.Add(lblHeaderText);
                stackPanel.Children.Add(imgTailIcon);
                nodeName = nodeName.Replace("-", "_").Replace(" ", "_");
                treeViewItem.Name = nodeName;
                treeViewItem.Header = stackPanel;
            }
            catch (Exception ex)
            { LogExceptionDetails(ex); }
            return treeViewItem;
        }

Add Image column in Datagrid control dynamically in WPF

Here is the code example given to add Image column in Datagrid control dynamically at run time in WPF.

public void AddColumnsToDataGrid(DataGrid dataGrid, DataGridColumnType columnType, string headerText, string bindingName, string imagePath,
           )
        {
FrameworkElementFactory factoryElementStackPanelImages = AddMultipleImagesIntoOneColumn(imagePath);
                            DataTemplate dataTemplate = new DataTemplate();
                            dataTemplate.VisualTree = factoryElementStackPanelImages;

                            DataGridTemplateColumn dgTemplateColumn = new DataGridTemplateColumn();
                            dgTemplateColumn.Header = headerText;
                            dgTemplateColumn.CellTemplate = dataTemplate;
                            dgTemplateColumn.CellStyle = styleDataGridCell;
                            dataGrid.Columns.Add(dgTemplateColumn);
}

private FrameworkElementFactory AddMultipleImagesIntoOneColumn(string imagesSourcePath)
        {
            FrameworkElementFactory factoryElementStackPanel = new FrameworkElementFactory(typeof(StackPanel));
            try
            {
                string imagePath, imageName;
                factoryElementStackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
                FrameworkElementFactory factoryImage;
                if (imagesSourcePath.Contains(ConstantVariables.CharacterValueHash))
                {
                    string[] arrImageSource = imagesSourcePath.Split(Convert.ToChar(ConstantVariables.CharacterValueHash));
                    foreach (string imgSource in arrImageSource)
                    {
                        if (imgSource.Contains(ConstantVariables.CharacterValueDollar))
                        {
                            string[] arrImagePathNName = imgSource.Split(Convert.ToChar(ConstantVariables.CharacterValueDollar));
                            imagePath = arrImagePathNName[0];
                            imageName = arrImagePathNName[1];
                        }
                        else
                        {
                            imagePath = imgSource;
                            imageName = string.Empty;
                        }
                        Uri uri = new Uri(ConstantVariables.UriString + imagePath);
                        BitmapImage bitMapSource = new BitmapImage();
                        bitMapSource.BeginInit();
                        bitMapSource.UriSource = uri;
                        bitMapSource.EndInit();
                        factoryImage = new FrameworkElementFactory(typeof(Image));
                        factoryImage.SetValue(Image.SourceProperty, bitMapSource);
                        factoryImage.SetValue(Image.WidthProperty, 15d);
                        factoryImage.SetValue(Image.HeightProperty, 15d);
                        factoryImage.SetValue(Image.MarginProperty, new Thickness(1));
                        if (!imageName.Equals(string.Empty))
                        {
                            factoryImage.SetValue(Image.NameProperty, imageName);
                            factoryImage.SetValue(Image.ToolTipProperty, imageName);
                        }
                        factoryElementStackPanel.AppendChild(factoryImage);
                        ImageColumnElement.Add(factoryImage);
                    }
                }
                else
                {
                    if (imagesSourcePath.Contains(ConstantVariables.CharacterValueDollar))
                    {
                        string[] arrImagePathNName = imagesSourcePath.Split(Convert.ToChar(ConstantVariables.CharacterValueDollar));
                        imagePath = arrImagePathNName[0];
                        imageName = arrImagePathNName[1];
                    }
                    else
                    {
                        imagePath = imagesSourcePath;
                        imageName = string.Empty;
                    }
                    Uri uri = new Uri(ConstantVariables.UriString + imagePath);
                    BitmapImage bitMapSource = new BitmapImage();
                    bitMapSource.BeginInit();
                    bitMapSource.UriSource = uri;
                    bitMapSource.EndInit();
                    factoryImage = new FrameworkElementFactory(typeof(Image));
                    factoryImage.SetValue(Image.SourceProperty, bitMapSource);
                    factoryImage.SetValue(Image.WidthProperty, 15d);
                    factoryImage.SetValue(Image.HeightProperty, 15d);
                    factoryImage.SetValue(Image.MarginProperty, new Thickness(1));

                    if (!imageName.Equals(string.Empty))
                    {
                        factoryImage.SetValue(Image.NameProperty, imageName);
                        factoryImage.SetValue(Image.ToolTipProperty, imageName);
                    }
                    factoryElementStackPanel.AppendChild(factoryImage);
                    ImageColumnElement.Add(factoryImage);
                }
            }
            catch (Exception ex)
            { LogExceptionDetails(ex); }
            return factoryElementStackPanel;
        }


Adding of Checkbox Column in Datagrid control in WPF

Some times we need to add some controls in a container at run time. Here is the coding logic given to add CheckBox column in Datagrid control dynamically at run time. This code logic is in context with WPF. for winforms the some classes may differ.

Example :

DataGridTemplateColumn dgTemplateColumn = new DataGridTemplateColumn();
                            
                            dgTemplateColumn.Header = headerText;

                            FrameworkElementFactory factoryElementCheckBox = new FrameworkElementFactory(typeof(CheckBox));
                            factoryElementCheckBox.SetBinding(CheckBox.IsCheckedProperty, new System.Windows.Data.Binding(bindingName));
                            factoryElementCheckBox.SetValue(CheckBox.NameProperty, bindingName);
                            factoryElementCheckBox.SetValue(CheckBox.HorizontalAlignmentProperty, HorizontalAlignment.Left);
                            factoryElementCheckBox.SetValue(CheckBox.VerticalAlignmentProperty, VerticalAlignment.Center);

                            CheckBoxColumnElement.Add(factoryElementCheckBox);

                            DataTemplate dataTemplate = new DataTemplate();
                            dataTemplate.VisualTree = factoryElementCheckBox;
                            dgTemplateColumn.CellTemplate = dataTemplate;
                            dgTemplateColumn.IsReadOnly = isReadOnly;
                            dataGrid.Columns.Add(dgTemplateColumn);
                            

Wednesday, July 30, 2014

Why to use an Interface?

While doing object oriented programming we generally make the classes and provide the functionality in it to give to the outside world.

That class may contain some private members and methods and some public members, properties and methods to use the functionality. While accessing the class members and methods we create object of the class and initialize it to call the methods.

This is the very basic development approach. We generally tend to ignore the usage and importance of Interface. An interface can provide us the flexibility of better utilization of memory and structure declaration for the members of the class. Also at the same time we can better use the concept of object oriented programming.

By use of an interface to implement over the class we can achieve the followings
è Encapsulation
è Polymorphism
è Better usage of memory
Here is the list of objects which are available to outside world by using of an interface
è Public properties
è Public methods
è Events
è Indexers
For example :

Public interface IMyFunctions
{
public string inputValue{get;set;}
     Void DoSomething();
}

Class MyFunctions : IMyFunctions
{
public string inputValue{get;set;}
     public Void DoSomething()
{ // provide your logic here }

}

Class OutputClass
{
IMyFunctions myFunctions = new MyFunctions();
myFunctions.inputValue = “TestData”;
muFunctions.DoSomething();
}


Since C#.Net does not support multiple inheritances of the classes, so somehow by using implementing multiple interfaces on a single class we can achieve the same.

What is Collection in .Net?

Collection classes are the specialized classes for data storage and retrieval.

Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index etc. These classes create collection of objects of the Object class, which is the base class for all data types in C#.


Most of the times we get a requirement to store the multiple data. This can be done by using the Array which supports the data storage at different indexes created. An Array is a collection of multiple data at different indexes. However this is a form of strongly typed object, we can store information in array of same type of object. 

On the other hand Collections gives us the flexibility to store the data of different type of objects in it.

Namespace for collections: System.Collection
Various types of collections and their usage.


Class
Usage
ArrayList
It represents an ordered list of objects which can be retrieved by indexes.
An Arraylist is alternative to an Array. However unlike array you can Add, Remove the items from the list and can be retrieved by indexes. An ArrayList is not bound to any specific length
Hashtable
This collection can store the objects with a key assigned to it. Any data storage is in the form of key-value pair in Hashtable and the stored object can be retrieved by the key which is assigned to it.
Stack
It represents a last-in and first out collection of object. When the item is added to stack, it is called “pushing” the item and when it get removed, it is called as “popping” the item.
Queue
It represents a first-in and first out collection of object. When the item is added to stack, it is called “enqueue” the item and when it get removed, it is called as “dequeue” the item.
SortedList
A SortedList is a combination of an array and a Hashtable.
It uses a key as well as an index to access the items in a list. If you access the items using an index, it is an Arraylist and if you access the items using a key, it is a Hashtable. The collection of items is always sorted by the key value.

How to split the string in SQL server

Sometimes there is a requirement when we want to get the individual words from a complete string. The question comes how can we do that in database level only so that our application will get the desired result from the database itself.

Below is the desired output in the split word format


To achieve this we have to use the "substring" method/function to split the string. Here we are creating an user defined function which will return the result in the split format.

Here is the logic for the function.

CREATE FUNCTION [dbo].[SplitData]
(
@RowData varchar(8000),
@SplitOn nvarchar(5)
)  
RETURNS @RtnValue table 
(
Id int identity(1,1),
Data nvarchar(100)

AS  
BEGIN 
Declare @Cnt int
Set @Cnt = 1

While (Charindex(@SplitOn,@RowData)>0)
Begin
Insert Into @RtnValue (data)
Select 
Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
Set @Cnt = @Cnt + 1
End

Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@RowData))

Return
END


Tuesday, July 22, 2014

What is an Interface?

An Interface is a container which contains the signature of the methods within. This means it can have only the declarations of the method without their definition. An interface needs to implement on the Class and in the implementation process the definition has to be provided for all the methods declared inside the interface.

As C# does not support multiple inheritance of classes, but at the same time we can implement as many interface as required on a class. So in that manner we can get the different functionalities inside a class by implementing multiple interface.

What all an interface can contain?

    è Methods
    è Properties
    è Events
    è Indexers

By default the access modifier is “public” for all of its children. An interface does not allow private access modifier to any of its child.

Example:

//Interface declaration
public interface IDemo
{
     public string SumValue {get; set;}   //Property declaration
public void Add(int num1, int num2); //Method declaration
}

//Interface implementation on class Demo
class Demo : IDemo
{
public string SumValue {get; set;}
public void Add(int num1, int num2)  //Method Implementation
{
SumValue = num1+num2;
}
}

Allow single quotation in a string for Insert or update query in C#

While inserting the data into database from application sometimes we encounter with the error of single quotation exists in the input data. Single quotation is the special character used to hold the string value in database (SQL). Here is the simple technique by which we can insert the details with single quotation into the input data.

Code language C#.

public string AllowSingleQouteToInsertOrUpdate(string inputValue)
        {
            string outputValue = string.Empty;
            if ((inputValue.IndexOf("'", 0) > 0) || (inputValue.IndexOf("'", 0) == 0))
            { outputValue = inputValue.Replace("'", "''"); }
            else
            { outputValue = inputValue; }
            return outputValue;
        }

Friday, July 18, 2014

Download Excel file from ASP.Net in VB.Net

As a requirement to have result data in xls file from ASP.Net application for some reporting purpose, Here is the simple process to get the same output.

The sample code is provided below to download the records in the excel file in the same table format i.e data in each cell of the sheet. We assume to have huge amount of data in DataTable object and in same table format it is required to download in xls sheet.
To create a different cell of data here we have used the Html Table and its Row and Column concept.

Here is the code snippet in VB.Net language.

Protected Sub GenerateXls(ByVal fileName As String, ByVal dtData As DataTable)
        Try
            HttpContext.Current.Response.Clear()
            HttpContext.Current.Response.ContentType = "application/ms-excel"
            HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName + "")
            HttpContext.Current.Response.Flush()
            Dim colCount, rowCount As Integer
            HttpContext.Current.Response.Write("<Table>")
            HttpContext.Current.Response.Write("<TR>")

            For colCount = 0 To dtData.Columns.Count - 1
                HttpContext.Current.Response.Write("<TD>")
                HttpContext.Current.Response.Write(dtData.Columns(colCount).ColumnName.ToString())
                HttpContext.Current.Response.Write("</TD>")
            Next
            HttpContext.Current.Response.Write("</TR>")

            For rowCount = 0 To dtData.Rows.Count - 1
                HttpContext.Current.Response.Write("<TR>")
                For colCount = 0 To dtData.Columns.Count - 1
                    HttpContext.Current.Response.Write("<TD>")
                    HttpContext.Current.Response.Write(dtData.Rows(rowCount)(colCount).ToString())
                    HttpContext.Current.Response.Write("</TD>")
                Next
                HttpContext.Current.Response.Write("</TR>")
            Next
            HttpContext.Current.Response.Write("</Table>")
            HttpContext.Current.Response.End()

        Catch ex As Exception
        End Try        
    End Sub

Thursday, July 17, 2014

Working with column index number in SQL query

Sometimes we have the question in our mind that how to get data from SQL table in sorted order by retriving by column index instead of column name. Generally this can be done when we use nested query and table name is given temporarily.

we can use column index in the select query to get the output. This can be done only for sorting the data from any table.

For example we have an employee table with this records








To sort the data in descending order by column name "EmpCode" we have the query

Select * from Emp order by EmpCode desc

To sort the data in descending order by column index of "EmpCode" we have the query

Select * from Emp order by 2 desc

result from both the queries given above is





Motivational qoutes

पूरे विश्वास के साथ अपने सपनों की तरफ बढ़ें। वही ज़िन्दगी जियें जिसकी कल्पना आपने की है।