private void miSendFeedback_Click(object sender, RoutedEventArgs e) { if (lvSW.SelectedItems.Count > 0) { try { GetSoftware oSelectedItem = ((GetSoftware)lvSW.SelectedItem); var vDB = Task.Run(() => { try { AnonymousDelegate update = delegate() { FeedbackForm oFeedBack = new FeedbackForm(); oFeedBack.Title = oSelectedItem.ProductName + " " + oSelectedItem.ProductVersion; oFeedBack.ShowDialog(); if (oFeedBack.hasFeedback) { RZRestAPI.Feedback(oSelectedItem.ProductName, oSelectedItem.ProductVersion, oSelectedItem.Manufacturer, "", oFeedBack.isWorking.ToString(), Properties.Settings.Default.UserKey, oFeedBack.tbFeedback.Text).ConfigureAwait(false);; } }; Dispatcher.Invoke(update); } catch { } }); } catch { } } }
private void miSendFeedback_Click(object sender, RoutedEventArgs e) { if (lvSW.SelectedItems.Count > 0) { try { GetSoftware oSelectedItem = ((GetSoftware)lvSW.SelectedItem); var vDB = Task.Run(() => { try { AnonymousDelegate update = delegate() { FeedbackForm oFeedBack = new FeedbackForm(); oFeedBack.Title = oSelectedItem.ProductName + " " + oSelectedItem.ProductVersion; oFeedBack.ShowDialog(); if (oFeedBack.hasFeedback) { RZRestAPIv2.Feedback(oSelectedItem.ProductName, oSelectedItem.ProductVersion, oSelectedItem.Manufacturer, oFeedBack.isWorking.ToString(), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name, oFeedBack.tbFeedback.Text, RZRestAPIv2.CustomerID).ConfigureAwait(false);; } }; Dispatcher.Invoke(update); } catch { } }); } catch { } } }
private IExpression ConvertToAnonymousDelegate(IMethodDefinition closureMethod, ITypeReference delegateType) { Contract.Requires(closureMethod != null); Contract.Requires(!(closureMethod is Dummy)); Contract.Requires(delegateType != null); AnonymousDelegate anonDel = new AnonymousDelegate(); anonDel.CallingConvention = closureMethod.CallingConvention; anonDel.Parameters = new List <IParameterDefinition>(closureMethod.Parameters); var body = this.GetCopyOfBody(closureMethod); if (this.closureFieldMapper != null) { this.closureFieldMapper.Traverse(body); } anonDel.Body = this.Rewrite(body); anonDel.ReturnValueIsByRef = closureMethod.ReturnValueIsByRef; if (closureMethod.ReturnValueIsModified) { anonDel.ReturnValueCustomModifiers = new List <ICustomModifier>(closureMethod.ReturnValueCustomModifiers); } anonDel.ReturnType = closureMethod.Type; anonDel.Type = delegateType; new LocalReadAndWriteCounter(this.numberOfAssignmentsToLocal, this.numberOfReferencesToLocal).Traverse(anonDel.Body); return(new ReparentAnonymousDelegateParametersAndLocals(this.host, this.containingMethod, closureMethod, anonDel).Rewrite(anonDel)); }
private void TSearch_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { AnonymousDelegate update = delegate() { tbSearch_LostFocus(sender, null); }; Dispatcher.Invoke(update); }
void oInstPanel_onEdit(object sender, EventArgs e) { AnonymousDelegate update = delegate() { try { bool bNoPreReqCheck = false; if (sender.GetType() == typeof(GetSoftware)) { GetSoftware oSelectedItem = (GetSoftware)sender; //Ignore PreRequisites if SHIFT is pressed if (Keyboard.Modifiers == ModifierKeys.Shift) { bNoPreReqCheck = true; } //Load Software details for a valid DeploymentType... SWUpdate oSW = new SWUpdate(oSelectedItem.ProductName, oSelectedItem.ProductVersion, oSelectedItem.Manufacturer, bNoPreReqCheck); //get Icon if (oSW.SW != null) { oSW.SW.Image = RZRestAPIv2.GetIcon(oSW.SW.IconHash); oNewPanel.OpenXML(oSW.SW); } tabNewSWSMI.Tag = tabWizard.SelectedItem; tabWizard.SelectedItem = tabNewSWSMI; } if (sender.GetType() == typeof(AddSoftware)) { AddSoftware oSelectedItem = (AddSoftware)sender; //Ignore PreRequisites if SHIFT is pressed if (Keyboard.Modifiers == ModifierKeys.Shift) { bNoPreReqCheck = true; } //Load Software details for a valid DeploymentType... SWUpdate oSW = new SWUpdate(oSelectedItem.ProductName, oSelectedItem.ProductVersion, oSelectedItem.Manufacturer, bNoPreReqCheck); oNewPanel.OpenXML(oSW.SW); tabNewSWSMI.Tag = tabWizard.SelectedItem; tabWizard.SelectedItem = tabNewSWSMI; } } catch { } }; Dispatcher.Invoke(update); }
static void Main(string[] args) { // lambda operatorebis ganvitarebis stadiebi //AnonymousDelegate anonymousDelegate = new AnonymousDelegate(delegate (int x) { return x * 2; }); //AnonymousDelegate anonymousDelegate = delegate (int x) { return x * 2; }; AnonymousDelegate anonymousDelegate = (x) => (x * 2); Console.WriteLine(anonymousDelegate(4)); Console.WriteLine(anonymousDelegate.Invoke(4)); Console.ReadLine(); }
public AnonymousMethod() { //1) Not implicitly typed input parameters (not only "x", must be "int x") //2) Delegate keyword and statement block NEEDED //3) Not compiled in Expression tree AnonymousDelegate sqr = delegate(int x) { return(x * x); }; Console.WriteLine(sqr(3)); // //Useful for events: }
public static void Main(string[] args) { //Question 1 //Extention for string Console.WriteLine("\n**********Extension for string*******\n"); string s = "It's a wonderful day"; Console.WriteLine("String is: " + s); Console.WriteLine("No of words: " + s.wordCount()); Console.WriteLine("No of Caharcters: " + s.characterCount()); //Question 2 //Nullable type Console.WriteLine("\n**********Nullable types*******\n"); int?nullableValue = null; Console.WriteLine("Nullable value with null: " + nullableValue); nullableValue = 10; if (nullableValue.HasValue) { Console.WriteLine("Nullable value with value: " + nullableValue.Value); } //Question 3 //Anonymous methods Console.WriteLine("\n**********Anonymous delegates*******\n"); // Instantiate the delegate type using an anonymous method. AnonymousDelegate anonymousDelegate = delegate(string string1, string string2) { //Return the concatenated input string System.Console.WriteLine("Anonymous delegate called.The concatenated reult is:\n" + (string1 + string2)); }; // Make anonymous delegate call with 2 strings. anonymousDelegate("New", "York"); //Question 4 //Anonymous type with properties var anonymousProperty = new { Name = "Shylaja", ID = "440247", City = "Chennai" }; // Print the anonymous property. Console.WriteLine("\n**********Anonymous property*******\nName: " + anonymousProperty.Name + ", ID: " + anonymousProperty.ID + ", City: " + anonymousProperty.City); //Question 5 //Partial classes Console.WriteLine("\n**********Partial classes*******\n"); MainClassForFiles.MainClass(); }
private void OSCAN_OnSWRepoLoaded(object sender, EventArgs e) { try { //oDB = ((RZScan)sender).SoftwareRepository; AnonymousDelegate update = delegate() { btInstallSoftware.Content = "Install new Software"; btInstallSoftware.IsEnabled = true; }; Dispatcher.Invoke(update); } catch { } }
public override IExpression VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) { var o = this.semanticModel.GetSymbolInfo(node); var s = o.Symbol as MethodSymbol; if (s != null) { var m = (MethodDefinition)this.mapper.TranslateMetadata(s); var anonDelParameters = new List <IParameterDefinition>(m.Parameters); this.parameters.Add(m, anonDelParameters); IBlockStatement body; var b = node.Body; if (b is ExpressionSyntax) { var e = this.Visit(b); body = new BlockStatement() { Statements = new List <IStatement>() { new ReturnStatement() { Expression = e, } }, }; } else if (b is BlockSyntax) { var sv = new StatementVisitor(this.host, this.semanticModel, this.mapper, m, this); var b2 = (IBlockStatement)sv.Visit(b); body = b2; } else { throw new InvalidDataException("VisitSimpleLambdaExpression: unknown type of body"); } var anon = new AnonymousDelegate() { Body = body, CallingConvention = s.IsStatic ? CallingConvention.HasThis : CallingConvention.Default, Parameters = anonDelParameters, ReturnType = m.Type, Type = this.mapper.Map(this.semanticModel.GetTypeInfo(node).ConvertedType), }; return(anon); } throw new InvalidDataException("VisitSimpleLambdaExpression couldn't find something to return"); }
private void TSearch_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { AnonymousDelegate update = delegate() { if (tbSearch.IsFocused) { tbSearch_Search(sender, null); } else { tSearch.Stop(); } }; Dispatcher.Invoke(update); }
private void OSCAN_OnSWRepoLoaded(object sender, EventArgs e) { try { AnonymousDelegate update = delegate() { btInstallSoftware.Content = "Install new Software"; btInstallSoftware.IsEnabled = true; }; Dispatcher.Invoke(update); oSCAN.bCheckUpdates = true; oSCAN.SWScan(); } catch { } }
private void OSCAN_OnUpdScanCompleted(object sender, EventArgs e) { //Remove duplicates... lNewVersion = ((RZScan)sender).NewSoftwareVersions.GroupBy(x => x.ShortName).Select(y => y.First()).ToList(); //var distinctItems = items.GroupBy(x => x.Id).Select(y => y.First()); foreach (string sExclude in Properties.Settings.Default.UpdExlusion) { try { lNewVersion.RemoveAll(t => t.ShortName == sExclude); } catch { } } AnonymousDelegate update = delegate() { Mouse.OverrideCursor = null; lbWait.Visibility = Visibility.Hidden; btNextScan.IsEnabled = true; btBackScan.IsEnabled = true; if (lNewVersion.Count > 0) { btUpdateSoftware.IsEnabled = true; if (lNewVersion.Count == 1) { btUpdateSoftware.Content = "there is currently (" + lNewVersion.Count.ToString() + ") update available..."; } else { btUpdateSoftware.Content = "there are currently (" + lNewVersion.Count.ToString() + ") updates available..."; } } else { btUpdateSoftware.IsEnabled = false; btUpdateSoftware.Content = "there are currently no updates available..."; } //tabWizard.SelectedItem = tabMain; }; Dispatcher.Invoke(update); }
/// <summary> /// Main method. /// </summary> /// <param name="args"></param> static void Main(string[] args) { // Delegate instantiation operation obj = new operation(Addition); // output Console.WriteLine("Addition is={0}", obj(23, 27)); Console.WriteLine(); Console.WriteLine("*******************************Array of Delegates********************"); ArrayDelegates.ImplementDelegate(); Console.WriteLine("*******************************Anonymous Delegates********************"); AnonymousDelegate.ImplementDelegate(); Console.WriteLine("*******************************Anonymous Delegates********************"); MulticastDelegateExample.ImplementDelegate(); }
private void OSCAN_OnSWScanCompleted(object sender, EventArgs e) { lSoftware = ((RZScan)sender).InstalledSoftware; AnonymousDelegate update = delegate() { Mouse.OverrideCursor = null; lbWait.Visibility = Visibility.Hidden; btNextScan.IsEnabled = true; btBackScan.IsEnabled = true; if (lNewVersion.Count > 0) { btUpdateSoftware.IsEnabled = true; if (lNewVersion.Count == 1) { btUpdateSoftware.Content = "there is currently (" + lNewVersion.Count.ToString() + ") update available..."; } else { btUpdateSoftware.Content = "there are currently (" + lNewVersion.Count.ToString() + ") updates available..."; } } else { btUpdateSoftware.IsEnabled = false; if (((RZScan)sender).bCheckUpdates) { btUpdateSoftware.Content = "Scanning for updates... please wait !"; } else { btUpdateSoftware.Content = "there are currently no updates available..."; } } //tabWizard.SelectedItem = tabMain; }; Dispatcher.Invoke(update); }
public void Test4(string p1) { // Anonymous delegate : short way to write delegate. //AnonymousDelegate anonDelegate = new AnonymousDelegate( //delegate(string text) { // Console.WriteLine(text); //}); // Instead above, we use clearer way: Action or Func (These are built-in delegate) // anonymouse method //Action<string> anonDelegate = delegate (string text) //{ // Console.WriteLine(text); //}; // much more clearer way: Lambda expression with "goes to" operator // Action<string> anonDelegate = text => Console.WriteLine(text); // much much much more clearer way: Lambda expression with "goes to" operator AnonymousDelegate anonDelegate = text => Console.WriteLine(text); anonDelegate(p1); }
private void TaskUpdate() { //UILock.TryEnterReadLock(350); try { bool bInstalling = false; AnonymousDelegate update = delegate() { lvDL.ItemsSource = null; lvDL.ItemsSource = lDLTasks; lvDL.UpdateLayout(); }; Dispatcher.Invoke(update); if (lDLTasks.Count > 0) { if (lDLTasks.Count(t => !t.Installed) == 0) { AllDone(this, EventArgs.Empty); } } if (lDLTasks.Count(t => t.Installing) > 0) { bInstalling = true; tDelay.Interval = 800; tDelay.Start(); return; } foreach (DLTask oDL in lDLTasks.Where(t => t.AutoInstall && t.PercentDownloaded == 100 && !t.Error && !t.Installed && !t.Downloading && !t.WaitingForDependency && !t.Installing && !t.UnInstalled)) { try { Mutex mRes = null; if (!Mutex.TryOpenExisting(@"RuckZuckCM", out mRes)) { oDL.SWUpd.InstallCM(false, false).ConfigureAwait(false); } return; } catch { } } foreach (DLTask oDL in lDLTasks.Where(t => t.WaitingForDependency && t.PercentDownloaded == 100 && !t.Error && !t.Installed && !t.Downloading && !t.Installing && !t.UnInstalled)) { try { bool allDone = true; foreach (string sPreReq in oDL.SWUpd.SW.PreRequisites) { if (lDLTasks.Count(t => t.ShortName == sPreReq && !t.Installed && !t.Error) != 0) { allDone = false; } } if (allDone) { if (!bInstalling) { Mutex mRes = null; if (!Mutex.TryOpenExisting(@"RuckZuckCM", out mRes)) { oDL.SWUpd.InstallCM(false, false).ConfigureAwait(false); } return; } } else { if (!oDL.Downloading && !oDL.WaitingForDependency && oDL.AutoInstall) { if (!bInstalling) { Mutex mRes = null; if (!Mutex.TryOpenExisting(@"RuckZuckCM", out mRes)) { oDL.SWUpd.InstallCM(false, false).ConfigureAwait(false); } return; } } } } catch { } } tDelay.Interval = 300; tDelay.Start(); } catch { tDelay.Interval = 500; tDelay.Start(); } finally { //UILock.ExitReadLock(); } }
public void Invoke(AnonymousDelegate begin, EndInvokeAnonymousDelegate end) { _endInvokeDelegate = end; begin(); }
static void Main(string[] args) { // 基本 SampleDelegate a = new SampleDelegate(AddOne); // 暗黙の型変換も可能 SampleDelegate s = SubtractOne; // インスタンスメソッドも代入可能 var sampleClass = new SampleClass(); InstanceDelegate i = sampleClass.Show; // 複数のメソッドを代入可能(マルチキャストデリゲート) InstanceDelegate m = sampleClass.Show; m += sampleClass.Show; // 匿名関数を代入可能 AnonymousDelegate an = delegate(int param1, int param2) { Console.WriteLine("Called Anonymouse Function!!!"); Console.WriteLine($"result: {param1 + param2}"); Console.WriteLine(); }; // ラムダ式でも書ける an += (int param1, int param2) => { Console.WriteLine("Called Lambda Expression!!!"); Console.WriteLine($"result: {param1 + param2}"); Console.WriteLine(); }; // もっと簡単なラムダ式 an += (param1, param2) => { Console.WriteLine("Called Simple Lambda Expression!!!"); Console.WriteLine($"result: {param1 + param2}"); Console.WriteLine(); }; // ラムダ式の中身が一行ならさらに簡単に書ける an += (param1, param2) => Console.WriteLine("Called More Simple Lambda Expression!!!"); // デリゲートを介してメソッドを呼び出す a(123); s(100); i("test"); m("multi"); an(5, 6); /* デリゲートにはすでに用意してある型がある(汎用デリゲート) * Actionは、任意個の引数を取り、かつ、戻り値のないメソッドへのDelegate * Funcは、任意個の引数を取り、かつ、戻り値のあるメソッドへのDelegate * Predicateは、任意個の引数を取り、かつ、戻り値の型がBooleanであるようなメソッドへのDelegate * ほかにもConvertorやComparisonがある */ // 引数なし、戻り値あり Func <int> func_01 = () => { Console.WriteLine("Called Func<TResult> !!!"); Console.WriteLine(); return(0); }; // 引数1つ、戻り値あり Func <int, string> func_02 = tt => { var cal = tt + 2; Console.WriteLine("Called Func<T, TResult> !!!"); Console.WriteLine($"result: {cal}"); Console.WriteLine(); return(cal.ToString()); }; // 引数2つ、戻り値あり Func <int, int, string> func_03 = (aa, bb) => { Console.WriteLine("Called Func<T1, T2, TResult> !!!"); Console.WriteLine($"result: {aa + bb}"); Console.WriteLine(); return((aa + bb).ToString()); }; // 引数なし、戻り値なし Action action_01 = () => Console.WriteLine("Called Action !!!"); // 引数1つ、戻り値なし Action <string> action_02 = str => { Console.WriteLine("Called Action<T> !!!"); Console.WriteLine($"param: {str}"); Console.WriteLine(); }; // 引数2つ、戻り値なし Action <string, string> action_03 = (param1, param2) => { Console.WriteLine("Called Action<T1, T2> !!!"); Console.WriteLine($"param: {param1}, {param2}"); Console.WriteLine(); }; // 引数1つ、戻り値Bool Predicate <int> predicate_01 = param => { Console.WriteLine("Called Predicate<T> !!!"); Console.WriteLine($"result: {param > 5}"); return(param > 5); }; // 汎用メソッドを呼び出す func_01(); func_02(8); func_03(56, 44); action_01(); action_02("test"); action_03("test01", "test02"); predicate_01(9); // Linqをいろいろな呼び方をする var list = new List <string> { "aaa", "bbb", "ccc", "ddd", "eee", "fff" }; var whereResult = list.Where(w => w == "ddd"); whereResult = list.Where((w) => { return(w == "ccc"); }); whereResult = list.Where(sampleClass.LinqWhereFunction).ToList(); var findResult = list.FindAll(x => x == "fff"); findResult = list.FindAll(sampleClass.LinqFindFunction); // イベントの登録で使用する var eventClass = new EventClass((sender, eventArgs) => Console.WriteLine(eventArgs.Message)); // 冗長な書き方 //var eventClass = new EventClass(new EventHandler<MyEventArgs>((sender, eventArgs) => Console.WriteLine(eventArgs.Message))); // 非同期実行 Task.Run(() => eventClass.Start()).Wait(); // ラムダ式でかきたくない場合はキャストすれば使用可能 //Task.Run((Action)eventClass.Start).Wait(); Console.WriteLine("キーを押して終了。"); Console.ReadKey(); }
static void Main(string[] args) { Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.ThreadException += Application_ThreadException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; string sTitle = "Collection Commander"; bool bName = false; foreach (string sArg in args) { if (sArg.StartsWith("/name:", true, System.Globalization.CultureInfo.CurrentCulture)) { sTitle = sArg.Substring(sArg.IndexOf(":") + 1); bName = true; } if (string.Compare("/install", sArg, true) == 0) { Console.Write("Register Console Extensions..."); registerConsoleExtension(); Console.WriteLine("..Done."); return; } if (string.Compare("/uninstall", sArg, true) == 0) { Console.Write("Unregister Etensions...."); unregisterConsoleExtension(); Console.WriteLine("...Done."); return; } //From https://cmcollctr.codeplex.com/discussions/612941 by Mikesch // Usage: CMCollCtr /List:[COMPUTERNAME1],[COMPUTERNAME2],[COMPUTERNAME3] if (sArg.StartsWith("/List:", true, System.Globalization.CultureInfo.CurrentCulture)) { var computerList = sArg.Remove(0, 6).Split(','); MainForm pForm = new MainForm(); pForm.Text = sTitle; pForm.Show(); System.Threading.Thread.Sleep(200); try { AnonymousDelegate clearbinding = delegate() { pForm.computerBindingSource.Clear(); }; pForm.Invoke(clearbinding); foreach (var computerName in computerList) { AnonymousDelegate updatecounts = delegate() { pForm.computerBindingSource.AllowNew = true; Computer oComp = new Computer() { ComputerName = computerName }; pForm.computerBindingSource.Add(oComp); }; pForm.Invoke(updatecounts); } AnonymousDelegate updateBinding = delegate() { pForm.dataGridView1.DataSource = pForm.computerBindingSource; }; pForm.Invoke(updateBinding); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } Application.Run(pForm); } //From https://cmcollctr.codeplex.com/discussions/612941 by Mikesch // Usage: CMCollCtr /File:[Filename] if (sArg.StartsWith("/File:", true, System.Globalization.CultureInfo.CurrentCulture)) { var fileName = sArg.Remove(0, 6); MainForm pForm = new MainForm(); pForm.Text = sTitle; pForm.Show(); System.Threading.Thread.Sleep(200); try { AnonymousDelegate clearbinding = delegate() { pForm.computerBindingSource.Clear(); }; pForm.Invoke(clearbinding); var sr = new System.IO.StreamReader(fileName); string computerName; while ((computerName = sr.ReadLine()) != null) { AnonymousDelegate updatecounts = delegate() { pForm.computerBindingSource.AllowNew = true; Computer oComp = new Computer() { ComputerName = computerName }; pForm.computerBindingSource.Add(oComp); }; pForm.Invoke(updatecounts); } sr.Close(); AnonymousDelegate updateBinding = delegate() { pForm.dataGridView1.DataSource = pForm.computerBindingSource; }; pForm.Invoke(updateBinding); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } Application.Run(pForm); } if (sArg.StartsWith("/Path:", true, System.Globalization.CultureInfo.CurrentCulture)) { string sPath = sArg.Remove(0, 6); string sQuery = "SELECT * FROM SMS_R_SYSTEM WHERE ResourceID in (SELECT ResourceID FROM SMS_CM_RES_COLL_" + sPath.Split('=')[1] + ")"; string sScope = sPath.Split(':')[0]; if (!string.IsNullOrEmpty(Properties.Settings.Default.ServerDNSSuffix)) { try { sScope = sPath.Replace(sPath.Split('\\')[2], sPath.Split('\\')[2] + Properties.Settings.Default.ServerDNSSuffix); } catch { } } MainForm pForm = new MainForm(); pForm.Text = sTitle; pForm.Show(); System.Threading.Thread.Sleep(200); try { AnonymousDelegate clearbinding = delegate() { pForm.computerBindingSource.Clear(); }; pForm.Invoke(clearbinding); foreach (ManagementObject MO in new ManagementObjectSearcher(sScope, sQuery).Get()) { AnonymousDelegate updatecounts = delegate() { pForm.computerBindingSource.AllowNew = true; Computer oComp = new Computer(); oComp.ComputerName = MO["Name"].ToString(); try { oComp.ComputerName = ((string[])MO.Properties["ResourceNames"].Value)[0].ToString(); } catch { } pForm.computerBindingSource.Add(oComp); }; pForm.Invoke(updatecounts); } AnonymousDelegate updateBinding = delegate() { pForm.dataGridView1.DataSource = pForm.computerBindingSource; }; pForm.Invoke(updateBinding); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } Application.Run(pForm); } } if (args.Length == 0 || (bName & args.Length == 1)) { try { MainForm pForm = new MainForm(); pForm.Text = sTitle; Application.Run(pForm); } catch (Exception ex) { ex.Message.ToString(); } } }
internal ReparentAnonymousDelegateParametersAndLocals(IMetadataHost host, IMethodDefinition method, IMethodDefinition closureMethod, AnonymousDelegate anonymousDelegate) : base(host) { Contract.Requires(host != null); Contract.Requires(method != null); Contract.Requires(closureMethod != null); Contract.Requires(anonymousDelegate != null); this.method = method; this.closureMethod = closureMethod; this.anonymousDelegate = anonymousDelegate; }
public override void TraverseChildren(IMethodCall methodCall) { if (methodCall.MethodToCall.ResolvedMethod.IsSpecialName && methodCall.MethodToCall.Name.Value == "add_BackKeyPress") { // check if it is a back key handler and if it is... // NAVIGATION TODO this only catches really locally delegate expressions. If it is created before, we see it as a BoundExpression // NAVIGATION TODO and need (again) data flow analysis bool delegateIsIdentified = false; bool delegateIsAnonymous = false; PhoneCodeHelper.instance().OnBackKeyPressOverriden = true; IBlockStatement delegateBody = null; IMethodDefinition delegateMethodRef = null; if (methodCall.Arguments.Count() == 1) { IExpression delegateArg = methodCall.Arguments.First(); ICreateDelegateInstance localDelegate = delegateArg as ICreateDelegateInstance; if (localDelegate != null) { delegateIsIdentified = true; delegateMethodRef = localDelegate.MethodToCallViaDelegate.ResolvedMethod; SourceMethodBody body = delegateMethodRef.Body as SourceMethodBody; if (body != null) { delegateBody = body.Block; } PhoneCodeHelper.instance().KnownBackKeyHandlers.Add(delegateMethodRef); } AnonymousDelegate anonDelegate = delegateArg as AnonymousDelegate; if (anonDelegate != null) { delegateIsIdentified = true; delegateIsAnonymous = true; delegateBody = anonDelegate.Body; } // NAVIGATION TODO what if it has no body? if (delegateBody != null) { bool navigates = false, cancelsNav = false; ICollection <string> navTargets; parseBlockForNavigation(delegateBody, out navigates, out navTargets); if (navigates) { ICollection <Tuple <IMethodReference, string> > targets = null; if (!PhoneCodeHelper.instance().BackKeyNavigatingOffenders.TryGetValue(typeBeingTraversed, out targets)) { targets = new HashSet <Tuple <IMethodReference, string> >(); } foreach (string tgt in navTargets) { IMethodReference dummyRef = null; if (delegateIsAnonymous) { dummyRef = new Microsoft.Cci.MutableCodeModel.MethodReference(); (dummyRef as Microsoft.Cci.MutableCodeModel.MethodReference).ContainingType = typeBeingTraversed; (dummyRef as Microsoft.Cci.MutableCodeModel.MethodReference).Name = Dummy.Name; } targets.Add(Tuple.Create <IMethodReference, string>((delegateIsAnonymous ? dummyRef : delegateMethodRef), "\"" + tgt + "\"")); } PhoneCodeHelper.instance().BackKeyNavigatingOffenders[typeBeingTraversed] = targets; } parseBlockForEventCancellation(delegateBody, out cancelsNav); if (cancelsNav) { string reason = "(via delegate "; if (delegateIsIdentified) { reason += delegateMethodRef.ContainingType.ToString() + "." + delegateMethodRef.Name.Value; } else { reason += "anonymous"; } reason += ")"; PhoneCodeHelper.instance().BackKeyCancellingOffenders.Add(Tuple.Create <ITypeReference, string>(typeBeingTraversed, reason)); } } } if (!delegateIsIdentified) { PhoneCodeHelper.instance().BackKeyHandlerOverridenByUnknownDelegate = true; PhoneCodeHelper.instance().BackKeyUnknownDelegateOffenders.Add(typeBeingTraversed); } } base.TraverseChildren(methodCall); }