annotation and reflection
@Retention(RetentionPolicy.RUNTIME)
public @interface DataContract {
String testToCall();
}
@DataContract(testToCall="Test")
public enum Cat {
Red("r"),
Blue("B"),
Yellow("Y");
public void Test(int id){System.out.println("test called "+id);}
}
main(String[] args) {
Cat c3= Cat.Red;
DataContract a= c3.getClass().getAnnotation(DataContract.class);
Method m = c3.getClass().getMethod(a.testToCall(),int.class);
m.invoke(c3,3); }
File IO:
PrintWriter w= new PrintWriter(new FileWriter("c:\\..."));
w.println("line 1");
w.close();
FileReader r= new FileReader("c:\\...");
BufferedReader br= new BufferedReader(r);
CapReader cr = new CapReader(br);
System.out.println(cr.readLine());
cr.close();
Path p=Paths.get(uri);
Path p1=Paths.get(uri+"1");
Path p2=Paths.get(uri);
Files.copy(p, p1);
Files.deleteIfExists(p);
Files.move(p1, p2);
Collections
List<Integer> list2=Arrays.asList(1,2,3,4);
Set<Integer> s= new HashSet<Integer>();
Queue<String> q= new LinkedList<String>();
q.offer("a"); q.poll(); q.peek();
\Map<Integer,Dog<Sex>> dogMap= new HashMap<Integer,Dog<Sex>>();
dogMap.put(1, new Dog<Sex>(null));
dogMap.get(1).Get();
Cat c= Cat.Red; //enum is class and has collection
for(Cat c1 : Cat.values()) System.out.println(c1);
Threading --by extends
Task t= new Task(); t.start(); // run()=sync start=async.
for (int i=0;i<100;i++) println("Main Thread run "+Thread.currentThread().getId());
public class Task extends Thread {
@Override public void run() {super.run();
for (int i=0;i<100;i++) Thread.sleep(1000);
println(Thread.currentThread().getId()+" not blocking main thread "+i);
Threading by Runnable
public class Task implements Runnable { @Override public void run(){same code}}
Task t= new Task(); Thread th= new Thread(t); th.start(); // explicit new thread
Threading by Executor
ExecutorService exec= Executors.newFixedThreadPool(3);
ExecutorService exec= Executors.newSingleThreadExecutor();
exec.submit(tRunnable);
exec.shutdown();
Synchronization at Method level
public class HW implements Runnable { static int counter=0;
public static void main(String[] args) {
ExecutorService exec= Executors.newFixedThreadPool(100);
HW h=new HW(); for(int i=0;i<10;i++) exec.submit(h);
exec.shutdown(); }
@Override
public synchronized void run() { counter++;
println("Thread Sync "+Thread.currentThread().getId()+" "+counter);}
maven mvn clean compile packge JAVA_HOME MAVEN_HOME
Thursday, March 31, 2016
Java First Braindump
Wednesday, March 30, 2016
Think Design Pattern in psuedo-code
Design pattern are abstract and hard to explain in words. But code seems simple
Visitor -- IAccept IVisitor
public interface IVisitor { Visit(Stock s);Visit(Option o);}
public interface IAccpet { void Accept(IVisitor v);}
public class Option : IAccpet {
public void Accept(IVisitor v) { v.Visit(this);}
}
public class Stock : IAccpet {
public void Accept(IVisitor v) {v.Visit(this); }
}
public class PnLVisitor : IVisitor {
void Visit(Option o) { } void Visit(Stock s) { } }
public class Trader
{
List<IAccpet> _holdings = new List<IAccpet>() { new Stock(), new Option() };
void CalcPnl() { foreach (var h in _holdings) h.Accept(new PnLVisitor()); }
}
Decorator---avoid sub-classing by composition/Wrapper
// eg. BufferStream(NetwokStream) since NS no buf
abstract class BaseComponent { }
class Decorator
{
protected BaseComponent _base;
// need to pass in concrete one
public Decorator(BaseComponent b){_base = b;}
}
Strategy --extend not modify
// new Strat extend for the same ctx
// avoid switch statement, call svc varying strat
public interface IStrategy { double Calculate();}
public class OptoinStrategy : IStrategy {
public OptoinStrategy(Context ctx) {}
public double Calculate(){return strategyValue;}
}
public class Context { }
public class Service {
IStrategy _strat;
public Service(IStrategy strat){ _strat = strat;}
public double Calc(){return _strat.Calculate();}
}
Think threading in pseudo-code
Threading primitives, Algorithm are better described in code
PLinq=AsParallel+With options
static void p_linq_as_parallel()
{
var rng = Enumerable.Range(3, 1000000000 - 3).AsParallel();
var primes = rng.Where(r => Enumerable.Range(2, (int) Math.Sqrt(r)).AsParallel().All(i => r%i > 0));
}
CountDown Rendezvous
static CountdownEvent _ce= new CountdownEvent(2);
static void count_down_2()
{
new Thread((d) =>
{
Thread.Sleep(3000);
Console.WriteLine("signal/wait after 3 sec, Id={0}",
Thread.CurrentThread.ManagedThreadId);
_ce.Signal();
_ce.Wait();
}).Start(); //immediate start no more sleep
Console.WriteLine("immed signal but have to wait,Id={0}",
Thread.CurrentThread.ManagedThreadId);
_ce.Signal();
_ce.Wait();
Console.WriteLine("all signaled so proceed");
}
Reader/Writer Lock = Monitor +upgrade+policy
// ReaderWriterLockSlim is 2x slower than lock
private static List<int> _shared_data = new List<int>();
private static ReaderWriterLockSlim _rw = new ReaderWriterLockSlim();
static void reader_writer()
{
//multi- reader and writer
new Thread(read_intermittent_continously).Start(); //muti-reader
new Thread(read_intermittent_continously).Start();
new Thread(write_occationa_continously).Start(); //muti-reader
new Thread(write_occationa_continously).Start();
}
static void read_intermittent_continously()
{
while (true)
{
_rw.EnterReadLock();
foreach (var i in _shared_data) { Thread.Sleep(10);}
_rw.ExitReadLock();
}
}
static void write_occationa_continously()
{
while (true)
{
int i = (new Random()).Next();
if (!_shared_data.Contains(i))
{
_rw.EnterWriteLock();
_shared_data.Add(i);
_rw.ExitWriteLock();
}
// need to read before upd=upgradeable
_rw.EnterUpgradeableReadLock();
int ii = _shared_data[0];
_rw.EnterWriteLock();
// do some updates
_rw.ExitWriteLock();
_rw.ExitUpgradeableReadLock();
Thread.Sleep(300);
}
}
static void nested_lock()
{
//var rw = new ReaderWriterLockSlim(); runtime exception, need policy
var rw = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
rw.EnterReadLock();
rw.EnterReadLock();
rw.ExitReadLock();
rw.ExitReadLock();
}
Barrier=Rendezvous= Countdown repeatedly
static Barrier _barrier = new Barrier(3);
static Action _act = () => {
for (int i = 0; i < 5; i++)
{
Console.Write(i + " ");
_barrier.SignalAndWait();
}
};
static void setup_rendezvous()
{
// output 000111222333444 so block till all 3 get there
new Thread(()=> { _act(); } );
new Thread(() => { _act(); });
new Thread(() => { _act(); });
}
Tuesday, March 29, 2016
Self host Nuget Server or Gallery and Nuget tools
There are 3-ways to setup Nuget, dir, WebApp, Nuget Gallery Repository== IIS Server or Local Dirtory or Nuget Gallary ASP.Net empty WebApp, install-package nuget.server => ur own nugget local Nuget Galary=nuget.org open source download Runs as WebSite+Sql Express. Nuget Gallery Web Page=NugetExplorer e.g. upload NugetExplorer--Win Desktop App GitHub build need 7.1 SDK, CodePlex has binary Create .nupkg file--NugetExplorer->Content->Meta->Tag- --> Dependency-->need to know ur own Dependencies rest dependencies pickup by Nuget Server NuGet.exe command Line tool--regular cmd not PS1 NugetExplorer--Open->"Nuget Command Line tools"--Download open nupkg to get NugGet.exe saved to c:\tools nugget.exe setApiKey nugget.exe publish mypackage.1.0.0.0.nupkg nuget push m.1.0.nupkg -s http://localhost:4222/ MYKEY PS1 Get-Package -ListAvailable copy package localfeed -updates LinqPad see Nuget Package install-package uninstall-package get-help nuget install-package -examples get-package -filter jq -project prj1
Set up Custom Control for Theme and Prefix AutoGen
Theme vs Skin --- Window build in Aero2.NormalColor.xaml, Classic.Xaml
Skin need code or xaml to load from xmal file to a scope
<Window.Resources>
<ResourceDictionary Source=""></ResourceDictionary>
</Window.Resources>
Style in Custom Control theme must be referenced by Component Res key
This style only applied inside Control never outside so this is not skinning
Classic.xaml/Areo.NormalColor.xaml under Theme dir
<Style TargetType="{x:Type Border}"
x:Key="{ComponentResourceKey
TypeInTargetAssembly={x:Type loc:CustomControl1},
ResourceId={x:Type Border}}">
<Setter Property="Background" Value="Red"></Setter>
</Style>
Generic.xaml use the style by Compo key
<Border Style="{DynamicResource {ComponentResourceKey
TypeInTargetAssembly={x:Type local:CustomControl1},
ResourceId={x:Type Border}}}">
</Border>
Note Microsoft build-in Theme applied to OS elements, Window Chrome, etc, not WPF
so no key needed. Windows theme only affect WPF Aero, Areo2, Classic, Lunar...
Control Panel..Personalization theme change
need Assembly Attribute to locate theme
[assembly:ThemeInfo(
ResourceDictionaryLocation.SourceAssembly, // theme
ResourceDictionaryLocation.SourceAssembly // generic
)]
design drag from Toolbox auto gene prefix
[assembly:XmlnsPrefix("http://jqd/","wpf")]
[assembly: XmlnsDefinition("http://jqd/", "WpfCustomControlLibrary1")]
to avoid verbose Component key use static class
public static class ShareResources {
static ComponentResourceKey _style1Key = new ComponentResourceKey
(typeof(CustomControl1), "style1");
public static ComponentResourceKey Style1Key
{ get { return _style1Key; }}}
<Border Style="{x:Static local:ShareResources.Style1Key}" />
Monday, March 28, 2016
Xaml Triggers and VisualState
DataTemplate/ControlTemplate/Style has triggers
Tigger can do setter, Enter exit action
MultiDataTrigger and MultiTrigger both have .Conditions
StoreBoard.Target=BackGround.(SolidBrush.Color)
This breaks the rule that code should not know xaml view
Xaml can only define Vstate need code behind to move
each state can have storeboard for transition effect
<ControlTemplate.Triggers>
<Trigger Property="" >
<Setter />
</Trigger>
<EventTrigger>
<BeginStoryboard>
<Storyboard></Storyboard>
</BeginStoryboard>
<EventTrigger.EnterActions>
</EventTrigger.EnterActions>
<EventTrigger.ExitActions>
<StopStoryboard>
</StopStoryboard>
</EventTrigger.ExitActions>
</EventTrigger>
<DataTrigger>
<DataTrigger.EnterActions>
<BeginStoryboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<StopStoryboard></StopStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
<DataTemplate>
<DataTemplate.Triggers>
</DataTemplate.Triggers>
</DataTemplate>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
</MultiDataTrigger.Conditions>
</MultiDataTrigger>
<MultiTrigger>
<MultiTrigger.Conditions>
</MultiTrigger.Conditions>
</MultiTrigger>
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Name="PART_border">
<ContentPresenter></ContentPresenter>
<VisualStateManager.VisualStateGroups>
<VisualState Name="normal"/>
<VisualState Name="MouseOver" >
<Storyboard Storyboard.TargetProperty="" Storyboard.TargetName="" />
<VisualState>
</VisualStateManager.VisualStateGroups>
</Border>
VisualStateManager.GoToState(this, "normal", true);
WCF custom control--inject into WPF and MVVM Command System
Execute/CanExecute=ICommand=RoutedCmd
route only, no app code, need to find cmdbinding up VTree
Decoupled Design. DelegateCommand, ApplicationCommand implements ICmd
<Button Command="AppCmds.Cut" /> <Window.CmdBindings> has app code
if(..) e.CanExec=true
<CmdBdg Executed="codebhd_appCode" CanExec="cdbh"/> note Execute(d).
routing without xaml VTree
--- target Binding, could be element outside up-VTree
<Button Command="Cut" CmdTarget={Binding Elem=_tb1}
--- or OnApplyTemplate() inject code
btn.Cliked +=(s,e)=>{ApplicationCommands.Cut.Execute(null,__tb1);}
Custom Routed Command --need to set CmdBinding somewhere
static class CmdHost { static RoutedCmd CustCmd;}
public CustomControl1() {
CommandBindins.Add(new CommandBinding(CmdHost.CustCmd, Exec,CanExec));
now CustCmd is injected into WPF Command System to enable the following:
(1) user <Button Command="CmdHost.CustCmd" Target="_ctl1"/>
(2) user Code Behind {Cmd.Host.CustCmd.Exec("Text RontedCmd(param,tgt");}
(3) ctr itself Exec(sender, e) { _ctl1 is updated here}
Custom Control must Implements ICommandSource to support MVVM
propdep snippet, manual modify ICommandSource
install-package relaycommand bring down source
install-package netfx-system.windows.input.delegatecommand
DelegateCommand have ()=>true for CanExec
[TemplatePart(Name = "PART_BDR", Type = typeof(TextBlock))]
public class CustomControl1 : ContentControl, ICommandSource
{
#region Minimum MVVM support---DP Cmd, OnApplyTemp hookup and
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
Border b = GetTemplateChild("PART_border") as Border;
b.MouseLeftButtonDown += (s, e) => {
if (Command is RoutedCommand) (Command as RoutedCommand).Execute(CommandParameter, CommandTarget);
else Command.Execute(CommandParameter);
};
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand),
typeof(CustomControl1), new PropertyMetadata((ICommand)null,
new PropertyChangedCallback(OnCommandChanged)));
[TypeConverter(typeof(CommandConverter))]
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
#endregion
#region Only for CanExecute =IsEnabled from VM DelegateCommand
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var cc = d as CustomControl1;
if(cc!= null)
{
cc.OnCommandChanged((ICommand)e.OldValue,(ICommand)e.NewValue);
}
}
EventHandler _persistHandleToAvoidGC;
protected virtual void OnCommandChanged(ICommand oldCmd, ICommand newCmd) // future extension point
{
HookUnhookCommand(oldCmd, newCmd); //hook/unhook for mem clean up
}
private void HookUnhookCommand(ICommand oldCmd, ICommand newCmd)
{
_persistHandleToAvoidGC = new EventHandler((s,e)=> {
// finnally, disable ctl through cmd.CanExe to VM DelegateCmd ()=>T/F
IsEnabled = Command.CanExecute(CommandParameter);
});
if(newCmd!=null) newCmd.CanExecuteChanged += _persistHandleToAvoidGC;
if (oldCmd != null) oldCmd.CanExecuteChanged -= _persistHandleToAvoidGC;
}
#endregion
#region CmdParam/Target are related to WPF Routed Cmd, not MVVM
public object CommandParameter
{
get { return (object)GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.Register("CommandParameter", typeof(object), typeof(CustomControl1), new PropertyMetadata(null));
public IInputElement CommandTarget
{
get { return (IInputElement)GetValue(CommandTargetProperty); }
set { SetValue(CommandTargetProperty, value); }
}
public static readonly DependencyProperty CommandTargetProperty =
DependencyProperty.Register("CommandTarget", typeof(IInputElement), typeof(CustomControl1), new PropertyMetadata(null));
#endregion
}
}
<cc:CustomControl1 Command="{Binding TestCommand}" Background="Transparent" />
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
Loaded += (s,e) => // INPC need to set in loaded
{
TestCommand = new DelegateCommand(() =>
{ MessageBox.Show("Command Triggered"); },
() => false); //true=CanExecute
};
}
public event PropertyChangedEventHandler PropertyChanged;
private DelegateCommand _testCommand;
public DelegateCommand TestCommand
{
get { return _testCommand; }
set
{
_testCommand = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("TestCommand"));
}
}
}
Subscribe to:
Posts (Atom)