Popular Posts

Tuesday, September 30, 2014

How to filter number in textbox



Below is the complete solution for accept only number and decimal by Textbox  in wpf.


First have create a DP.

 public static class TextBoxFilter
    {
        private static readonly List<Key> _controlKeys = new List<Key>
                                                            {
                                                             
                                                                Key.End,
                                                                Key.Enter,
                                                                Key.Escape,
                                                                Key.Home,
                                                                Key.Insert,
                                                                Key.Left,
                                                                Key.PageDown,
                                                                Key.PageUp,
                                                                Key.Back,
                                                                Key.CapsLock,
                                                                Key.LeftCtrl,
                                                                Key.RightCtrl,
                                                                Key.Down,
                                                                Key.Right,
                                                                Key.LeftShift,
                                                                Key.RightShift,
                                                                Key.Tab,
                                                                Key.Up,
                                                             
                                                           
                                                            };

        private static bool _IsDigit(Key key)
        {
            bool shift = (Keyboard.Modifiers & ModifierKeys.Shift) != 0;
            bool retValue;
            if (key >= Key.D0 && key <= Key.D9 && !shift || key == Key.OemPeriod)
            {
             
                retValue = true;
            }
            else
            {
                retValue = key >= Key.NumPad0 && key <= Key.NumPad9;
            }
            return retValue;
        }

        public static bool GetIsPositiveNumericFilter(DependencyObject src)
        {
            return (bool)src.GetValue(IsPositiveNumericFilterProperty);
        }

        public static void SetIsPositiveNumericFilter(DependencyObject src, bool value)
        {
            src.SetValue(IsPositiveNumericFilterProperty, value);
        }

        public static DependencyProperty IsPositiveNumericFilterProperty =
            DependencyProperty.RegisterAttached(
            "IsPositiveNumericFilter", typeof(bool), typeof(TextBoxFilter),
            new PropertyMetadata(false, IsPositiveNumericFilterChanged));

        public static void IsPositiveNumericFilterChanged
            (DependencyObject src, DependencyPropertyChangedEventArgs args)
        {
            if (src != null && src is TextBox)
            {
                TextBox textBox = src as TextBox;

                if ((bool)args.NewValue)
                {
                    textBox.KeyDown += _TextBoxPositiveNumericKeyDown;
                }
            }
        }

        static void _TextBoxPositiveNumericKeyDown(object sender, KeyEventArgs e)
        {
            bool handled = true;

            if (_controlKeys.Contains(e.Key) || _IsDigit(e.Key))
            {
                handled = false;
            }

            e.Handled = handled;
        }


        //==================On the Change Behaviour

        public static bool GetIsBoundOnChange(DependencyObject src)
        {
            return (bool)src.GetValue(IsBoundOnChangeProperty);
        }

        public static void SetIsBoundOnChange(DependencyObject src, bool value)
        {
            src.SetValue(IsBoundOnChangeProperty, value);
        }

        public static DependencyProperty IsBoundOnChangeProperty =
                    DependencyProperty.RegisterAttached(
            "IsBoundOnChange", typeof(bool), typeof(TextBoxFilter),
            new PropertyMetadata(false, IsBoundOnChangeChanged));

        public static void IsBoundOnChangeChanged(DependencyObject src,
                    DependencyPropertyChangedEventArgs args)
        {
            if (src != null && src is TextBox)
            {
                TextBox textBox = src as TextBox;

                if ((bool)args.NewValue)
                {
                    textBox.TextChanged += _TextBoxTextChanged;
                }
            }
        }

        static void _TextBoxTextChanged(object sender, TextChangedEventArgs e)
        {
            if (sender is TextBox)
            {
                TextBox tb = sender as TextBox;
                BindingExpression binding = tb.GetBindingExpression(TextBox.TextProperty);
                if (binding != null)
                {
                    binding.UpdateSource();
                }
            }
        }
    }


and in XAML.

<TextBox  Name="txtCode"  utility:TextBoxFilter.IsPositiveNumericFilter="True"
                                  utility:TextBoxFilter.IsBoundOnChange="True" />


Sunday, September 28, 2014

Focus on control from viewModel

In wpf we should not access any UI control in viewmodel then how can we focus on control any such condition . below is solution for the same.


First create a attached property.

 public static class FocusExt
    {
        public static bool GetIsFocused(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsFocusedProperty);
        }


        public static void SetIsFocused(DependencyObject obj, bool value)
        {
            obj.SetValue(IsFocusedProperty, value);
        }


        public static readonly DependencyProperty IsFocusedProperty =
            DependencyProperty.RegisterAttached(
             "IsFocused", typeof(bool), typeof(FocusExt),
             new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));


        private static void OnIsFocusedPropertyChanged(DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            var uie = (UIElement)d;
            if ((bool)e.NewValue)
            {
                uie.Focus();
            }
        }
    }




First add namastace inb XAML like.
xmlns:utility="clr-namespace:NPOS.Utility"


then create a property in Model.
 private bool isControlFocused;

        public bool IsControlFocused
        {
            get { return isControlFocused; }
            set { isControlFocused = value; OnPropertyChanged("IsControlFocused"); }
        }


and set it to true in ViewModel.
Model.IsControlFocused = true;

and finally bind this property ib View.
 <TextBox utility:FocusExt.IsFocused="{Binding Model.IsControlFocused}"/>                                        

Sunday, March 2, 2014

How to self host the MVC Web API

Below is the complete solution for self hosting of Web API.

static HttpClient client = new HttpClient();
        static void Main(string[] args)
        {
            client.BaseAddress = new Uri("http://admin.xyz.com");
            ListAllProducts();
            ListProduct(1);
        }

 static void ListAllProducts()
        {
            HttpResponseMessage resp = client.GetAsync("api/product").Result;
            resp.EnsureSuccessStatusCode();
            var products = resp.Content.ReadAsStringAsync().Result;
        }

 static void ListProduct(int id)
        {
            var resp = client.GetAsync(string.Format("api/product/{0}", id)).Result;
            resp.EnsureSuccessStatusCode();
            var product = resp.Content.ReadAsStringAsync().Result;

        }

How to get/save image from live stream

Below is the complete solution for get image from live stream and save to local disk.

//=============================================================
    //Please change following variables to suite your need, strIP to the camera IP
        private string strIP = "000.00.0.000";
        private static string ImagePath = "d:\\";
       static string  name = "";
    //===========================================================


// Get image from live stream.
 private void BtnDownload_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string baseUrl = "http://" + strIP + "/cgi-bin/snapshot.cgi?channel=2";

                Uri urlUri = new Uri(baseUrl);
                WebRequest webRequest = WebRequest.CreateDefault(urlUri);
                webRequest.ContentType = "image/jpeg";
                WebResponse webResponse = webRequest.GetResponse();
                var images = new BitmapImage();
                images.BeginInit();
                images.StreamSource = webResponse.GetResponseStream();
                images.EndInit();
                img.Source = images;
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

//Get image from image control to save on local disk.
 public byte[] GetImageFromImageControl(BitmapImage imageC)
        {
            MemoryStream memStream = new MemoryStream();
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(imageC));
            encoder.Save(memStream);
            return memStream.GetBuffer();
        }

//Save to local disk
 private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var image = GetImageFromImageControl(img.Source as BitmapImage);
                SaveImageToDisk(image);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

public static void SaveImageToDisk(byte[] imageByte)
        {
            MemoryStream ms = new MemoryStream(imageByte);
            Image image = Image.FromStream(ms);
            name = ImagePath + DateTime.Now.Ticks + ".jpeg";
            image.Save(name);
            MessageBox.Show("Image saved at  " + name);
        }

Tuesday, February 11, 2014

How to add SplashScreen in WPF application

You can add SplashScreen easily of WPF application.

1-Create image that you want to use as a splash screen. 
You can use any image format like BMP, GIF, JPEG, PNG, or TIFF format.

2-Right click on project and click on existing Items then add image to project

3-In Solution Explorer, select the image.

4- In the Properties window of image, click the drop-down arrow for the Build Action property.
Select SplashScreen from the drop-down list.
5- Press F5 , SplashScreen will show before application start.

this is useful when application start-up is slow.

Monday, February 10, 2014

The version of SQL Server in use does not support datatype 'datetime2'

Sometime we face Sql server  version not support datetime2 errer in entity framework when we run application .


 I did a quick research and found out that datetime2 aka datetime2(7) is the problem and settingProviderManifestToken="2005" will solve the issue.


Solution:-

we have to change SQL server version in edmx file.right click on your edmx, open it with XML (Text) Editor and set ProviderManifestToken="2005"

will work proper.