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..................!!!

Tuesday, February 8, 2011

WPF Validator as ajax/ Jquery

You can use wpf validator more smooth as ajax/ jquery. Just complete the following with me.

 Step 1.

       Open A new Window in WPF

Step 2. Add a class Which will provide the Validation

          /************ StringAtikStringValidationRule ************/

using System.Globalization;
using System.Windows.Controls;

namespace WpfApplication4
{
    public class StringAtikStringValidationRule : ValidationRule
    {
        private int _minimumLength = -1;
        private int _maximumLength = -1;
        private string _errorMessage;

        public int MinimumLength
        {
            get { return _minimumLength; }
            set { _minimumLength = value; }
        }

        public int MaximumLength
        {
            get { return _maximumLength; }
            set { _maximumLength = value; }
        }

        public string ErrorMessage
        {
            get { return _errorMessage; }
            set { _errorMessage = value; }
        }

        public override ValidationResult Validate(object value,
            CultureInfo cultureInfo)
        {
            ValidationResult result = new ValidationResult(true, null);
            string inputString = (value ?? string.Empty).ToString();
            if (inputString == null)
            {
                inputString = string.Empty;
            }

            if (inputString.Length < this.MinimumLength ||
                   (this.MaximumLength > 0 &&
                    inputString.Length > this.MaximumLength))
            {
                result = new ValidationResult(false, this.ErrorMessage);
            }
            return result;
        }
    }
}
                  /********End Of the Class**********/

Step 3. Now add a class which will Show the Error Message

           /**************ErrorProvider ************/

using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows;
using System.ComponentModel;
using System.Windows.Data;
using System.Reflection;

namespace WpfApplication4
{
    public class ErrorProvider : Decorator
    {
        private delegate void FoundBindingCallbackDelegate(FrameworkElement element, Binding binding, DependencyProperty dp);
        private FrameworkElement _firstInvalidElement;
        private Dictionary<DependencyObject, Style> _backupStyles = new Dictionary<DependencyObject, Style>();

        /// <summary>
        /// Constructor.
        /// </summary>
        public ErrorProvider()
        {
            this.DataContextChanged += new DependencyPropertyChangedEventHandler(ErrorProviderDataContextChanged);
            this.Loaded += new RoutedEventHandler(ErrorProviderLoaded);
        }

        /// <summary>
        /// Called when this component is loaded. We have a call to Validate here that way errors appear from the very
        /// moment the page or form is visible.
        /// </summary>
        private void ErrorProviderLoaded(object sender, RoutedEventArgs e)
        {
            Validate();
        }

        /// <summary>
        /// Called when our DataContext changes.
        /// </summary>
        private void ErrorProviderDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.OldValue != null && e.OldValue is INotifyPropertyChanged)
            {
                ((INotifyPropertyChanged)e.NewValue).PropertyChanged -= new PropertyChangedEventHandler(DataContextPropertyChanged);
            }

            if (e.NewValue != null && e.NewValue is INotifyPropertyChanged)
            {
                ((INotifyPropertyChanged)e.NewValue).PropertyChanged += new PropertyChangedEventHandler(DataContextPropertyChanged);
            }

            Validate();
        }

        /// <summary>
        /// Validates all properties on the current data source.
        /// </summary>
        /// <returns>True if there are no errors displayed, otherwise false.</returns>
        /// <remarks>
        /// Note that only errors on properties that are displayed are included. Other errors, such as errors for properties that are not displayed,
        /// will not be validated by this method.
        /// </remarks>
        public bool Validate()
        {
            bool isValid = true;
            _firstInvalidElement = null;

            if (this.DataContext is IDataErrorInfo)
            {
                List<Binding> allKnownBindings = ClearInternal();

                // Now show all errors
                foreach (Binding knownBinding in allKnownBindings)
                {
                    string errorMessage = ((IDataErrorInfo)this.DataContext)[knownBinding.Path.Path];
                    if (errorMessage != null && errorMessage.Length > 0)
                    {
                        isValid = false;

                        // Display the error on any elements bound to the property
                        FindBindingsRecursively(
                        this.Parent,
                        delegate(FrameworkElement element, Binding binding, DependencyProperty dp)
                        {
                            if (knownBinding.Path.Path == binding.Path.Path)
                            {

                                BindingExpression expression = element.GetBindingExpression(dp);
                                ValidationError error = new ValidationError(new ExceptionValidationRule(), expression, errorMessage, null);
                                System.Windows.Controls.Validation.MarkInvalid(expression, error);

                                if (_firstInvalidElement == null)
                                {
                                    _firstInvalidElement = element;
                                }
                                return;

                            }
                        });
                    }
                }
            }
            return isValid;
        }

        /// <summary>
        /// Returns the first element that this error provider has labelled as invalid. This method
        /// is useful to set the users focus on the first visible error field on a page.
        /// </summary>
        /// <returns></returns>
        public FrameworkElement GetFirstInvalidElement()
        {
            return _firstInvalidElement;
        }

        /// <summary>
        /// Clears any error messages.
        /// </summary>
        public void Clear()
        {
            ClearInternal();
        }

        /// <summary>
        /// Clears any error messages and returns a list of all bindings on the current form/page. This is simply so
        /// it can be reused by the Validate method.
        /// </summary>
        /// <returns>A list of all known bindings.</returns>
        private List<Binding> ClearInternal()
        {
            // Clear all errors
            List<Binding> bindings = new List<Binding>();
            FindBindingsRecursively(
                    this.Parent,
                    delegate(FrameworkElement element, Binding binding, DependencyProperty dp)
                    {
                        // Remember this bound element. We'll use this to display error messages for each property.
                        bindings.Add(binding);
                    });
            return bindings;
        }

        /// <summary>
        /// Called when the PropertyChanged event is raised from the object we are bound to - that is, our data context.
        /// </summary>
        private void DataContextPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsValid")
            {
                return;
            }
            Validate();
        }

        /// <summary>
        /// Recursively goes through the control tree, looking for bindings on the current data context.
        /// </summary>
        /// <param name="element">The root element to start searching at.</param>
        /// <param name="callbackDelegate">A delegate called when a binding if found.</param>
        private void FindBindingsRecursively(DependencyObject element, FoundBindingCallbackDelegate callbackDelegate)
        {

            // See if we should display the errors on this element
            MemberInfo[] members = element.GetType().GetMembers(BindingFlags.Static |
                    BindingFlags.Public |
                    BindingFlags.FlattenHierarchy);

            foreach (MemberInfo member in members)
            {
                DependencyProperty dp = null;

                // Check to see if the field or property we were given is a dependency property
                if (member.MemberType == MemberTypes.Field)
                {
                    FieldInfo field = (FieldInfo)member;
                    if (typeof(DependencyProperty).IsAssignableFrom(field.FieldType))
                    {
                        dp = (DependencyProperty)field.GetValue(element);
                    }
                }
                else if (member.MemberType == MemberTypes.Property)
                {
                    PropertyInfo prop = (PropertyInfo)member;
                    if (typeof(DependencyProperty).IsAssignableFrom(prop.PropertyType))
                    {
                        dp = (DependencyProperty)prop.GetValue(element, null);
                    }
                }

                if (dp != null)
                {
                    // Awesome, we have a dependency property. does it have a binding? If yes, is it bound to the property we're interested in?
                    Binding bb = BindingOperations.GetBinding(element, dp);
                    if (bb != null)
                    {
                        // This element has a DependencyProperty that we know of that is bound to the property we're interested in.
                        // Now we just tell the callback and the caller will handle it.
                        if (element is FrameworkElement)
                        {
                            if (((FrameworkElement)element).DataContext == this.DataContext)
                            {
                                callbackDelegate((FrameworkElement)element, bb, dp);
                            }
                        }
                    }
                }
            }

            // Now, recurse through any child elements
            if (element is FrameworkElement || element is FrameworkContentElement)
            {
                foreach (object childElement in LogicalTreeHelper.GetChildren(element))
                {
                    if (childElement is DependencyObject)
                    {
                        FindBindingsRecursively((DependencyObject)childElement, callbackDelegate);
                    }
                }
            }
        }
    }
}
              /*********** End Of The Error Provider Class*************/

 Step.4 Now add the XAML code in App.xaml in application Resource Which will take effect On Every Page.

               /****************** App.XAML ********************/

  <Application.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <DockPanel LastChildFill="True">

                            <TextBlock DockPanel.Dock="Right"
Foreground="Orange"
Margin="5" 
FontSize="12pt"
Text="{Binding ElementName=MyAdorner, 
                               Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                            </TextBlock>

                            <Border BorderBrush="Green" BorderThickness="3">
                                <AdornedElementPlaceholder Name="MyAdorner" />
                            </Border>

                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self}, 
                       Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Application.Resources>

                              /****************End Of App XAML***************/

step 5. Now customise your UI Field which you want to set validate. Consider a text Box then xaml will be

                            /************* Text box xaml*************/
 <StackPanel>
            <TextBox Height="23" HorizontalAlignment="Left" Margin="93,91,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" >
                <TextBox.Text>
                    <Binding Path="Name" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <local:StringAtikStringValidationRule MinimumLength="1" MaximumLength="30" 
ErrorMessage="Name is required." />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>
        </StackPanel>

                           /*********** End Of xaml Stack***************/
Step 6. create a class in which aspect you bind the text field consider customer class.

                          /************ Customer Class ************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WpfApplication4
{
    public class Customer
    {
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }
}
              /********** End Of Customer Class**********/
step 7. Now declare the class at the initially of your UI.
                      /***************** Initial in UI *****************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApplication4
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            Customer c = new Customer();

            InitializeComponent();
            this.DataContext = c;
        }
    }
}
                         /******************* End of initialization UI *********************/
Enjoy................. 


Saturday, February 5, 2011

UI Field Validation in WPF

UI field validation in WPF is a one of most important. Because when the field can't get the Specific class then it will get Error. So it better to create a CheckField()  for specific Button Event & there you can implement the method as:

/******************* A Button Event *****************/
         private void appointAddButton_Click(object sender, RoutedEventArgs e)
        {
            AddAppointmentInListView();


        }
     /************** Implement AddAppointmentInListView Method*****************/
        private void AddAppointmentInListView()
        {
            try
            {
                if (CheckField())
                {
                    EAppointment objAppointment = new EAppointment();
                    objAppointment.TrackNo = Convert.ToInt64(employeeTrackNoTextBox.Text);
                    objAppointment.InterviewId = Convert.ToInt64(employeeIdTextBox.Text);
                    objAppointment.AppointmentDate =  appointDateDateTimePicker.SelectedDate.Value;
                    List<EAppointment> listAppoint = new List<EAppointment>();
                    listAppoint.Add(objAppointment);
                    objAppointment.AppointList = listAppoint;
                    appointlistView.Items.Add(objAppointment);
                    
                }
                
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
  /************* Implement CheckField Method************/
 /********* Note that you should Declare raiseKeyUp as Global********
/******** private bool raiseKeyUp = true; ********/
     private bool CheckField()
        {
            if (employeeTrackNoTextBox.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Please enter Track Number", "IEMS", MessageBoxButton.OK);
                this.raiseKeyUp = false;
                employeeTrackNoTextBox.Focus();
                return false;
            }
                             return true;
        }

  You can also Make your Validation Field more Glossy if you download the Code from the link:


                 http://www.codeproject.com/KB/WPF/wpfvalidation.aspx
                 http://www.codeproject.com/KB/WPF/RegexValidationInWPF.aspx

  Now see what happen in your validation. Enjoy......!!



Friday, February 4, 2011

Upload a Picture in WPF UI

 Uploading Picture in UI is very Important It is Quite Easy. On upload button Event Write down The following code:

                OpenFileDialog dlg;
                FileStream fs;
               byte[] data;

              dlg = new Microsoft.Win32.OpenFileDialog();

              dlg.ShowDialog();
               if (dlg.FileName == "")
            {
                MessageBox.Show("Picture is not selected......");
            }
            else
            {
                fs = new FileStream(dlg.FileName, FileMode.Open, FileAccess.Read);


                data = new byte[fs.Length];
                fs.Read(data, 0, System.Convert.ToInt32(fs.Length));


                fs.Close();
                ImageSourceConverter imgs = new ImageSourceConverter();
                SupplierLogoimage.SetValue(Image.SourceProperty, imgs.ConvertFromString(dlg.FileName.ToString()));


EnJoy....... !!

Thursday, February 3, 2011

Generate Random Number

The Random class defined in the .NET Framework class library provides functionality to generate random numbers. 

The Random class constructors have two overloaded forms. It takes either no value or it takes a seed value.

The Random class has three public methods - Next, NextBytes, and NextDouble. The Next method returns a random number, NextBytes returns an array of bytes filled with random numbers, and NextDouble returns a random number between 0.0 and 1.0. The Next method has three overloaded forms and allows you to set the minimum and maximum range of the random number.



                int newTicketNumber;
                int ticketnumber = Convert.ToInt32(lastTicNotextBox.Text);
                Random random =new Random();
                newTicketNumber = random.Next(ticketnumber);
                newticnomtextBox.Text = newTicketNumber.ToString();

Wednesday, February 2, 2011

MSDN WPF

Windows Presentation Foundation (WPF) is a next-generation presentation system for building Windows client applications with visually stunning user experiences. With WPF, you can create a wide range of both standalone and browser-hosted applications


   http://msdn.microsoft.com/en-us/library/aa970268.aspx

WPF Developer Tools

in wpf there are many tools are not support as we do win/Web form. this project is very usefull for WPF control tool.

        http://wpfdevelopertools.codeplex.com/

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...