Wednesday, November 30, 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();  
       }  
     }  

Thursday, October 27, 2011

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.Items.Add("Atik");
            comboBox1.Items.Add("Amin");
            comboBox1.Items.Add("Nabab");
            comboBox1.Items.Add("Refat");
            comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
        }

Tuesday, October 25, 2011

C# LINQ INSERT,UPDATE, DELETE, DOES EXIST statement

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.

LINQ INSERT:


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


LINQ DOESEXIST:


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


LINQ UPDATE:


 public void UpdateProductName(Product aProduct)  
     {  
       var product = dataContexObj.PRODUCT_NAMEs.First(c => c.ID == aProduct.Id);  
       product.NAME = aProduct.ProductName;  
       dataContexObj.SubmitChanges();  
     }  


LINQ DELETE:



 public void DeleteProductName(Product aProduct)  
     {  
       PRODUCT_NAME productName = dataContexObj.PRODUCT_NAMEs.First(c => c.ID == aProduct.Id);  
       dataContexObj.PRODUCT_NAMEs.DeleteOnSubmit(productName);  
       dataContexObj.SubmitChanges();  
     }  



LINQ GETALL FROM TABLE:



 public List<Product> GetAllProductName()  
     {  
       List<Product> products = new List<Product>();  
       foreach (var p in (from j in dataContexObj.PRODUCT_NAMEs select new { j.ID, j.NAME }).Distinct())  
       {  
         Product aProduct = new Product();  
         aProduct.ProductName = p.NAME;  
         aProduct.Id = (int)p.ID;  
         products.Add(aProduct);  
       }  
       return products;  
     }  


Enjoy...




Saturday, October 22, 2011

How to use code in blogspot

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

http://codeformatter.blogspot.com/2009/06/about-code-formatter.html#comment-form

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

Enjoy...

Friday, October 21, 2011

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" Value="Green"/>  
                               <Setter TargetName="txtTextBlock" Property="Foreground" Value="White"/>  
                          </DataTrigger>  
                     </DataTemplate.Triggers>  
                </DataTemplate>  
           </DataGridTemplateColumn.CellTemplate>  
      </DataGridTemplateColumn>  

Enjoy...

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;
                eCalendarSetup.StartTime = calendarInfo.CAL_START_TIME.ToString();
                eCalendarSetup.EndTime = calendarInfo.CAL_END_TIME.ToString();
                eCalendarSetup.Remarks = calendarInfo.CAL_REMARKS;
                calendarSetupsList.Add(eCalendarSetup);
            }  
            return calendarSetupsList;
        }






Enjoy....

Thursday, October 20, 2011

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).Split('-');  
           string[] splitedMainId = splitedRef[0].Split('Q');  
           rfqSerials.Add(Convert.ToInt32(splitedMainId[1]));  
         }  
         refence = "RFQ"+ (rfqSerials.Max() + 1) + "-" + dt.Year;  
       }  
       else  
       {  
         refence = "RFQ10001" + "-" + dt.Year;  
       }  
       return refence;  
     }  

Enjoy...

Monday, October 17, 2011

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;  
         if (i==0)  
         {  
           anStock.Qty = Convert.ToInt32(textBox1.Text);  
         }  
         else if (i == 1)  
         {  
           anStock.Qty = Convert.ToInt32(textBox2.Text);  
         }  
         else  
         {  
           anStock.Qty = Convert.ToInt32(textBox3.Text);  
         }  
         stockManagerObj.MoveToBranch(anStock);  
       }  

Load ListView:


 headlistView.Items.Clear();  
       foreach (EStock stock in stockManagerObj.GetAllHeadofficeStock())  
       {  
         headlistView.Items.Add(stock);  
       }  


LINQ GetAll From Table:


  List<EStock> headList = new List<EStock>();  
       var queery = from head in dataContex.HeadStocks  
             select new {head.TrNo, head.ItemCode, head.ItemName, head.Qty};  
       foreach (var hOffice in queery)  
       {  
         EStock eStock = new EStock();  
         eStock.Tr_No = hOffice.TrNo;  
         eStock.ItemCode = hOffice.ItemCode;  
         eStock.ItemName = hOffice.ItemName;  
         eStock.Qty = (int) hOffice.Qty;  
         headList.Add(eStock);  
       }  
       return headList;  


LINQ Does Exist:


  internal bool DoesExist(EStock anStock)  
     {  
       return (dataContex.BranchStocks.Any(o => o.ItemCode.Contains(anStock.ItemCode) && o.TrNo.Contains(anStock.Tr_No)));  
     }  

Sunday, October 9, 2011

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:

Enjoy...

Wednesday, October 5, 2011

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:

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/d3d6b7ec-71f9-4011-afc5-0bf3956e6d78#x__Toc265507378

Enjoy.

Friday, June 10, 2011

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()
        {
            try
            {
                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;
                        obj.buildingTypecomboBox.Items.Clear();
                        BBuildingSetup ObjBBuildingSetup = new BBuildingSetup( foreach (EBuildingSetup objEclient in ObjBBuildingSetup.GetAllBuildingTYpe())
                        {
                                         obj.buildingTypecomboBox.Items.Add(objEclient.BuildingType);
                        }
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Combobox reloading problem", "Client Info", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }





Thank you.

Saturday, May 7, 2011

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
 <ListView BorderBrush="#FFA8CC7B" Height="133" HorizontalAlignment="Left"  
    Margin="88,382,0,0"Name="lvInvDetails" VerticalAlignment="Top" Width="596"  
     ItemContainerStyle="{StaticResource alternatingStyle}" AlternationCount="2">  
   <ListView.View>  
     <GridView>  
     <GridViewColumn DisplayMemberBinding="{Binding Path=InvoiceDetailsItemId}"  
           Header="Item Id" Width="90" />  
     <GridViewColumn DisplayMemberBinding="{Binding Path=InvoiceDetailsItemName}"  
          Header="Item Name" Width="120" />  
     </GridView>  
   </ListView.View>  
 </ListView>  


enjoy...

 

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>  

Wednesday, April 27, 2011

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 :

  http://wpftoolkit.codeplex.com/

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);


Enjoy....

Friday, April 22, 2011

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
                if(objEBuildingSetup.BuildingType==textBox2.Text.Trim())
                {
                    dataGrid1.SelectedIndex = i;
                }
            }

Thursday, March 31, 2011

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" />  
           </ContextMenu>  
  </ListView.ContextMenu>  
          <ListView.View>  
             <GridView>  
               <GridViewColumn Header="Branch ID"  
            Width="80" DisplayMemberBinding="{Binding Path=ZoneBranchId}" />  
               <GridViewColumn Header="Building ID"  
            Width="80" DisplayMemberBinding="{Binding Path=ZoneBuildingId}" />  
             </GridView>  
          </ListView.View>  
   </ListView>  

 

     
         

Now you can set action on Click Event. consider EditZoneInfoContextMenu 



   private void EditZoneInfoContextMenu_Click(object sender, RoutedEventArgs e)  
     {  
       FillZoneInformationField();  
     }  
           //Implement your method  
           private void FillZoneInformationField()  
     {  
       if (zonelistView.SelectedIndex > -1)  
       {  
         ObjEZoneSetup = (EZoneSetup) zonelistView.SelectedItem;  
         zoneIDtextBox.Text = ObjEZoneSetup.ZoneId;  
         zoneAisletextBox.Text = ObjEZoneSetup.ZoneAisle;  
         zonePositiontextBox.Text = ObjEZoneSetup.ZonePosition;  
         zoneTiretextBox.Text = ObjEZoneSetup.ZoneTire;  
         zoneInfotextBox.Text = ObjEZoneSetup.ZoneAdditionalInfo;  
         if (ObjEZoneSetup.ZoneStatus=='Y')  
         {  
           zoneActiveradioButton.IsChecked = true;  
         }  
         if (ObjEZoneSetup.ZoneStatus=='N')  
         {  
           zoneInactiveradioButton.IsChecked = true;  
         }  
         zonelistView.Items.Remove(zonelistView.SelectedItem);  
       }  
     }  




Download the latest sample

Enjoy.....!


Wednesday, March 23, 2011

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 LoadBranchIDComboBox()  
 {  
 ZoneBranchIDcomboBox.Items.Clear();  
 listOfZone = ObjBZoneSetup.GetAllBranchID();  
 foreach (EZoneSetup floorSetupObj in listOfZone)  
 {  
 ZoneBranchIDcomboBox.ItemsSource = listOfZone;  
 }  
 }  

=============== Business Logic============
 public List GetAllBranchID()  
 {  
 List listOfZoneBranchID = ObjZoneDAL.GetAllBranchID();  
 return listOfZoneBranchID;  
 }  

============== GateWay:=============
 public List GetAllBranchID()  
 {  
 List listOfBranchID = new List();  
 try  
 {  
 foreach (var ZoneSetup in objDataContext.SP_GET_BRANCH_NAME())  
 {  
 EZoneSetup eZoneSetupobj = new EZoneSetup();  
 eZoneSetupobj.ZoneBranchId = ZoneSetup.WI_ID;  
 eZoneSetupobj.ZoneBranchName = ZoneSetup.WI_NAME;  
 listOfBranchID.Add(eZoneSetupobj);  
 }  
 }  
 catch (Exception exception)  
 {  
 throw exception;  
 }  
 return listOfBranchID;  
 }  

Enjoy....

Wednesday, March 9, 2011

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)
{

{
ticketlistView.Items.Add(ticketObj1);
}


}
}




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 firstNumber = ticketObj.LasetTicketNo;
int secondNumber = ticketObj.QuantiryOfTicket;
int result = firstNumber + secondNumber;
string ticketNumber;

for (int count = firstNumber+1; count <= result; count++)
{
Ticket ticketObjTosend = new Ticket();
//ticketObjTosend.EncriptedTicket += "CA";
ticketObj.NewTicketNo = Convert.ToInt32(count);

ticketObjTosend.NewTicketNo =ticketObj.NewTicketNo;
ticketNumber = "CA";
ticketNumber += Convert.ToString(ticketObjTosend.NewTicketNo);


ticketObjTosend.EncriptedTicket = ticketNumber;

ticketObjTosend.TicketDuration = ticketObj.TicketDuration;
ticketObjTosend.TicketCreationdate = ticketObj.TicketCreationdate;

list.Add(ticketObjTosend);


}
return list;

}

Thursday, March 3, 2011

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

Enjoy....!!

Wednesday, March 2, 2011

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" >
<ListView.View>
<GridView AllowsColumnReorder="True">


<GridViewColumn DisplayMemberBinding="{Binding Path=VendorId}" Header="Vendor ID" Width="90"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=VendorName}" Header="Vendor Name" Width="90"/>
</GridView>
</ListView.View>
</ListView>

Sunday, February 27, 2011

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()
        {
            vendorTYpecomboBox.Items.Clear();
            ObjVendorTypeList = ObjBvendorType.GetAllVendirType();
            foreach (EVendorType obj in ObjVendorTypeList)
            {
                vendorTYpecomboBox.Items.Add(obj.VendorType);
            }

          
        }

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"/>

Enjoy...

Saturday, February 26, 2011

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

Friday, February 25, 2011

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;
               }
        }

Enjoy....!!



Thursday, February 24, 2011

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;  
         }  
         }  
     }  

Wednesday, February 23, 2011

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);

                countryNames.Add(country.DisplayName.ToString());
            }

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

            foreach (string item in nameAdded)
            {
                supplierCountryComboBox.Items.Add(item);
            
            }
        }

Monday, February 21, 2011

WPF Google Sample project

This link contain some WPF sample project
http://sites.google.com/site/wpfprojects/

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 report data source.

12.  Right click on the solution add a new window name ReportViewerUI.




Drag & drop the CrystalReportsViewer Control from Toolbox in ReportViewerUI.  Wait till the window look like





13. Modify the XAML like :
 <Window x:Class="WPFReportTest.ReportViewerUI"  
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
     Title="ReportViewerUI" Height="399" Width="724" xmlns:my="clr-namespace:SAPBusinessObjects.WPF.Viewer;assembly=SAPBusinessObjects.WPF.Viewer">  
   <Grid>  
     <my:CrystalReportsViewer Margin="63,38,0,0" Name="crystalReportsViewer" VerticalAlignment="Top" ShowLogo="False" HorizontalAlignment="Center"  
                  ShowToggleSidePanelButton="True" ShowToolbar="True" ShowOpenFileButton="False" />  
   </Grid>  
 </Window>  




and CS code:
 
 using System.Windows;  
 using System.Windows.Controls.Primitives;  
 namespace WPFReportTest  
 {  
   public partial class ReportViewerUI : Window  
   {  
     public ReportViewerUI()  
     {  
       InitializeComponent();  
       var sidepanel = crystalReportsViewer.FindName("btnToggleSidePanel") as ToggleButton;  
       if (sidepanel != null)  
       {  
         crystalReportsViewer.ViewChange += (x, y) => sidepanel.IsChecked = false;  
       }  
     }  
     public void setReportSource(CrystalDecisions.CrystalReports.Engine.ReportDocument aReport)  
     {  
       this.crystalReportsViewer.ViewerCore.ReportSource = aReport;  
     }  
   }  
 }  




 
14.You will get Error like this.



Right click on the project references add reference then add the 3 dll
Name: CrystalDecisions.CrystalReports.Design
      CrystalDecisions.CrystalReports.Engine
      CrystalDecisions.ReportSource
Now Build the Solution it will be Success.

15. Add a Report utility Class Name ReportUtility
  and modify the class with this method. 
 
 public static void Display_report(ReportClass rc, object objDataSource, Window parentWindow)  
     {  
       try  
       {  
         rc.SetDataSource(objDataSource);  
         ReportViewerUI  
               Viewer = new ReportViewerUI();  
         Viewer.setReportSource(rc);  
         Viewer.ShowDialog();  
       }  
       catch (Exception ex)  
       {  
         throw ex;  
       }  
     }  



16. Now we are want to show a table data in report. Let’s create a database ReportTestDB





Add a New table Like



Select Id as Primary Key and auto Increment. Give the name of the Table EMPLOYEE_INFO.

17. Now Insert some data




18. Right Click on the solution, Add new Item select LINQ to SQL DBML File name it ReportTestDataContext.dbml




19. It will appear this window  click on



Select your server name and database name

 
20. Expand the database select the table and drag and drop it to the DBML File.




Now Save it and close the window.
21. Add a New EEmployee Class which contain the following:

 public class EEmployee  
   {  
     public int Id { get; set; }  
     public string Name { get; set; }  
     public int Age { get; set; }  
     public string Address { get; set; }  
   }  


Also add 2 another class BEmployee and EmployeeDAL
 
 public class BEmployee  
   {  
     private EmployeeDAL employeeDALObj = new EmployeeDAL();  
     public List<EEmployee> GetAllEmployeeInfo()  
     {  
       return employeeDALObj.GetAllEmployeeInfo();  
     }  
   }  
 public class EmployeeDAL  
   {  
     private ReportTestDataContextDataContext reportDataContextObj = new ReportTestDataContextDataContext();  
     internal List<EEmployee> GetAllEmployeeInfo()  
     {  
       List<EEmployee> employees = new List<EEmployee>();  
       foreach (var info in reportDataContextObj.EMPLOYEE_INFOs)  
       {  
         EEmployee eEmployeeObj = new EEmployee();  
         eEmployeeObj.Id = info.Id;  
         eEmployeeObj.Name = info.Name;  
         eEmployeeObj.Age = (int) info.Age;  
         eEmployeeObj.Address = info.Address;  
         employees.Add(eEmployeeObj);  
       }  
       return employees;  
     }  
   }  


22. Right Click on the solution add a Crystal Report name EmployeeInfoCrystalReport




Select as a Blank report



Right click on the DataBase Field and click Database Expert



Expand  the .NET object and select EEmployee and click ok button.





Now Expand the Database field Drag and drop the attribute and design your crystal report.



After Completing your design Save all and close window.
23. Now In main window Take a Button Control  Name Show Employee Info . On the click event write down the code.

 List<EEmployee> employeeInfoList = bEmployeeObj.GetAllEmployeeInfo();  
       if (employeeInfoList.Count > 0)  
       {  
         EmployeeInfoCrystalReport employeeInfoCrystalReport = new EmployeeInfoCrystalReport();  
         ReportUtility.Display_report(employeeInfoCrystalReport, employeeInfoList, this);  
       }      
       else  
       {  
         MessageBox.Show("Don't have any records.", "Employee Info", MessageBoxButton.OK, MessageBoxImage.Information);  
       }  

25. Now Build the solution Run it Click on show Employee you Will get The following Error



To remove the error you have to add  this line of code in app.config file

 <startup useLegacyV2RuntimeActivationPolicy="true">  
       <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>  
    </startup>  

26. Now Build the solution Run it and you will get Your Desire report.



Download Crystal Report Source Code
Feel free for any comment.
thank you.

Monday, February 14, 2011

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);
            fs1.Flush();
            fs1.Close();
            ImageSourceConverter imgs = new ImageSourceConverter();
            SupplierLogoimage.SetValue(Image.SourceProperty, imgs.ConvertFromString(strfn));
            /*End Image Setup*/

Friday, February 11, 2011

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;
            vendorItemListSearchListBox.Items.Clear();
            try
            {
                List<EVendorItem> listVendorItem = ObjBvendorItem.GetAllVendorList();
                foreach (EVendorItem aEJournalMaster in listVendorItem)
                {
                    vendorItemListSearchListBox.Items.Add(aEJournalMaster);
                }
            }
            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, SelectionChangedEventArgs e)
        {
            if (vendorItemListSearchListBox.SelectedIndex > -1)
            {
                EVendorItem seletedItemList = (EVendorItem)vendorItemListSearchListBox.SelectedItem;
                viVendorNamestextBox.Text = seletedItemList.VendorName;
                itemvendorIDtextBox.Text = seletedItemList.VendorId;
                vlItemNametextBox.Text = seletedItemList.ItemName;
                vlItemNumbertextBox.Text = seletedItemList.ItemNumber;
                vlQuantityValutextBox.Text = seletedItemList.QuantityValu;
                vlManufacturingDateTimePicker.SelectedDate = seletedItemList.ManufacturingDate;
                vlEntryDateTimePicker.SelectedDate = seletedItemList.ExpireDate;
                vlActiveRadioButton.IsEnabled = true;
                vendorItemListPopup.IsOpen = false;
            }
        }

/============ Entity==================/


public class EVendorItem
    {
        public string VendorId { get; set; }
        public string VendorName { get; set; }
        public string ItemName { get; set; }
        public string ItemNumber { get; set; }
        public string QuantityValu { get; set; }
        public DateTime? ManufacturingDate { get; set; }
        public DateTime? ExpireDate { get; set; }
        public DateTime? AccessDate;
        public string AccessBY { get; set; }
        public char Status { get; set; }

    }

/=================== Entity Manager===================/

  private bool BSuccess { get; set; }
      VendorItemDAL objVendorItemDAL = new VendorItemDAL();
      public List<EVendorItem> GetAllVendorList()
      {
          List<EVendorItem> listVendorItem = objVendorItemDAL.GetAllVendorItemList();
          return listVendorItem;
      }

/================== Gateway====================/

    private bool BSuccess { get; set; }
      public List<EVendorItem> GetAllVendorItemList()
      {
          List<EVendorItem> listVendorItem = new List<EVendorItem>();

          try
          {
              IEBSDataContext objDataContext = new IEBSDataContext();
              foreach (var VendorItem in objDataContext.SP_VENDOR_ITEM_LIST_GETALL())
              {
                  EVendorItem objEVendorItem = new EVendorItem();
                  objEVendorItem.VendorId = VendorItem.VIL_VI_ID;
                  objEVendorItem.VendorName = VendorItem.VIL_NAME;
                  objEVendorItem.ItemNumber = VendorItem.VIL_ITEM_NUM;
                  objEVendorItem.QuantityValu = VendorItem.VIL_PER_QTY_VALUE.ToString();
                  objEVendorItem.ManufacturingDate = VendorItem.VIL_MFD;
                  objEVendorItem.ExpireDate = VendorItem.VIL_EXP_DATE;
                  objEVendorItem.Status = (char)VendorItem.VIl_STATUS;
                  listVendorItem.Add(objEVendorItem);
              }
          }
          catch (Exception objException)
          {

              throw objException;
          }
          return listVendorItem;
      }
/================== ui xaml code================/

 <!-- Pop up for Vendor Id & Name Searching-->
                        <Popup Name="vendorItemListPopup" Placement="Center" IsEnabled="True" IsOpen="False" Grid.RowSpan="2">
                            <ListView Height="145" HorizontalAlignment="Stretch" Margin="0,0,0,0" Name="vendorItemListSearchListBox" VerticalAlignment="Top" Width="257" SelectionChanged="VendorItemListSearchListBoxSelectionChanged">
                                <ListView.View>
                                    <GridView>
                                        <GridViewColumn Header="Vendor Id" Width="100" DisplayMemberBinding="{Binding Path=VendorId}" />
                                        <GridViewColumn Header="Vendor Name" Width="100" DisplayMemberBinding="{Binding Path=VendorName}" />
                                    </GridView>
                                </ListView.View>
                            </ListView>
                        </Popup>

Enjoy..................!!!

SQL Get all Index create script from Database

To get all script from database as a create new index into another database you can use the following --Get all Index Script SELECT...