Showing posts from 2011

TRANSACTION implementation in LINQ

LINQ is become one of most popular. But Based on our business logic we need to Use Transaction in LINQ.
LINQ Transaction is much more smart. You do not need to rollback. If it fail to complete any query it automatically rollback.

To use transaction You have to add a .NET dll name  "System.Transaction" in reference of your application.


Now in your DataAccess Layer you can use like

public void UpdateSaleDetailsTable(ESalesReturn aSalesReturn) { using(System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required)) { UpdateSaleDetailsTableData(aSalesReturn); UpdateSaleTable(aSalesReturn); UpdateCurrentProductTable(aSalesReturn); InsertIntoSalesReturnTable(aSalesReturn); scope.Complete(); } }

WPF ComboBox Last item should be selected

If we want that our comboBox will select the last item, in combobox loading time then you can use

  private void LoadComboBo()
            comboBox1.SelectedIndex = comboBox1.Items.Count - 1;


There is no doubt "LINQ" is much more smart that other. In our development we face complex transaction or logical query for our application. Hare is some common LINQ opration. It is important that your all table should be present in dbml file.  Hare PRODUCT_NAME is the table name, In which i will perform All LINQ operation. Product is the class name which will contain data.  table should contain a Primary Key.


public void SaveNewProductName(Product aProduct) { var newProductName = new PRODUCT_NAME { NAME = aProduct.ProductName }; dataContexObj.PRODUCT_NAMEs.InsertOnSubmit(newProductName); dataContexObj.SubmitChanges(); }


public bool DoesExistProductName(Product aProduct) { return (dataContexObj.PRODUCT_NAMEs.Any(o => o.NAME.Contains(aProduct.ProductName))); }


public void UpdateProductName(Product…

How to use code in blogspot

You can easily use your code spinet in your blog. Follow the link:

Hare it is important You have paste your formatted code on your  Blog in  edit HTML view.


WPF DataGrid Cell Color Change

DataGrid's ROW & CELL color Changing is one of most important part in our development. if you want to change Data grid specific cell Background just like:

use the xaml code for "Remaining Day" column in your Datagrid.

<DataGridTemplateColumn Header="Remaining Day" Width="150"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Border x:Name="brdBroder" VerticalAlignment="Stretch" Margin="1"> <TextBlock Text="{Binding RemainLeave}" Margin="3,1" x:Name="txtTextBlock"/> </Border> <DataTemplate.Triggers> <DataTrigger Binding="{Binding RemainLeave}" Value="0"> <Setter TargetName="brdBroder" Property="Background" Val…

C# LINQ Search between date

The SQL BETWEEN operator we can use in C# code. Before your query you have to use
System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("en-US");  

Consider the Example:
internal List<ECalendarSetup> GetCalenderInfoOnSelectedDate(ECalendarSetup calendarSetup) { ieclHrmDataContext = new IECL_HRMDataContext(); List<ECalendarSetup> calendarSetupsList = new List<ECalendarSetup>(); var query = from j in ieclHrmDataContext.HR_CALENDAR_INFOs where j.CAL_DAY_DATE >= calendarSetup.FromDate && j.CAL_DAY_DATE <= calendarSetup.ToDate select j; foreach (var calendarInfo in query) { ECalendarSetup eCalendarSetup = new ECalendarSetup(); eCalendarSetup.Date = (DateTime) calendarInfo.CAL_DAY_DATE; eCalendarSetup.DayStatus = calendarInfo.CAL_DAY_STATUS; eCalend…

C# string split & LINQ operation

Spliting string in C# is one of the most interesting part. you can also perform your business logic operation on spliting part.
Hare is a list of serial no comes from database, i split the Serial no then just increment id no +1 on maximum serial no, and return to UI.
i also check hare is the serial no is in current year.

internal string GetNewSerialNo() { string refence = ""; DateTime dt = DateTime.Now; List<RFQ> _listAllRef =new List<RFQ>(); foreach (var objrfq in rfqDalObj.GetNewSerialNo()) { string[] splitedRef = (objrfq.SerialNO).Split('-'); if(DateTime.Now.Year.ToString()==splitedRef[1]) { _listAllRef.Add(objrfq); } } List<int> rfqSerials = new List<int>(); if (_listAllRef.Count > 0) { foreach (var obj in _listAllRef) { string[] splitedRef = (obj.SerialNO).Sp…

WPF Common Programming

ListView Binding:

<ListView Height="182" HorizontalAlignment="Left" Name="foodSaleslistView" VerticalAlignment="Top" Width="503" BorderBrush="#00981010" Margin="2,1,0,0"> <ListView.View> <GridView> <GridViewColumn DisplayMemberBinding="{Binding Path=FoodName}" Header="Food name" Width="250" /> <GridViewColumn DisplayMemberBinding="{Binding Path=Qty}" Header="Quantity" Width="100" /> <GridViewColumn DisplayMemberBinding="{Binding Path=TotalPrice}" Header="Total price" Width="150" /> </GridView> </ListView.View> </ListView>
Get Data From ListView:

for (int i = 0; i < headlistView.Items.Count; i++) { EStock anStock = headlistView.Items[i] as EStock; …

Convert TEXT file in to CSV file using Excel

It's really great that you can convert text file in CSV file using Excel. Thn you can save this data in SQL Database. Hare is the link:


WPF 4 Updated Information

There is many new functionality added in WPF 4 Like Visual tree,State Manager,VSM, Touch & manioulation, Graphics & Animation and much more.
 By the following Link You can get idea:


WPF Datagrid highlight border

WPF Datagrid cell {X,Y} coordinate value

Some time we need to find the datagrid selected cell's coordinate value. like

You can easily find our your selected cell value. Please follow this link for more details.


WPF select item from Combobox itemlist with given item

Find items from comboBox & show as selected item.

WPF update other UI control from cyrrent window.

In our application sometimes we need that when we perform any cloud operation the it will take effect to other
UI control. hare is the sample:

private void LoadWMSComboInBuildingUI()
                BuildingSetup obj;
                foreach (Window objWindow in Application.Current.Windows)
                    string[] splitedNamespace = (objWindow.ToString()).Split('.');
                    string aClassNameFromCollection = splitedNamespace[splitedNamespace.Length - 1];
                    if (aClassNameFromCollection == "BuildingSetup")
                        obj = (BuildingSetup)objWindow;
                        BBuildingSetup ObjBBuildingSetup = new BBuildingSetup( foreach (EBuildingSetup objEclient in ObjBBuildingSetup.GetAllBuildingTYpe())

WPF list view selected row colour change

For setting the background color of Listview rows in an alternate fashion (odd rows and even rows) at first create a style element :
<Style x:Key="alternatingStyle" TargetType="{x:Type ListViewItem}"> <Style.Triggers> <Trigger Property="ItemsControl.AlternationIndex" Value="0"> <Setter Property="Background" Value="LightSkyBlue"></Setter> </Trigger> <Trigger Property="ItemsControl.AlternationIndex" Value="1"> <Setter Property="Background" Value="LightGray"></Setter> </Trigger> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="Orange"/> </Trigger> </Style.Triggers> </Style>

Now write this XAML code for ListView <ListV…

WPF DateTime show in Listview and DataGrid

In our WPF application when we want to visualize the date in list or grid column. then it show us date by default with time. but we don't want to see the time. so we can control easily in xaml code of list or grid. example as:

<ListView Height="147" HorizontalAlignment="Left" Margin="15,26,0,0" Name="lvCalList" VerticalAlignment="Top" Width="211"> <ListView.View> <GridView> <GridViewColumn DisplayMemberBinding="{Binding Path=FromDate,StringFormat={}{0:MM/dd/yyyy}}" Header="From Date" Width="100" /> <GridViewColumn DisplayMemberBinding="{Binding Path=ToDate,StringFormat={}{0:MM/dd/yyyy}}" Header="To Date" Width="105" /> </GridView> </ListView.View> </ListView>

WPF Stylist message Box

in our WPF application if we want to make our messagebox more stylist like:

we can easily do it in our application. For this we need to add a dll name WPF Extended toolkit to download from :

To represent the messagebox we can use:

MessageBoxResult result = Microsoft.Windows.Controls.MessageBox.Show("You are welcome", "Extended WPF ToolKit MessageBox", MessageBoxButton.OKCancel, MessageBoxImage.Information);


WPF searching DataGrid Field From TextBox Matching data

Hi all,
      Searching DataGrid Value from  TextBox is a good idea .

// Hare i use a list which will retrive data from database for DataGrid ItemsSource

List<EBuildingSetup> listbuildingInformation = ObjBBuildingSetup.GetAllBuildingInformation(eBuildingSetupObj);

dataGrid1.ItemsSource = listbuildingInformation;

//For Your button click:

 for (int i = 0; i < dataGrid1.Items.Count-1; i++)
                EBuildingSetup objEBuildingSetup = (EBuildingSetup)dataGrid1.Items[i];

                // Hare it is important that which field data you want to search like BuildingType in your grid
                    dataGrid1.SelectedIndex = i;

WPF Contextmenu For ListView item

If we want to use context menu in WPF Listview. Then we have to done 2 steps:

Bind your Listview for Contex Menu:

<ListView Height="136" Background="#FFDBF3F3" BorderBrush="#FF40C01D" HorizontalAlignment="Left" Margin="6,6,0,0" Name="zonelistView" VerticalAlignment="Top" Width="722" > <ListView.ContextMenu> <ContextMenu Name="ZoneIformationList" StaysOpen="true" Background="WhiteSmoke"> <ContextMenu.BitmapEffect> <BitmapEffectGroup/> </ContextMenu.BitmapEffect> <MenuItem Header="Edit" Name="EditZoneInfoContextMenu" Click="EditZoneInfoContextMenu_Click" /> <MenuItem Header="Remove" Name="RemoveZoneInfoContextMenu" Click="RemoveZoneInfoContextMenu_Click" />…

WPF Multicolumn ComboBox

In WPF Multicolumn ComboBox we can easily complete it By the following procedure:
Modify your Combobox maml as following:

================XAML  Binding ===============

<ComboBox Height="23" HorizontalAlignment="Left" Margin="87,7,0,0" Name="ZoneBranchIDcomboBox" VerticalAlignment="Top" Width="160" > <ComboBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding ZoneBranchId}" Width="60"/> <TextBlock Text="|"/> <TextBlock Text="{Binding ZoneBranchName}" Width="60"/> </StackPanel> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox>
==========Your UI Code for Load ComboBox:=========

private void LoadBranch…

WPF theme

In Codeplex There is some wonderfull theme for WPF

Substring and add String in WPF

hi all, For our application sometimes we need substring a string. Hare i give example in which it take a string from a text field and then substring it for perticular operation.

private void GenerateTicket()
string ticketNumber = lastTicketNumbertextBox.Text;
string substring = "";
substring = ticketNumber.Substring(2, 8);
ticketObj.LasetTicketNo = Convert.ToInt32(substring);
ticketObj.QuantiryOfTicket = Convert.ToInt32(ticketQuantitytextBox.Text);
ticketObj.TicketDuration = Convert.ToInt32(ticketTimeDurationtextBox.Text);
ticketObj.TicketCreationdate = Convert.ToDateTime(ticketGeneratordatePicker.Text);

list = ticketManager.GetGenerateNumber(ticketObj);
ticketObj.ListOfTicket = list;

foreach (Ticket ticketObj1 in list)



In Get generatenumber(ticketObj) method after generating the number from substring it add string again for every new number.

public List GetGenerateNumber(Ticket ticketObj)
List list=new List();

int firstNum…

WPF Delete Selected Item From Listview

we often need to delete item from Listview. You have to use context menu for perform delete operation. then on your delete event just write:

private void ticketRemovebutton_Click(object sender, RoutedEventArgs e) { if (ticketlistView.SelectedItem != null) { ticketlistView.Items.RemoveAt(ticketlistView.Items.IndexOf(ticketlistView.SelectedItem)); } else { MessageBox.Show("Please select item for remove from the list"); } }

Download the Latest Sample


How to Get Machine IP Address

Sometimes we need to get the IP Address of the current PC. Under a Event we can get the IP address Easily by using the Code:

string myHost = System.Net.Dns.GetHostName();
            string myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[1].ToString();
            MessageBox.Show("My PC Name : "+myHost + "\nMy IP Address : " + myIP);

WPF add listview column binding in XAML

some time we fall in confused that how to we will add Column in Listview it's quite Easy:

<ListView Height="91" HorizontalAlignment="Left"
    Margin="6,6,0,0" Name="ticketlistView" VerticalAlignment="Top" Width="560" >
<GridView AllowsColumnReorder="True">

<GridViewColumn DisplayMemberBinding="{Binding Path=VendorId}"Header="Vendor ID" Width="90"/>
<GridViewColumn DisplayMemberBinding

WPF ComboBox & ListView Load From Database

Combox load & Listview load for our application is one of the most important task in our Development.
For ComboBox:

 private void LoadVendorTYpeComboBox()
            ObjVendorTypeList = ObjBvendorType.GetAllVendirType();
            foreach (EVendorType obj in ObjVendorTypeList)


For ListView:
 private void LoadVendorTypeListView()         {             vendorTypelistView.Items.Clear();             ObjVendorTypeList = ObjBvendorType.GetAllVendirType();             foreach (EVendorType obj in ObjVendorTypeList)             {                 vendorTypelistView.Items.Add(obj);             }         }
for listview you have to bind the object in list column.
<GridViewColumn DisplayMemberBinding="{Binding Path=VendorType}"  Header="Vendor Type" Width="100"/>

WPF Message Box

Hay Guy's Sometime we are forgate how to write message box to perform operation. it's quite simple

MessageBox.Show("Are you sure want to Delete this?", "Confirmation", MessageBoxButton.YesNo) == MessageBoxResult.Yes

WPF Listview selection item change

List view selection change is one of interesting matter in WPF. When you will select the item from list view. It will automatically fill field of the corrosponding item. Consider the following Selection change Event:

 private void unitNamelistView_SelectionChanged(object sender, SelectionChangedEventArgs e)
            if (unitNamelistView.SelectedIndex > -1)
   /*====Setting Selected item in Entity=====*/
                EUnitMeasurement seletedUnit = (EUnitMeasurement)unitNamelistView.SelectedItem;
                /*==== Filling UI Field From entity======*/
    unitIDtextBox.Text = seletedUnit.Id;
                unitAbbrivationtextBox.Text = seletedUnit.UnitName;
                fullNameUnittextBox.Text = seletedUnit.FullNameOfUnit;
                unitCommenttextBox.Text = seletedUnit.UnitComment;


WPF Text Change value will Auto select Listview item

if you want to select Listview item in Textfield value change you can do it by the code in text Change Event:

private void textBox1_TextChanged(object sender, TextChangedEventArgs e) { string typeID = textBox1.Text; for (int i = 0; i < unitNamelistView.Items.Count; i++) { EUnitMeasurement aWHType = (EUnitMeasurement)unitNamelistView.Items[i]; if (aWHType.UnitName == typeID) { unitNamelistView.SelectedIndex = i; break; } } }

WPF Get All Country in Combobox

To Get all Country Name in your program now you no need to use Enum or load from Database. Microsoft .NET give All Country Name using this code.
** You need to use namesapce: using System.Globalization;
Create a Method in Load event of your UI and Implement it as Following:

    private void PopulateCountryComboBox()
            RegionInfo country = new RegionInfo(new CultureInfo("en-US", false).LCID);
            List<string> countryNames = new List<string>();
            foreach (CultureInfo cul in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
                country = new RegionInfo(new CultureInfo(cul.Name, false).LCID);


            IEnumerable<string> nameAdded = countryNames.OrderBy(names => names).Distinct();

            foreach (string item in nameAdded)


WPF Google Sample project

This link contain some WPF sample project

WPF Crystal Report Viewer Using SAP

There is no doubt that we fall a great problem that the VS2010 is not intregated crystal report. Initially it seems to be a big problem. Hare is some step for SAP crystal report that we can use in our WPF application.

1.Download  Crystal report from this Link:
2. Remove Crystal report if any exist.
3. Close your VS-2010 and install the new downloaded CRforVS_13_0 .
4. Take a new WPF project

5. Right click on the project click on Properties

6. Change the target framework .NET Framework 4 Client Profile to  .NET Framework 4.

7. Click on main window then click on Toolbox.  Right Click on the General Tab then click on Choose Item.

8. It will appear this window click on WPF Component.

9.  Select CrystalReportsViewer  click on ok  Button.

10. Now you will see the report viewer control.

11. Your Crystal Report Environment is ready. Now we will add Crystal report. Maximum time we use dataset for report source But I Strongly recommend to use your Class as repor…

WPF set Image in UI

byte[] ImgGet ;
  /*image setUp*/
            ImgGet = (byte[])objEVendorInformation.SupplierLogo;
            string strfn = Convert.ToString(DateTime.Now.ToFileTime());
            FileStream fs1 = new FileStream(strfn, FileMode.CreateNew, FileAccess.Write);
            fs1.Write(ImgGet, 0, ImgGet.Length);
            ImageSourceConverter imgs = new ImageSourceConverter();
            SupplierLogoimage.SetValue(Image.SourceProperty, imgs.ConvertFromString(strfn));
            /*End Image Setup*/

WPF Pop Up List View

Pop up List view is needed when we want to search from database.

/=============== Button Event==================/

    private void VendorItemListSearchListBoxSelectionChanged_Click(object sender, RoutedEventArgs e)
            vendorItemListPopup.IsOpen = true;
                List<EVendorItem> listVendorItem = ObjBvendorItem.GetAllVendorList();
                foreach (EVendorItem aEJournalMaster in listVendorItem)
            catch (Exception ex)
                MessageBox.Show("Error: " + ex.Message, "Vendor List ID Search", MessageBoxButton.OK, MessageBoxImage.Error);

  /============= Pop up List view Change Event=============/

    private void VendorItemListSearchListBoxSelectionChanged(object sender…