Saturday, December 20, 2014

Insert xml data in sql server using OPENXML

DECLARE @xml NVARCHAR(max)

SET @xml ='<Delivery><item reqNo="REQ001" code="0001" Qty="25"/><item reqNo="REQ001" code="0002" Qty="35"/></Delivery>'


declare @xml_hndl int    
   
    exec sp_xml_preparedocument @xml_hndl OUTPUT, @xml


Select *

        From
            OPENXML(@xml_hndl, '/Delivery/item', 1)
            With
               (
                 reqNo NVARCHAR(20) '@reqNo',
                 code NVARCHAR(20) '@code',
                 qty money '@Qty'
               )
              

Left Outer Join Example in Entity Framework

public List<RawMaterial> GetRawMaterialInfo()
        {
            using (dbContext = new tPOS_DBEntities())
            {
                var data = from p in dbContext.RawMaterials
                           join q in dbContext.UnitOfMeasures on p.UOM_Receive equals q.Code into rcvUOM
                           from a in rcvUOM.DefaultIfEmpty()
                           join r in dbContext.UnitOfMeasures on p.UOM_Stock equals r.Code into stkUOM
                           from b in stkUOM.DefaultIfEmpty()
                           join s in dbContext.RawMaterials on p.ParentCode equals s.Code
                           select new
                           {
                               p.Code,
                               p.ConvertionRate,
                               p.CreatedBy,
                               p.CreatedDate,
                               p.DriesPrcnt,
                               p.ID,
                               p.Level,
                               p.Name,
                               p.NonExpireItem,
                               p.NonInvItem,
                               p.ParentCode,
                               RecvUOM = a.UOM,
                               p.ROL,
                               p.ROQ,
                               p.StdCPU,
                               p.StockCPU,
                               StockUOM = b.UOM,
                               p.SysCode,
                               p.UOM_Receive,
                               p.UOM_Stock,
                               p.UpdatedBy,
                               p.UpdatedDate,
                               ParentName = s.Name
                           };

                List<RawMaterial> lst = new List<RawMaterial>();
                RawMaterial l;

                foreach (var d in data)
                {
                    l = new RawMaterial();
                    l.Code = d.Code;
                    l.ConvertionRate = d.ConvertionRate;
                    l.CreatedBy = d.CreatedBy;
                    l.CreatedDate = d.CreatedDate;
                    l.DriesPrcnt = d.DriesPrcnt;
                    l.ID = d.ID;
                    l.Level = d.Level;
                    l.Name = d.Name;
                    l.NonExpireItem = d.NonExpireItem;
                    l.NonInvItem = d.NonInvItem;
                    l.ParentCode = d.ParentCode;
                    l.ParentName = d.ParentName;
                    l.RecvUOM = d.RecvUOM;
                    l.ROL = d.ROL;
                    l.ROQ = d.ROQ;
                    l.StdCPU = d.StdCPU;
                    l.StockCPU = d.StockCPU;
                    l.StockUOM = d.StockUOM;
                    l.SysCode = d.SysCode;
                    l.UOM_Receive = d.UOM_Receive;
                    l.UOM_Stock = d.UOM_Stock;
                    l.UpdatedBy = d.UpdatedBy;
                    l.UpdatedDate = d.UpdatedDate;

                    if (l.ParentName != null)
                    {
                        l.FullName = (l.ParentName.Trim().Length != 0 ? l.ParentName + "::" : "") + l.Name;
                    }
                    else
                    {
                        l.FullName = l.Name;
                    }

                    lst.Add(l);
                }
                return lst.OrderBy(p => p.ParentName).OrderBy(p => p.Name).ToList();

            }
        }

Tuesday, September 9, 2014

Conver rows to dynamic columns in sql server 2008

DECLARE @denominationList NVARCHAR(MAX)

SELECT @denominationList = STUFF(
    (SELECT '],[' + CONVERT(NVARCHAR(20),VALUE)
    FROM Gift_Denomination WHERE IsInactive = 0
    FOR XML PATH('')),1,2,'') +']'


DECLARE @sql NVARCHAR(max)

SET @sql =
'SELECT * FROM (
    SELECT  ShopId, ShopName,Value, 0 IssueQty FROM dbo.ShopList s, Gift_Denomination d
            WHERE LEFT(s.ShopId,1) = ''G'' AND  d.IsInactive = 0
) as SourceTable
PIVOT
(
    MAX(IssueQty)
    FOR Value IN ('+@denominationList+')
) AS PivotTable order by shopid'

EXECUTE (@sql)

Thursday, August 7, 2014

Jquery Is not working After Postback

use the following code:

<script type="text/javascript">
        //On UpdatePanel Refresh
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        if (prm != null) {
            prm.add_endRequest(function (sender, e) {
                if (sender._postBackSettings.panelsToUpdate != null) {
                    $("#ContentPlaceHolder1_txtDownPayment").blur(function () {                       
                        var ttl = $("#ContentPlaceHolder1_txtPrice").val();
                        var booking = $("#ContentPlaceHolder1_txtBookingAmount").val();
                        var downPayment = $("#ContentPlaceHolder1_txtDownPayment").val();

                        var remain = ttl - booking - downPayment;

                        $("#ContentPlaceHolder1_txtRemaingAmount").val(remain);                      
                    });
                }
            });
        };
    
    </script>

Wednesday, May 14, 2014

Numeric Textbox in WPF

public class TextBoxHelpers : DependencyObject
    {
        public static bool GetIsNumeric(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsNumericProperty);
        }

        public static void SetIsNumeric(DependencyObject obj, bool value)
        {
            obj.SetValue(IsNumericProperty, value);
        }

        // Using a DependencyProperty as the backing store for IsNumeric.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsNumericProperty =
         DependencyProperty.RegisterAttached("IsNumeric", typeof(bool), typeof(TextBoxHelpers), new PropertyMetadata(false, new PropertyChangedCallback((s, e) =>
         {
             TextBox targetTextbox = s as TextBox;
             if (targetTextbox != null)
             {
                 if ((bool)e.OldValue && !((bool)e.NewValue))
                 {
                     targetTextbox.PreviewTextInput -= targetTextbox_PreviewTextInput;

                 }
                 if ((bool)e.NewValue)
                 {
                     targetTextbox.PreviewTextInput += targetTextbox_PreviewTextInput;
                     targetTextbox.PreviewKeyDown += targetTextbox_PreviewKeyDown;
                 }
             }
         })));

        static void targetTextbox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = e.Key == Key.Space;
        }

        static void targetTextbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            TextBox tb = sender as TextBox;

            Char newChar = e.Text.ToString()[0];
            if (newChar != '.')
            {
                e.Handled = !Char.IsNumber(newChar);
            }
            else
            {
                e.Handled = tb.Text.Contains('.');
            }
        }
    }

xaml Page:

xmlns:ui="clr-namespace:Reluce.ServiceTracker.Helpers"  

<TextBox
            Name="txtQty"
            Grid.Row="4"
            Grid.Column="1"
            Margin="2"
            HorizontalAlignment="Left"           
            FontSize="12"
            AcceptsReturn="False"
            Width="120" 
            ui:TextBoxHelpers.IsNumeric="True"

Focus to next Control in wpf on Enter key event

public static class FocusAdvancement
    {
        public static bool GetAdvancesByEnterKey(DependencyObject obj)
        {
            return (bool)obj.GetValue(AdvancesByEnterKeyProperty);
        }

        public static void SetAdvancesByEnterKey(DependencyObject obj, bool value)
        {
            obj.SetValue(AdvancesByEnterKeyProperty, value);
        }

        public static readonly DependencyProperty AdvancesByEnterKeyProperty =
            DependencyProperty.RegisterAttached("AdvancesByEnterKey", typeof(bool), typeof(FocusAdvancement),
            new UIPropertyMetadata(OnAdvancesByEnterKeyPropertyChanged));

        static void OnAdvancesByEnterKeyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var element = d as UIElement;
            if (element == null) return;

            if ((bool)e.NewValue) element.KeyDown += Keydown;
            else element.KeyDown -= Keydown;
        }

        static void Keydown(object sender, KeyEventArgs e)
        {
            if (!e.Key.Equals(Key.Enter)) return;

            var element = sender as UIElement;
            if (element != null) element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }


in xaml Page:
 xmlns:ui="clr-namespace:Reluce.ServiceTracker.Helpers"

<TextBox
            Name="txtName"
            Grid.Row="1"
            Grid.Column="3"
            Margin="2"
            HorizontalAlignment="Left"           
            FontSize="12"
            AcceptsReturn="False"
            Width="120"
            ui:FocusAdvancement.AdvancesByEnterKey="True"
            />

Tuesday, April 29, 2014

Add Drop Shadow Effect to button in wpf

<Style TargetType="Button">
            <Setter Property="Button.Effect">
                <Setter.Value>
                    <DropShadowEffect Color="Black" Direction="320" ShadowDepth="3" BlurRadius="5" Opacity="0.5" />
                </Setter.Value>
            </Setter>
        
  </Style>

Create Rounded corner button on wpf

<Style TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border CornerRadius="6" Background="{TemplateBinding Background}"
                                BorderThickness="1">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center">
                            </ContentPresenter>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
  </Style>

Show Hand Cursor on mouse over of a Button in wpf

<Style TargetType="Button">
         <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Cursor" Value="Hand" />
                    <Setter Property="Background" Value="DarkGoldenrod"/>
                </Trigger>
            </Style.Triggers>
        </Style>

How show a Image in a ListviewItem when it is selected in wpf?

1. Converter Class:

public class BoolToVisibleOrHidden : IValueConverter
    {
        public BoolToVisibleOrHidden() { }
        public bool Collapse { get; set; }
        public bool Reverse { get; set; }
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool bValue = (bool)value;
            if (bValue != Reverse)
            {
                return Visibility.Visible;
            }
            else
            {
                if (Collapse)
                    return Visibility.Collapsed;
                else
                    return Visibility.Hidden;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Visibility visibility = (Visibility)value;
            if (visibility == Visibility.Visible)
                return !Reverse;
            else
                return Reverse;
        }
    }

2.  Add Reference to the xaml file:

xmlns:local="clr-namespace:Reluce.ServiceTracker.Helpers"

 <UserControl.Resources>
        <local:BoolToVisibleOrHidden x:Key="BoolToVisConverter" Collapse="True" />
        <LinearGradientBrush x:Key="LightBrush" StartPoint="0,0" EndPoint="0,1">
            <GradientBrush.GradientStops>
                <GradientStopCollection>
                    <GradientStop Color="#FFF" Offset="0.0"/>
                    <GradientStop Color="#EEE" Offset="1.0"/>
                </GradientStopCollection>
            </GradientBrush.GradientStops>
        </LinearGradientBrush>
    </UserControl.Resources>

3. Listview:

<ListView
            Name="lbMainMenu"
            Grid.Row="2"
            FontSize="17"            
            Width="209"
            Margin="2,3,0,3"           
            PreviewMouseLeftButtonUp ="lbMainMenu_PreviewMouseLeftButtonUp" >
            <ListView.Items>
                <ListViewItem Selected="Addministartion_Selected">
                    <StackPanel Name="stkPanel" Orientation="Horizontal">
                            <TextBlock
                                Name="lblScreenName"
                                Grid.Row="0"
                                Grid.Column="0"
                                Text="Administration" />
                            <Image
                                Grid.Row="0"
                                Grid.Column="1"
                                HorizontalAlignment="Right"
                                Margin="53,0,0,0"
                                Source="/Assets/arrow.png"
                                />                       
                    </StackPanel>
                </ListViewItem>

            <ListView.ItemContainerStyle>
                <Style TargetType="ListViewItem">
                    <Setter Property="Background" Value="{StaticResource LightBrush}"  />
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Cursor" Value="Hand" />
                        </Trigger>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="Background" Value="Green"  />
                            <Setter Property="FontWeight" Value="Bold" />
                            <Setter Property="FontStyle" Value="Italic" />
                        </Trigger>                       
                    </Style.Triggers>                   
                </Style>
            </ListView.ItemContainerStyle>
            <ListView.Background>
                <LinearGradientBrush   EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#666666" Offset="1"/>
                    <GradientStop Color="#999999" Offset="0.5"/>
                </LinearGradientBrush>
            </ListView.Background>
        </ListView>

4. Add Following Line Image:

Visibility="{Binding Converter={StaticResource BoolToVisConverter}, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}, AncestorLevel=1},Path=IsSelected}"

5. Example:

 <Image
                                Grid.Row="0"
                                Grid.Column="1"
                                HorizontalAlignment="Right"
                                Margin="127,0,0,0"
                                Source="/Assets/arrow.png"
                                Visibility="{Binding Converter={StaticResource BoolToVisConverter}, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}, AncestorLevel=1},Path=IsSelected}"
                            />


How to Close parent window from a User Control in WPF

 Window parent = Window.GetWindow(this);
 parent.Close();