User talk:Jetmathew

Button with Contextmenu on click
 Button with Context Menu                <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen"> <DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/> </BooleanAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> </Style.Triggers> </Style> </Button.Style> </Button>

Form Lamda expression
public static List<LambdaExpression> GetLambdaExpression(Type objType, string field, Operator oprator, IList values) {         List<LambdaExpression> lstExp = new List<LambdaExpression>; LambdaExpression lmdExp = null; foreach (string itm in values) {             var param = Expression.Parameter(objType, field.Substring(1, (field.Length - 1))); ConstantExpression right = null; switch (field.Substring(0, 1)) {                 case "i": right = Expression.Constant(Convert.ToInt32(itm), typeof(int)); break; case "s": right = Expression.Constant(itm, typeof(string)); break; case "d": right = Expression.Constant(Convert.ToDouble(itm), typeof(double)); break; case "t": right = Expression.Constant(Convert.ToDateTime(itm), typeof(DateTime?)); break; case "b": right = Expression.Constant(Convert.ToBoolean(itm), typeof(bool)); break; default: break; }             var left = Expression.Property(param, field.Substring(1, (field.Length - 1))); BinaryExpression expr = null; switch (oprator) {                 case Operator.Equal: expr = Expression.Equal(left, right); lmdExp = Expression.Lambda(expr, param); break; case Operator.NotEqual: expr = Expression.NotEqual(left, right); lmdExp = Expression.Lambda(expr, param); break; case Operator.Greaterthan: expr = Expression.GreaterThan(left, right); lmdExp = Expression.Lambda(expr, param); break; case Operator.Greaterthanorequal: expr = Expression.GreaterThanOrEqual(left, right); lmdExp = Expression.Lambda(expr, param); break; case Operator.Lessthan: expr = Expression.LessThan(left, right); lmdExp = Expression.Lambda(expr, param); break; case Operator.Lessthanorequal: expr = Expression.LessThanOrEqual(left, right); lmdExp = Expression.Lambda(expr, param); break; case Operator.Assign: expr = Expression.Assign(left, right); lmdExp = Expression.Lambda(expr, param); break; case Operator.In: var methodContains = typeof(string).GetMethod("Contains", new[] { typeof(string) }); var filterContains = Expression.Call(left, methodContains, right); lmdExp = Expression.Lambda(filterContains, param); break; default: break; }             lstExp.Add(lmdExp); }         return lstExp; }

public List GetId(string field, Operator opr, string value) {          List obligors = new List ; List<LambdaExpression> exp = LINQ.GetLambdaExpression(typeof(Obligor), field, opr, new List { value }); PortfolioData.Obligors.ToList<Portfolio>.FindAll(delegate(Portfolio obl) { return Filter(obl, exp); }).ForEach(itm => obligors.Add(((Obligor)itm).ObligorId)); return obligors; } private bool Filter(Portfolio obligor, List<LambdaExpression> exp) {          foreach (LambdaExpression itm in exp) {              if (Convert.ToBoolean(itm.Compile.DynamicInvoke(obligor))) {                  recordCount = recordCount + 1; return true; }          }           return false; }

My Command
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input;

namespace WpfDict {  public class MyCommand: ICommand {

Action submit; Predicate _canExecute; public MyCommand(Action action, Predicate canExecute) {          submit = action; _canExecute = canExecute; }      public bool CanExecute(object parameter) {          return _canExecute(parameter); }      public void Execute(object parameter) {          submit(parameter); }      public event EventHandler CanExecuteChanged; } }

View Model
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections.ObjectModel; using System.Windows.Input; using System.Reactive.Linq; using System.Reactive.Concurrency; using System.Reactive.Subjects;

namespace WpfDict {  public class ViewModel {      OrderManager _order = new OrderManager; Subject<Man> orderSub = new Subject<Man>; public ViewModel {          this.Mans = new ObservableCollection<Man>; this.Mans.Add(new Man { Id = 100, Name = "Justin", Edit = new MyCommand(Submit, CanExecute) }); this.Mans.Add(new Man { Id = 200, Name = "Manoj", Edit = new MyCommand(Submit, CanExecute) });

this.SubmitBtn = new MyCommand(Submit, CanExecute); this.StartBtn = new MyCommand(Start, CanExecute); this.StopBtn = new MyCommand(Stop, CanExecute); this.CommandList = new List<ICommand>; CommandList.Add(new MyCommand(Submit, CanExecute)); CommandList.Add(new MyCommand(Submit, CanExecute)); this.Pages = new List<KeyValuePair<int, int>>; this.Pages.Add(new KeyValuePair<int, int>(10, 10)); this.Pages.Add(new KeyValuePair<int, int>(20, 20)); }      public ObservableCollection<Man> Mans { get; set; } private Dictionary<int, Man> MainList = new Dictionary<int, Man>; public ICommand SubmitBtn { get; set; } public ICommand StartBtn { get; set; } public ICommand StopBtn { get; set; } public List<ICommand> CommandList { get; set; } public List<KeyValuePair<int,int>> Pages { get; set; }

private void Submit(object param) {          this.Mans.Add(new Man { Id = 200, Name = "Manoj", Edit = new MyCommand(Submit, CanExecute) }); }      private bool CanExecute(object param) {          return true; }      private void Start(object param) {                    _order.Order += _order_Order; _order.Start; Observable.FromEventPattern<TickEventArgs>(_order, "Order").Select(itm=> itm.EventArgs.Item).Buffer(2).ObserveOnDispatcher.Subscribe(x => AddMan(x)); }

private void AddMan(IList<Man> itm) {                     foreach (var item in itm) {              MainList[item.Id]= item; if (this.Mans.Count <= 4) this.Mans.Add(item); else {                  var val= this.Mans.FirstOrDefault(mn => mn.Id == item.Id); if (val != null) {                      this.Mans.Remove(val); this.Mans.Add(val); this.Mans.OrderBy(ord => ord.Id); }              }           }                 }       void _order_Order(object sender, TickEventArgs e)       { }      private void Stop(object param) {          _order.Stop; }   }    public class Man {       public string Name {get;set;} public int Id {get;set;} public ICommand Edit { get; set; } }

public class OrderManager {       public event EventHandler<TickEventArgs> Order; private IDisposable _observer; public void Start {           Random rnd = new Random; if (this.Order != null) {               _observer = Observable.Interval(TimeSpan.FromSeconds(2)).Subscribe(x => Order(null, new TickEventArgs { Item = new Man { Id = rnd.Next, Name = "RX-" + x } })); }       }        public void Stop {           if (_observer != null) _observer.Dispose; }   }    public class TickEventArgs : EventArgs {       public Man Item { get; set; } } }

View
<Window x:Class="WpfDict.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.RowDefinitions> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <ListView Grid.Row="0" ItemsSource="{Binding Path=Mans}"> <ListView.View> <GridView > <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Path=Id}"></GridViewColumn> <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}"></GridViewColumn> <GridViewColumn Header="Action"> <GridViewColumn.CellTemplate> <DataTemplate> <StackPanel> <Button Command="{Binding Path=Edit}" Content="Edit"></Button> </StackPanel> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> </ListView> <Button Grid.Row="1" Width="50" Height="20" Content="Submit" Command="{Binding Path=SubmitBtn}" CommandParameter="{Binding ElementName=cmb, Path=SelectedValue}"></Button> <ComboBox Width="40" Height="30" Name="cmb" SelectedIndex="0" ItemsSource="{Binding Path=Pages}" Grid.Row="2" DisplayMemberPath="Key" ></ComboBox> <Button Grid.Row="3" Width="500" Height="30" Name="cmButton" > Button with Context Menu <Button.ContextMenu> <ContextMenu Name="cm" StaysOpen="true"> <MenuItem Header="File"/> <MenuItem Header="Save"/> <MenuItem Header="SaveAs"/> <MenuItem Header="Recent Files"> <MenuItem Header="ReadMe.txt"/> <MenuItem Header="Schedule.xls"/> </MenuItem> </ContextMenu> </Button.ContextMenu> <Button.Style> <Style TargetType="{x:Type Button}"> <Style.Triggers> <EventTrigger RoutedEvent="Click"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen"> <DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/> </BooleanAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> </Style.Triggers> </Style> </Button.Style> </Button>

</Grid> </Window>

To kill child Process when Parent dies - This example will work only in release mode or not from Visual studio
-- Job Manager Class

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace GUI {   using System; using System.Diagnostics; using System.Runtime.InteropServices;

namespace JobManagement {       public class JobManager : IDisposable {           [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern IntPtr CreateJobObject(IntPtr a, string lpName);

[DllImport("kernel32.dll")] static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, UInt32 cbJobObjectInfoLength);

[DllImport("kernel32.dll", SetLastError = true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);

[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool CloseHandle(IntPtr handle);

private IntPtr handle; private bool disposed;

public JobManager {               handle = CreateJobObject(IntPtr.Zero, null);

var info = new JOBOBJECT_BASIC_LIMIT_INFORMATION {                   LimitFlags = 0x2000 };               var extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION {                   BasicLimitInformation = info };

int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION)); IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length); Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);

if (!SetInformationJobObject(handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr, (uint)length)) throw new Exception(string.Format("Unable to set information. Error: {0}", Marshal.GetLastWin32Error)); }

public void Dispose {               Dispose(true); GC.SuppressFinalize(this); }

private void Dispose(bool disposing) {               if (disposed) return;

if (disposing) { }

Close; disposed = true; }

public void Close {              CloseHandle(handle); handle = IntPtr.Zero; }

public bool AddProcess(IntPtr processHandle) {               return AssignProcessToJobObject(handle, processHandle); }

public bool AddProcess(int processId) {               return AddProcess(Process.GetProcessById(processId).Handle); }

}

#region Helper classes

[StructLayout(LayoutKind.Sequential)] struct IO_COUNTERS {           public UInt64 ReadOperationCount; public UInt64 WriteOperationCount; public UInt64 OtherOperationCount; public UInt64 ReadTransferCount; public UInt64 WriteTransferCount; public UInt64 OtherTransferCount; }

[StructLayout(LayoutKind.Sequential)] struct JOBOBJECT_BASIC_LIMIT_INFORMATION {           public Int64 PerProcessUserTimeLimit; public Int64 PerJobUserTimeLimit; public UInt32 LimitFlags; public UIntPtr MinimumWorkingSetSize; public UIntPtr MaximumWorkingSetSize; public UInt32 ActiveProcessLimit; public UIntPtr Affinity; public UInt32 PriorityClass; public UInt32 SchedulingClass; }

[StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES {           public UInt32 nLength; public IntPtr lpSecurityDescriptor; public Int32 bInheritHandle; }

[StructLayout(LayoutKind.Sequential)] struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION {           public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation; public IO_COUNTERS IoInfo; public UIntPtr ProcessMemoryLimit; public UIntPtr JobMemoryLimit; public UIntPtr PeakProcessMemoryUsed; public UIntPtr PeakJobMemoryUsed; }

public enum JobObjectInfoType {           AssociateCompletionPortInformation = 7, BasicLimitInformation = 2, BasicUIRestrictions = 4, EndOfJobTimeInformation = 6, ExtendedLimitInformation = 9, SecurityLimitInformation = 5, GroupInformation = 11 }

#endregion

}

}

-- Main Class, Prime is an external exe.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Diagnostics; namespace GUI {   class Program {       static void Main(string[] args) {                      Process pr = new Process; ProcessStartInfo prs = new ProcessStartInfo; prs.FileName = @"prime.exe"; pr.StartInfo = prs; pr.Start;

JobManagement.JobManager mng = new JobManagement.JobManager; mng.AddProcess(Process.GetCurrentProcess.Handle); mng.AddProcess(pr.Handle); Console.ReadLine; }

} }

SQL PIVOT
DECLARE @cols as NVARCHAR(MAX); DECLARE @query AS NVARCHAR(MAX);

select @cols = STUFF (( SELECT (',[' + CONVERT(VARCHAR(8),MAX(asofdate), 112)+']') as MonthEnd from [PMPrimeDB].[dbo].[UpdsExposure] group by  SUBSTRING(CONVERT(VARCHAR(8),asofdate, 112) ,0,7) ORDER BY (',[' + CONVERT(VARCHAR(8),MAX(asofdate), 112) +']')  FOR XML PATH(), TYPE ).value('.', 'NVARCHAR(MAX)'), 1, 1, );

--select @cols = REPLACE(@cols,' ','-');

--print @cols

select @query ='select * from ( select (PM_+T1.[ExpTypeId]+_+ T1.[Ccy]+_+T1.expId) as FacilityId, T3.[RatingTTCBand] as TTCDG	, CONVERT(VARCHAR(8),T1.AsOfDate, 112) as asofdate	FROM [PMPrimeDB].[dbo].[UpdsExposure]	T1	INNER JOIN 	(select MAX(asofdate) as MonthEnd from [PMPrimeDB].[dbo].[UpdsExposure] group by  SUBSTRING(convert(varchar(10), AsOfDate, 112 ) ,0,7)) T2	ON T1.AsOfDate = T2.MonthEnd 		    AND T1.[PMAssetTypeCode] in (LOAN,BOND)      	AND T1.[ExpTypeId] IN (100,110,120,150,200,210,220,230,240,300,420,510,810,815)	INNER JOIN 				[PMPrimeDB].[dbo].[UpdsCompany] T3 ON (T1.BorrCompId = T3.CompId AND T1.asofdate = T3.asofdate)	) P1 pivot ( max(TTCDG) for asofdate in ('+ @cols +')) as AvgIncomePerDay'; print @query execute(@query);

SQL Server Date formats
http://www.sql-server-helper.com/tips/date-formats.aspx

custom button
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.Navigation; using System.Windows.Shapes;

namespace YesNoPopup1 {   public class YesNoPopup : Button {       static YesNoPopup {           DefaultStyleKeyProperty.OverrideMetadata(typeof(YesNoPopup), new FrameworkPropertyMetadata(typeof(YesNoPopup))); }       static ICommand action; public static readonly DependencyProperty YesActionProperty = DependencyProperty.Register("YesAction", typeof(ICommand), typeof(YesNoPopup),       new FrameworkPropertyMetadata(null, DefaultValueChangedCallback)); public static readonly DependencyProperty IsBusyProperty = DependencyProperty.Register("IsBusy", typeof(bool), typeof(YesNoPopup)); //FrameworkPropertyMetadataOptions.AffectsParentMeasure));

private static void DefaultValueChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)        { YesNoPopup _this = (d as YesNoPopup); action = _this.YesAction; _this.Click -= new RoutedEventHandler(_this_Click); _this.Click += new RoutedEventHandler(_this_Click); }

static void _this_Click(object sender, RoutedEventArgs e)        { //new Window1.Show; action.Execute(null); }

///        /// Gets or sets the Content. ///        /// The Content. public ICommand YesAction {           get { return (ICommand)GetValue(YesActionProperty); } set { SetValue(YesActionProperty, value); } }       ///         /// Gets or sets the Content. ///        /// The Content. public bool IsBusy {           get { return (bool)GetValue(YesActionProperty); } set { SetValue(YesActionProperty, value); } }   } }

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Input; using Microsoft.Practices.Prism.Commands; using Microsoft.Practices.Prism.ViewModel;

namespace ControlTest {  public class ViewModel : NotificationObject {      public ICommand Pop { get; set; } public bool IsBusy { get; set; }

public ViewModel {          this.Pop = new DelegateCommand(Message); }

private void Message {          //new Window1.Show; IsBusy = true; RaisePropertyChanged("IsBusy"); }   } }

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:CustomControl="clr-namespace:YesNoPopup1"> <Style TargetType="{x:Type CustomControl:YesNoPopup}"> <Style.Triggers> <Trigger Property="IsBusy" Value="true"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type CustomControl:YesNoPopup}"> <Grid> <Rectangle Fill="Blue" RadiusX="20" RadiusY="20"/> <Ellipse Fill="White" /> <ContentPresenter Content="{Binding}"> <ContentPresenter.ContentTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" Height="50"> <TextBlock Text="{Binding RelativeSource={RelativeSource        AncestorType={x:Type CustomControl:YesNoPopup}}, Path=Content }" Margin="5"/> <TextBox Text="I am busy" Margin="5" Width="100"/> <Button Content="Show Name" /> </StackPanel> </DataTemplate> </ContentPresenter.ContentTemplate> </ContentPresenter> </Grid> </ControlTemplate>

</Setter.Value> </Setter> </Trigger> <Trigger Property="IsBusy" Value="false"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type CustomControl:YesNoPopup}"> <Grid> <Rectangle Fill="Blue" RadiusX="20" RadiusY="20"/> <Ellipse Fill="White" /> <ContentPresenter Content="{Binding}"> <ContentPresenter.ContentTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" Height="50"> <TextBlock Text="{Binding RelativeSource={RelativeSource        AncestorType={x:Type CustomControl:YesNoPopup}}, Path=Content }" Margin="5"/> <TextBox Text="wwww" Margin="5" Width="100"/> <Button Content="Show Name" /> </StackPanel> </DataTemplate> </ContentPresenter.ContentTemplate> </ContentPresenter> </Grid> </ControlTemplate>

</Setter.Value> </Setter> </Trigger> </Style.Triggers> </Style> </ResourceDictionary>