We need to implement custom software analytics to trace the usage of the application. We have a common Command base class so the idea if to trace there something that allows us to know which command has been executed.  Consider the following sample code on a WPF Window with 1 Button:  public partial class MainWindow : Window {     private readonly Command _commandName = new Command();      public MainWindow()     {         InitializeComponent();     }      private void Button_Click(object sender, RoutedEventArgs e)     {         _commandName.Execute();     } }  public class Command {     public void Execute()     {         MessageBox.Show(this.GetCommandName());         // ....     }      private string GetCommandName()     {         string commandName = null;          MethodBase method = new StackTrace(new StackFrame(2)).GetFrame(0).GetMethod();         Type callingType = method.DeclaringType;          if (callingType != null)         {             IList&lt;FieldInfo&gt; variables = callingType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.GetField | BindingFlags.Instance).Where(f =&gt; f.FieldType == typeof(Command)).ToList();              if (variables.Count == 1)             {                 commandName = variables[0].Name;             }         }          return commandName;     } }   This code will show the variable name but only if there is one Command variable on the calling type. Is there a way of getting the calling variable name directly without going thru reflection?  The output of this code is (and should be) _commandName not Button_Click.
30039
When logging in C#, how can I learn the name of the method that called the current method? I know all about System.Reflection.MethodBase.GetCurrentMethod(), but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, something like Assembly.GetCallingAssembly() but for methods.
8570
I am running a program and want to see what its return code is (since it returns different codes based on different errors).  I know in Bash I can do this by running     echo $?   What do I do when using cmd.exe on Windows?
44149
I'm experimenting with the  feature, and embedding it in a Visualforce page, from where I hoped I would have some control over the canvas.  Now, the apex:canvasApp has a property called  and it's description says that they're parameters passed to the canvas app.    When I don't use the parameters attribute the canvas page draws normally, and using firebug I can see the call to the ip address of the canvas app. But for it to be useful to me I need to pass some parameters to the canvas page and when I do use the parameters attribute the canvas simply does not show, and in firebug it does not show any call to the ip of the canvas.  How are these parameters passed or how can one catch them? Using firebug, in the call to the ip of the canvas app, I can't see any of the parameters that I'm trying to pass.  Here's the simple code I'm experimenting with:  &lt;apex:page &gt; &lt;apex:canvasApp applicationName="Test Canvas" height="400px" width="750px" parameters="{vst_cli: '1293'}" /&gt; &lt;/apex:page&gt;   Inside the parameters attribute I've tried some different things: "{vst_cli: '1293'}" "{vst_cli: 1293}" "{'vst_cli': '1293'}" All of which had the same effect.  Any help or pointers will be welcome.  Thanks in advance.
97172
Hi i am trying to write script for display list of records from wrapper class.   @remoteaction     public static wrappercls getaccounts(){         string account = 'select id,name,accountnumber from account';         listacc = database.query(account);         count = listacc.size();         system.debug('#####'+count);         wrappercls wra = new wrappercls(count,listacc);         return wra;     }      public class wrappercls{         public integer count11;         public list&lt;account&gt; account;          public wrappercls(integer count11,list&lt;account&gt; account){             this.count11 = count11;             this.account = account;         }     }    This class returns list of account records and record count parameter.Need to display these records in page.Is it possible if possible Please help me on this..  Script  &lt;script&gt;   function getallaccounts(){     exremote.getaccounts(         function(result,event){             if(event.status){              }             else {              }        },{escape:true}     ); } &lt;/script&gt;   Thanks in Advance...
28780
I'm looking for a tool or method to find out what command line parameters have been passed to a program, for example when it was run by another program (launcher-application scenario).
52358
I'm writing an application that can be started either as a standard WinForms app or in unattended mode from the command-line. The application was built using the VS 2k5 standard WinForms template.  When the application is executed from the command-line, I want it to output information that can be captured by the script executing the application. When I do this directly from Console.WriteLine(), the output does not appear, although it can be captured by piping to a file.  On the other hand, I can force the application to pop up a second console by doing a P/Invoke on AllocConsole() from kernel32. This is not what I want, though. I want the output to appear in the same window the application was called from.  This is the salient code that allows me to pop up a console from the command line:  &lt;STAThread()&gt; Public Shared Sub Main()      If My.Application.CommandLineArgs.Count = 0 Then         Dim frm As New ISECMMParamUtilForm()         frm.ShowDialog()     Else         Try             ConsoleControl.AllocConsole()             Dim exMan As New UnattendedExecutionManager(ConvertArgs())             IsInConsoleMode = True             OutputMessage("Application started.")             If Not exMan.SetSettings() Then                 OutputMessage("Execution failed.")             End If         Catch ex As Exception             Console.WriteLine(ex.ToString())         Finally             ConsoleControl.FreeConsole()         End Try      End If  End Sub  Public Shared Sub OutputMessage(ByVal msg As String, Optional ByVal isError As Boolean = False)     Trace.WriteLine(msg)     If IsInConsoleMode Then         Console.WriteLine(msg)     End If      If isError Then         EventLog.WriteEntry("ISE CMM Param Util", msg, EventLogEntryType.Error)     Else         EventLog.WriteEntry("ISE CMM Param Util", msg, EventLogEntryType.Information)     End If  End Sub
105634
Often I need to recall the different \tracing commands; and a couple of times I stumbled on some webpages that worked fine for me; sadly, I didn't keep them, and my searches don't take me there anymore.   So I thought I'd ask about links to where one can read a list of \tracing commands?   For instance,  mentions:  \tracingall \tracingassigns \tracingcommands \tracinggroups \tracingifs \tracinglostchars \tracingmacros \tracingnesting \tracingonline \tracingoutput \tracingpages \tracingparagraphs \tracingrestores \tracingstats \tracingscantokens   .. but, I'm pretty sure there was something like \tracingboxes (and not so sure if there was something like \tracingglues); yet I cannot find any resources mentioning those.
96218
I came across this code and wanted others to provide their point of view... is it good or bad ? ;)  Class ReportClass {  public string ReportName {get; set;} }   Then it was used as follows in code:  displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())   That is about the simplest form example I can give you. Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?  EDIT: I'm referring to the inplace assignment. Which I wasn't aware of until today
18114
I have a method with an out parameter that tries to do a type conversion. Basically:  public void GetParameterValue(out object destination) {     object paramVal = "I want to return this. could be any type, not just string.";      destination = null; // default out param to null     destination = Convert.ChangeType(paramVal, destination.GetType()); }   The problem is that usually someone would call this like:  string output; GetParameterValue(output);   This will fail because of:  destination.GetType()   destination is null, so we can't call .GetType() on it. We also can not call:  typeof(destination)   because destination is a variable name not a type name.  So is there any way to get the type of an object that is set to null? I would think there would have to be a way to know what type a storage location is without it being assigned anything.    Just to give a bit more info, I am trying to make a utility method that will grab the output parameters of an Oracle stored procedure. The issue is that DbParameter.Value is of type object.  What would be ideal would be for the developers to do something like:  string val = GetParameterValue("parameterName");   The notable thing is that there is no casting of types. In practice, you don't know the lparam of the "equals", so I went with:  string val; GetParameterValue("parameterName", out val);   And figured within the method, I would know the destination type of the output variable. I guess that was a bad assumption. As an alternative, I also wrote the method:  public T GetParameterValue&lt;T&gt;(string paramName)   So the developers can do:  string val = GetParameterValue&lt;string&gt;("parameterName");   I find the explicit "string" declaration to be repetitive, especially since in practice, the destination if probably an object property and the oracle data type could change (think ORM):  MyObj.SomeProp = GetParameterValue&lt;MyObj.SomeProp.GetType()&gt;("parameterName");   But again, if MyObj.SomeProp is null, that .GetType() call fails. The VM has to know the type of MyObj.SomeProp, even when its null, right? or else how would it catch cast exceptions?    To partially solve my own problem, I can do:  MyObj.SomeProp = GetParameterValue&lt;typeof(MyObj).GetField("SomeProp").GetType()&gt;("parameterName");   The whole idea was to not have to explicitly use the Type in more than one place, so that if the data type changes, it only has to be changed in the destination object (MyObj.SomeProp) and in the DB. There has to be a better way...
120233
I would like to be able to pass aarguments to operators that I am calling from panels/buttons but I do not know how to do that. At the moment I use "global" variables but they tend to make the code a bit like a puzzle since I need to constantly update them.  See the code below, in that example I would like to pass an argument (like ARG) to "object.simple_operator" when the button is clicked.  import bpy     def DO_SOMETHING(arg):      print(arg)  return  class SimpleOperator(bpy.types.Operator):     """Tooltip"""     bl_idname = "object.simple_operator"     bl_label = "Simple Object Operator"      @classmethod     def poll(cls, context):         return context.active_object is not None      def execute(self, context):         DO_SOMETHING(ARG)         return {'FINISHED'}    class MyPanel(bpy.types.Panel):      bl_label = "mypanel"     bl_idname = "OBJECT_PT_MyPanel"      def draw(self, context):          layout = self.layout          wm = context.window_manager          obj = context.object          row = layout.row()         row.operator('object.simple_operator')
65745
I have created an Apex InterfaceFactory that the user can use to get an instance of a specified implementation of an interface. For this I use the System.Type class. The actual name of the class can be set in a custom setting. I wanted to be able to pass some parameters to the constructor of the dynamically instantiated class. In short; this is the code I'm talking about:  public static MyInterface GetMyInterfaceImplementationByClassName(String settingName){     String implementationClassName;     Type t;     MyInterface implementation = null;      //get the actual class name from the custom setting     Interface_Implementations__c settings = Interface_Implementations__c.getInstance(settingName);      //just make sure there actually is a className found     if (settings != null &amp;&amp; settings.Class__c != null) {         implementationClassName = settings.Class__c;         //get the type object for the class name retrieved from the custom setting         t = Type.forName(implementationClassName);         //this line is where my question comes in; how can I pass parameters here         implementation = (MyInterface)t.newInstance();     }      return implementation; }
3927
I'm trying to set a variable inside my controller via an actionFunction, which is called by some Javascript, which is initially called by either by an actionPanel (with styleClass='btn') or a commandButton.  If the caller is the actionPanel then the variable updates reliably. However with the commandButton I can see the updated value flash briefly before reverting to its previous value. Maybe one out of every six clicks of the button actually causes the new value to stick. Sometimes it can take a dozen or more tries, regardless of click frequency.  Can someone please explain what's going on here?  PAGE  &lt;apex:page controller="MyController"&gt;     &lt;apex:form &gt;         &lt;apex:outputPanel id="panel"&gt;             &lt;apex:outputText value="MyString = {!MyString}"/&gt;             &lt;apex:actionFunction name="SetString" rerender="panel"&gt;                 &lt;apex:param name="param1" value="" assignTo="{!MyString}"/&gt;             &lt;/apex:actionFunction&gt;             &lt;script&gt;                 function JSetString() {                     SetString('{!MyString}' + '.');                 }             &lt;/script&gt;             &lt;apex:outputPanel onclick="JSetString()" styleClass="btn"&gt;                 Grow {!MyString} (works)             &lt;/apex:outputPanel&gt;             &lt;apex:commandButton onclick="JSetString()" value="Grow {!MyString} (unreliable)" rerender="panel"/&gt;         &lt;/apex:outputPanel&gt;     &lt;/apex:form&gt; &lt;/apex:page&gt;   CONTROLLER  global class MyController {      public MyController() { MyString = 'hello'; }      public String MyString {get;set;} }
59878
I want to pass an enum value as command parameter in WPF, using something like this:  &lt;Button      x:Name="uxSearchButton"      Command="{Binding Path=SearchMembersCommand}"      CommandParameter="SearchPageType.First"     Content="Search"&gt; &lt;/Button&gt;   SearchPageType is an enum and this is to know from which button search command is invoked.  Is this possible in WPF, or how can you pass an enum value as command parameter?
439
Consider:  namespace WindowsApplication1 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }          private void button1_Click(object sender, EventArgs e)         {             //int[] val = { 0, 0};             int val;             if (textBox1.Text == "")             {                 MessageBox.Show("Input any no");             }             else             {                 val = Convert.ToInt32(textBox1.Text);                 Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));                 ot1.Start(val);             }         }          private static void ReadData(object state)         {             System.Windows.Forms.Application.Run();         }          void setTextboxText(int result)         {             if (this.InvokeRequired)             {                 this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });             }             else             {                 SetTextboxTextSafe(result);             }         }          void SetTextboxTextSafe(int result)         {             label1.Text = result.ToString();         }          private static void SumData(object state)         {             int result;             //int[] icount = (int[])state;             int icount = (int)state;              for (int i = icount; i &gt; 0; i--)             {                 result += i;                 System.Threading.Thread.Sleep(1000);             }             setTextboxText(result);         }          delegate void IntDelegate(int result);          private void button2_Click(object sender, EventArgs e)         {             Application.Exit();         }     } }   Why is this error occurring?     An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Form1.setTextboxText(int)
118759
Question  I'm writing some code that needs to be able to get the values of the parameters from the method that called into the class. I know how to get all the way to the ParameterInfo[] array, but I don't know how to then get the values. Is this even possible?  If it is, I think it has something to do with using the MethodBody property from the MethodInfo object, which allows you to inspect the IL stream, including properties, but I don't know how to do it, and I haven't found applicable code on Google.  Code  // Finds calling method from class that called into this one public class SomeClass {     public static void FindMethod()     {         for (int i = 1; i &lt; frameCount; i++)         {             var frame = new StackFrame(i);             var methodInfo = frame.GetMethod();             if (methodInfo.DeclaringType != this.GetType())             {                 string methodName = frame.GetMethod().Name;                 var paramInfos = methodInfo.GetParameters();                  // Now what?? How do I get the values from the paramInfos                  break;             }             else if (i == frameCount - 1)             {                 throw new TransportException("Couldn't find method name");             }         }     } }
47409
I have run into an issue with WPF and Commands that are bound to a Button inside the DataTemplate of an ItemsControl. The scenario is quite straight forward. The ItemsControl is bound to a list of objects, and I want to be able to remove each object in the list by clicking a Button. The Button executes a Command, and the Command takes care of the deletion. The CommandParameter is bound to the Object I want to delete. That way I know what the user clicked. A user should only be able to delete their "own" objects - so I need to do some checks in the "CanExecute" call of the Command to verify that the user has the right permissions.  The problem is that the parameter passed to CanExecute is NULL the first time it's called - so I can't run the logic to enable/disable the command. However, if I make it allways enabled, and then click the button to execute the command, the CommandParameter is passed in correctly. So that means that the binding against the CommandParameter is working.  The XAML for the ItemsControl and the DataTemplate looks like this:  &lt;ItemsControl      x:Name="commentsList"     ItemsSource="{Binding Path=SharedDataItemPM.Comments}"     Width="Auto" Height="Auto"&gt;     &lt;ItemsControl.ItemTemplate&gt;         &lt;DataTemplate&gt;             &lt;StackPanel Orientation="Horizontal"&gt;                 &lt;Button                                                  Content="Delete"                     FontSize="10"                     Command="{Binding Path=DataContext.DeleteCommentCommand, ElementName=commentsList}"                      CommandParameter="{Binding}" /&gt;             &lt;/StackPanel&gt;                                 &lt;/DataTemplate&gt;     &lt;/ItemsControl.ItemTemplate&gt; &lt;/ItemsControl&gt;   So as you can see I have a list of Comments objects. I want the CommandParameter of the DeleteCommentCommand to be bound to the Command object.  So I guess my question is: have anyone experienced this problem before? CanExecute gets called on my Command, but the parameter is always NULL the first time - why is that?  Update: I was able to narrow the problem down a little. I added an empty Debug ValueConverter so that I could output a message when the CommandParameter is data bound. Turns out the problem is that the CanExecute method is executed before the CommandParameter is bound to the button. I have tried to set the CommandParameter before the Command (like suggested) - but it still doesn't work. Any tips on how to control it.  Update2: Is there any way to detect when the binding is "done", so that I can force re-evaluation of the command? Also - is it a problem that I have multiple Buttons (one for each item in the ItemsControl) that bind to the same instance of a Command-object?  Update3: I have uploaded a reproduction of the bug to my SkyDrive:
3800
I can't get to the bottom of this error, because when the debugger is attached, it does not seem to occur.  Collection was modified; enumeration operation may not execute  Below is the code. This is a WCF server in a Windows service. The method NotifySubscribers() is called by the service whenever there is a data event (at random intervals, but not very often - about 800 times per day). When a Windows Forms client subscribes, the subscriber ID is added to the subscribers dictionary, and when the client unsubscribes, it is deleted from the dictionary. The error happens when (or after) a client unsubscribes. It appears that the next time the NotifySubscribers() method is called, the foreach() loop fails with the error in the subject line. The method writes the error into the application log as shown in the code below. When a debugger is attached and a client unsubscribes, the code executes fine. Do you see a problem with this code? Do I need to make the dictionary thread-safe? [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class SubscriptionServer : ISubscriptionServer {     private static IDictionary&lt;Guid, Subscriber&gt; subscribers;      public SubscriptionServer()     {                     subscribers = new Dictionary&lt;Guid, Subscriber&gt;();     }      public void NotifySubscribers(DataRecord sr)     {         foreach(Subscriber s in subscribers.Values)         {             try             {                 s.Callback.SignalData(sr);             }             catch (Exception e)             {                 DCS.WriteToApplicationLog(e.Message,                    System.Diagnostics.EventLogEntryType.Error);                  UnsubscribeEvent(s.ClientId);             }         }     }          public Guid SubscribeEvent(string clientDescription)     {         Subscriber subscriber = new Subscriber();         subscriber.Callback = OperationContext.Current.                 GetCallbackChannel&lt;IDCSCallback&gt;();          subscribers.Add(subscriber.ClientId, subscriber);                  return subscriber.ClientId;     }      public void UnsubscribeEvent(Guid clientId)     {         try         {             subscribers.Remove(clientId);         }         catch(Exception e)         {             System.Diagnostics.Debug.WriteLine(&quot;Unsubscribe Error &quot; +                      e.Message);         }     } }