public ChartController(IHubConnectionContext <dynamic> clients)
        {
            Clients = clients;
            MethodDelegate metho = new MethodDelegate(this.start);

            metho.BeginInvoke(null, null);
        }
Пример #2
0
        private void FrmItemList_Load(object sender, EventArgs e)
        {
            method += new MethodDelegate(getList);
            int count = method();

            toolStripStatusLabel2.Text = count.ToString();;
        }
Пример #3
0
        /// <summary>
        /// Starts the main loop.
        /// </summary>
        public void Run()
        {
            // Start the main loop and continue until it's stopped
            m_running = true;
            while (m_running)
            {
                // Wait on Invoke or Stop methods to be called
                m_syncEvent.WaitOne();

                while (m_methodQueue.Count != 0)
                {
                    MethodDelegate method = (MethodDelegate)m_methodQueue.Dequeue();

                    try
                    {
                        // Perform the action
                        method();
                    }
                    catch (Exception e)
                    {
                        String msg = e.Message + " " + e.InnerException + " " + e.StackTrace;

                        // Send event
                        Safir.Logging.SendSystemLog(Safir.Logging.Severity.Critical,
                                                    "Unhandled Exception in MainLoop: " + msg);

                        // Terminate the application
                        //Instances.SelfInstance.MainModule.FatalError();
                    }
                }

                m_syncEvent.Reset();
            }
        }
 public MenuItem(int number, string text, MethodDelegate method = null, int depth = 5)
 {
     Number      = number;
     Text        = text;
     Depth       = depth;
     this.method = method;
 }
Пример #5
0
        public static void Main()
        {
            MethodDelegate deleg = new MethodDelegate(method);

            #region first way
            IAsyncResult asyncRes = deleg.BeginInvoke(4, null, null);
            IAsyncResult asyncRes2 = deleg.BeginInvoke(5, null, null);

            Console.WriteLine("do work");

            Console.WriteLine("when it need get the results");

            Console.WriteLine(deleg.EndInvoke(asyncRes2));
            Console.WriteLine(deleg.EndInvoke(asyncRes));
            #endregion

            #region second way
            AsyncCallback callback = new AsyncCallback(callbackMethod);
            object objectSuppliedState = new object();

            deleg.BeginInvoke(6, callback, objectSuppliedState);
            deleg.BeginInvoke(7, new AsyncCallback(callbackMethod2), new object[] { deleg, objectSuppliedState });

            eventt1.WaitOne();
            eventt2.WaitOne();
            #endregion
        }
Пример #6
0
 /*
  * 本节, 中示例提供对 BeginInvoke() 函数, 异步调用完成后系统执行回调委托。
  * 回调调用 EndInvoke() 并处理异步调用的结果。
  * 如果启动异步调用线程不需要处理结果是调用此调用模式很有用。
  * 异步调用完成后系统调用线程以外启动线程上调。
  * 若使用此调用模式, 作为第二到最后 - BeginInvoke() 函数的参数必须传递 AsyncCallback 类型的委托。
  * BeginInvoke() 还有最后参数键入 对象 到您可以将任何对象。 当它调用该对象可用于您回调函数。
  * 为此参数一个重要用途是以传递用于初始化调用该委托。
  * 回调函数然后使用与该委托 EndInvoke() 函数来完成调用。 此调用模式是所示。
  * */
 /// <summary>
 /// 异步方法完成后执行回调
 /// </summary>
 public static void DemoCallback()
 {
     MethodDelegate dlgt = new MethodDelegate(LongRunningMethod);
     int            iExecThread;
     AsyncCallback  asyncCallback = new AsyncCallback(MyAsyncCallback);
     IAsyncResult   iar           = dlgt.BeginInvoke(5000, out iExecThread, asyncCallback, dlgt);
 }
Пример #7
0
        /// <summary>
        /// Low now method
        /// </summary>
        /// <param name="errors">error list</param>
        public static void LogNow(List <string> errors)
        {
            var log = new ErrorLogFactory().GetErrorLogInstance();
            var callGenerateFileAsync = new MethodDelegate(log.LogError);

            callGenerateFileAsync.BeginInvoke(errors, null, null);
        }
Пример #8
0
        /// <summary>
        /// Sets the field used to determine the X axis
        /// </summary>
        /// <param name="expression">The name of the parameter to comprise the X axis</param>
        public void SetXAxis(string expression)
        {
            this.XAxis         = expression;
            this.XAxisGetValue = getExpressionEvaluator(expression);
            foreach (var l in Lines)
            {
                l.Plot.Remove(this);
            }
            Plot.XAxis1 = null;
            Plot.YAxis1 = null;

            // Re-generate all of the data
            foreach (var l in Lines)
            {
                l.SetExpression(this, l.Expression);
                l.Generate(this);
            }

            // Select the proper X axis and refresh the plot
            if (XAxis.Equals("Time"))
            {
                Plot.XAxis1 = TimeAxis;
            }
            Refresh();
        }
Пример #9
0
 public ConsoleCommand(string name, MethodDelegate method, string description, int tag)
 {
     this.name        = name;
     this.method      = method;
     this.description = description;
     this.tag         = tag;
 }
Пример #10
0
 public MethodMetadata(MethodDelegate methoddelegate, MethodCallback callback, bool validate, params Type[] inputtypes)
 {
     Delegate   = methoddelegate;
     InputTypes = inputtypes;
     Callback   = callback;
     Validate   = validate;
 }
Пример #11
0
        public static void CheckForException(Type exceptionType, string message, MethodDelegate tryCode, bool checkValidationException)
        {
            Dictionary <string, string> exceptionProperties = new Dictionary <string, string>();

            exceptionProperties.Add("Message", message);
            ExceptionHelpers.CheckForException(exceptionType, exceptionProperties, tryCode, checkValidationException);
        }
Пример #12
0
        /// <summary>
        /// 有了物品,有了方法,下面就是将两者结合起来的贪心算法GreedyAlgo
        /// </summary>
        /// <param name="problem"></param>
        /// <param name="greedyCallback"></param>
        public void CalculateResult(TagProblem problem, MethodDelegate greedyCallback)
        {
            int index         = 0;
            int currSumWeight = 0;

            //先选
            while ((index = greedyCallback(problem.objs, currSumWeight)) != -1)
            {
                if (problem.objs[index].Weight + currSumWeight <= problem.total)
                {
                    ////如果背包没有装满,还可以再装,标记下装进去的物品状态为1
                    problem.objs[index].Status = 1;
                    //把这个idx的物体的重量装进去,计算当前的重量
                    currSumWeight += problem.objs[index].Weight;

                    Console.WriteLine("index:{0},price:{1},weight:{2}", index, problem.objs[index].Price, problem.objs[index].Weight);
                }
                else
                {
                    //不能选这个物品了,做个标记2后重新选剩下的
                    problem.objs[index].Status = 2;
                }
                Console.WriteLine("currSumWeight:{0}", currSumWeight);
            }
        }
Пример #13
0
        public static void LogNow(List <string> strError)
        {
            IErrorLogging log = new ErrorLogFactory().GetErrorLogInstance();

            MethodDelegate callGenerateFileAsync = new MethodDelegate(log.LogError);
            IAsyncResult   ar = callGenerateFileAsync.BeginInvoke(strError, null, null);
        }
Пример #14
0
        public void PointerNullMethodDelegateParameter()
        {
            var            obj = new PointerHolder();
            MethodDelegate d   = obj.Method;

            d.DynamicInvoke(null, 0);
        }
Пример #15
0
        public void PointerMethodDelegateParameter(int value)
        {
            var            obj = new PointerHolder();
            MethodDelegate d   = obj.Method;

            d.DynamicInvoke(Pointer.Box(unchecked ((void *)value), typeof(byte *)), value);
        }
Пример #16
0
        //public DynamicMethod _normalClassDynamicMethod;
        //public NormalClass _normalClassDynamicMethodClass;
        //private MethodDelegate _normalClassDynamicMethodDelegated;

        public CallTests()
        {
            {
                var nc = new NormalClass(0);
                _normalClassRef.Add(nc);
                _normalClassLambda = () => nc.Method();
            }
            {
                var nc = new NormalClass(0);
                _normalClassRef.Add(nc);
                Expression <Func <int> > et = () => nc.Method();
                _normalClassExpressionTree = et.Compile();
            }
            {
                var nc = new NormalClass(0);
                _normalClassRef.Add(nc);
                _normalClassDelegate = nc.Method;
            }
            {
                var nc = new NormalClass(0);
                _normalClassRef.Add(nc);
                _normalClassDynamic = nc;
            }
            {
                var nc = new NormalClass(0);
                _normalClassRef.Add(nc);
                _normalClassReflectionClass      = nc;
                _normalClassReflectionMethodInfo = nc.GetType().GetMethod("Method");
            }

            //GenerateDynamicMethod();
        }
Пример #17
0
        public void Say(string words)
        {
            MethodDelegate dlgt = new MethodDelegate(Say);

            // Initiate the asynchronous call.
            IAsyncResult ar = dlgt.BeginInvoke(words, out int iExecThread, null, null);
        }
Пример #18
0
        public TBalancer(int portIndex, byte protocolVersion, ISettings settings) :
            base("T-Balancer bigNG", new Identifier("bigng", portIndex.ToString(CultureInfo.InvariantCulture)), settings)
        {
            _portIndex       = portIndex;
            _protocolVersion = protocolVersion;

            ParameterDescription[] parameter = { new ParameterDescription("Offset [°C]", "Temperature offset.", 0) };
            int offset = 0;

            for (int i = 0; i < _digitalTemperatures.Length; i++)
            {
                _digitalTemperatures[i] = new Sensor("Digital Sensor " + i, offset + i, SensorType.Temperature, this, parameter, settings);
            }

            offset += _digitalTemperatures.Length;

            for (int i = 0; i < _analogTemperatures.Length; i++)
            {
                _analogTemperatures[i] = new Sensor("Analog Sensor " + (i + 1), offset + i, SensorType.Temperature, this, parameter, settings);
            }

            offset += _analogTemperatures.Length;

            for (int i = 0; i < _sensorHubTemperatures.Length; i++)
            {
                _sensorHubTemperatures[i] = new Sensor("Sensorhub Sensor " + i, offset + i, SensorType.Temperature, this, parameter, settings);
            }

            offset += _sensorHubTemperatures.Length;

            for (int i = 0; i < _miniNgTemperatures.Length; i++)
            {
                _miniNgTemperatures[i] = new Sensor("miniNG #" + (i / 2 + 1) + " Sensor " + (i % 2 + 1), offset + i, SensorType.Temperature, this, parameter, settings);
            }

            for (int i = 0; i < _sensorHubFlows.Length; i++)
            {
                _sensorHubFlows[i] = new Sensor("Flowmeter " + (i + 1),
                                                i,
                                                SensorType.Flow,
                                                this,
                                                new[] { new ParameterDescription("Impulse Rate", "The impulse rate of the flowmeter in pulses/L", 509) },
                                                settings);
            }

            for (int i = 0; i < _controls.Length; i++)
            {
                _controls[i] = new Sensor("Fan Channel " + i, i, SensorType.Control, this, settings);
            }

            for (int i = 0; i < _miniNgControls.Length; i++)
            {
                _miniNgControls[i] = new Sensor("miniNG #" + (i / 2 + 1) + " Fan Channel " + (i % 2 + 1), 4 + i, SensorType.Control, this, settings);
            }

            _alternativeRequest = DelayedAlternativeRequest;

            Open();
            Update();
        }
        public static void LogNow(List<string> strError)
        {
            IErrorLogging log = new ErrorLogFactory().GetErrorLogInstance();

            MethodDelegate callGenerateFileAsync = new MethodDelegate(log.LogError);
            IAsyncResult ar = callGenerateFileAsync.BeginInvoke(strError, null, null);
        }
Пример #20
0
        private void Form1_Load(object sender, EventArgs e)
        {
            MethodDelegate deleg = new MethodDelegate(method);

            #region first way
            IAsyncResult asyncRes = deleg.BeginInvoke(4, null, null);
            IAsyncResult asyncRes2 = deleg.BeginInvoke(5, null, null);

            listBox1.Items.Add("do work");

            listBox1.Items.Add("when it need get the results");

            listBox1.Items.Add(deleg.EndInvoke(asyncRes2));
            listBox1.Items.Add(deleg.EndInvoke(asyncRes));
            #endregion

            #region second way
            AsyncCallback callback = new AsyncCallback(callbackMethod);
            object objectSuppliedState = new object();

            IAsyncResult qwerqwer = deleg.BeginInvoke(6, callback, objectSuppliedState);
            // qwerqwer.AsyncWaitHandle.WaitOne();
            deleg.BeginInvoke(7, new AsyncCallback(callbackMethod2), new object[] { deleg, objectSuppliedState });

            object objectSuppliedState2 = new object();
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(objectSuppliedState2);
            System.Threading.SendOrPostCallback deleg2 = new System.Threading.SendOrPostCallback(methodForGettingResults);
            deleg.BeginInvoke(8, new AsyncCallback(callbackMethod3), new object[] { deleg, asyncOp, deleg2, objectSuppliedState });
            #endregion
        }
Пример #21
0
        /**
         * Metodo delegato per inizio chiamata asincrona volta a processare
         * la finestra.
         */
        public void ManageWindow(List <Packet> buffer, bool isLast)
        {
            List <Packet>  tmp = new List <Packet>(buffer);
            MethodDelegate delegateWindowWork = new MethodDelegate(this.SetWindowAndWork);

            delegateWindowWork.BeginInvoke(tmp, isLast, null, null);
        }
        private static void PreProcessRequest(Hashtable requestParams, HttpContext context, string recName)
        {
            if (context.Cache[spsRules + recName] == null)
            {
                string fileName = context.Server.MapPath("~/ConvertRules/" + recName + ".txt");

                if (!File.Exists(fileName))
                {
                    return;
                }

                context.Cache.Insert(spsRules + recName, GetMethodDelegateFromRecName(fileName, context), new CacheDependency(fileName));
            }
            else
            {
                if (context.Cache[spsRules + recName] is MethodDelegate)
                {
                    MethodDelegate processMethod = context.Cache[spsRules + recName] as MethodDelegate;

                    if (processMethod != null)
                    {
                        processMethod(requestParams);
                    }
                }
            }
        }
Пример #23
0
        private void RunTest(MethodDelegate function, bool testExtra)
        {
            var root = BinaryTreeHelper.BuildTree(new int[] { 5, 4, 7, 8, 9, 6, 3, 2, 1 });

            var n1 = root.LeftChild.LeftChild.LeftChild;
            var n2 = root.LeftChild.RightChild;

            var expected = root.LeftChild;
            BinaryTreeNode <int> foundNode;
            var result = function(root, n1, n2, out foundNode);

            Assert.IsTrue(result);
            Assert.AreEqual(expected, foundNode);

            n1       = root.LeftChild.LeftChild.LeftChild;
            n2       = root.RightChild.RightChild;
            expected = root;
            result   = function(root, n1, n2, out foundNode);
            Assert.IsTrue(result);
            Assert.AreEqual(expected, foundNode);

            n1       = root.LeftChild.LeftChild.LeftChild;
            n2       = root.RightChild.LeftChild;
            expected = root;
            result   = function(root, n1, n2, out foundNode);
            Assert.IsTrue(result);
            Assert.AreEqual(expected, foundNode);

            result = function(null, n1, n2, out foundNode);
            Assert.IsFalse(result);

            result = function(root, null, n2, out foundNode);
            Assert.IsFalse(result);

            result = function(root, n1, null, out foundNode);
            Assert.IsFalse(result);

            result = function(root, n1, n1, out foundNode);
            Assert.IsFalse(result);

            if (testExtra)
            {
                n1 = root.LeftChild;
                n2 = root.LeftChild.LeftChild.RightChild;

                expected = root.LeftChild;
                result   = function(root, n1, n2, out foundNode);
                Assert.IsTrue(result);
                Assert.AreEqual(expected, foundNode);
            }

            if (testExtra)
            {
                n1     = root.LeftChild;
                n2     = new BinaryTreeNode <int>(5);
                result = function(root, n1, n2, out foundNode);
                Assert.IsTrue(result);
                Assert.IsNull(foundNode);
            }
        }
Пример #24
0
        public void IntPtrMethodDelegateParameter(int value)
        {
            var            obj = new PointerHolder();
            MethodDelegate d   = obj.Method;

            d.DynamicInvoke((IntPtr)value, value);
        }
        public object Execute(AutoAttributeContext context)
        {
            string classScript = "";

            if (_parser.NextToken() != TokenType.Eof)
            {
                if (_parser.Token == TokenType.Comment ||
                    _parser.Token == TokenType.LineComment)
                {
                    _parser.SkipComments();
                }

                if (_parser.Token == TokenType.Symbol && _parser.TokenSymbol == "{")
                {
                    classScript = DefaultUsings +
                                  " class Expression { \n " +
                                  "   public static object Execute(AutoAttributeContext context) " +
                                  PreparedScript +
                                  " } ";
                }
            }

            Console.WriteLine(classScript);
            var assembly = CSScript.LoadCode(classScript);

            MethodDelegate method = assembly.GetStaticMethod("*.Execute", context);

            return(method(context));
        }
Пример #26
0
        /// <summary>
        /// Does magic cross thread stuff, mostly used for GUI updates from background threads.
        /// </summary>
        /// <param name="control">Control that might be on a different Thread</param>
        /// <param name="methodName">name of method to execute</param>
        /// <param name="parameters">objects used in invoking method</param>
        public static void InvokeMethod(Control control, string methodName, object[] parameters)
        {
            if (control.InvokeRequired)
            {
                MethodDelegate d = InvokeMethod;
                control.Invoke(d, control, methodName, parameters);
            }
            else
            {
                var paramTypes = new Type[0];
                if (parameters != null && parameters.Length > 0)
                {
                    paramTypes = parameters.Select(o => o.GetType()).ToArray();
                }

                var method = control.GetType().GetMethod(methodName, paramTypes);
                if (method == null)
                {
                    throw new Exception(
                              $"Could not find Property {methodName.Split( '=' )[0]} on {control.GetType()}");
                }

                //specify which method if two have the same name and invoke
                method.Invoke(control, parameters);
            }
        }
        public TResult UpdateCachedData <TResult>(ICacheSettings settings, MethodDelegate <TResult> @delegate, TResult data, params Object[] args)
        {
            // TODO: Support Locking Here

            var buffer = data;

            // Default cache settings
            if (settings == null)
            {
                settings = this.DefaultSettings;
            }

            #region Build CacheKey

            String cacheKey = settings.CacheKeyOverride;

            if (String.IsNullOrWhiteSpace(cacheKey))
            {
                cacheKey = this.BuildCacheKey(@delegate, args);
            }

            #endregion

            #region Cache Storage

#if !CACHENULLS
            // Early exit for empty result
            // TODO: Consider adding option to cache NULL data here
            if (buffer == null)
            {
                return(buffer = null);
            }
#endif

            #region Ensure we have a dependency and that we have a cachekey collection to add to

            settings.Dependencies           = settings.Dependencies ?? this.DefaultDependency;
            settings.Dependencies.CacheKeys = settings.Dependencies.CacheKeys ?? new String[] { };

            #endregion

            CacheItem cacheItem = null;

#if CACHENULLS
            if (buffer == null)
            {
                cacheItem = new CacheItem(cacheKey, TrackingCacheProvider.NULL_OBJECT, "CacheUtils");
            }
            else
#endif
            cacheItem = new CacheItem(cacheKey, buffer, "CacheUtils");

            // Save Data To Cache
            this._cache.Add(cacheItem, settings.GetCacheItemPolicy());

            #endregion

            return(buffer);
        }
Пример #28
0
        public TBalancer(string portName, byte protocolVersion)
        {
            this.portName        = portName;
            this.icon            = Utilities.EmbeddedResources.GetImage("bigng.png");
            this.protocolVersion = protocolVersion;

            ParameterDescription[] parameter = new ParameterDescription[] {
                new ParameterDescription("Offset", "Temperature offset.", 0)
            };
            int offset = 0;

            for (int i = 0; i < digitalTemperatures.Length; i++)
            {
                digitalTemperatures[i] = new Sensor("Digital Sensor #" + (i + 1),
                                                    offset + i, null, SensorType.Temperature, this, parameter);
            }
            offset += digitalTemperatures.Length;

            for (int i = 0; i < analogTemperatures.Length; i++)
            {
                analogTemperatures[i] = new Sensor("Analog Sensor #" + (i + 1),
                                                   offset + i, null, SensorType.Temperature, this, parameter);
            }
            offset += analogTemperatures.Length;

            for (int i = 0; i < sensorhubTemperatures.Length; i++)
            {
                sensorhubTemperatures[i] = new Sensor("Sensorhub Sensor #" + (i + 1),
                                                      offset + i, null, SensorType.Temperature, this, parameter);
            }
            offset += sensorhubTemperatures.Length;

            for (int i = 0; i < sensorhubFlows.Length; i++)
            {
                sensorhubFlows[i] = new Sensor("Flowmeter #" + (i + 1),
                                               offset + i, null, SensorType.Flow, this, new ParameterDescription[] {
                    new ParameterDescription("Impulse Rate",
                                             "The impulse rate of the flowmeter in pulses/L", 509)
                });
            }
            offset += sensorhubFlows.Length;

            for (int i = 0; i < miniNGTemperatures.Length; i++)
            {
                miniNGTemperatures[i] = new Sensor("miniNG #" + (i / 2 + 1) +
                                                   " Sensor #" + (i % 2 + 1), offset + i, null, SensorType.Temperature,
                                                   this, parameter);
            }
            offset += miniNGTemperatures.Length;

            alternativeRequest = new MethodDelegate(DelayedAlternativeRequest);

            try {
                serialPort = new SerialPort(portName, 19200, Parity.None, 8,
                                            StopBits.One);
                serialPort.Open();
                Update();
            } catch (IOException) { }
        }
Пример #29
0
        public SkryptEngine SetValue(string name, MethodDelegate value)
        {
            var val = new FunctionInstance(this, value);

            SetGlobal(name, val);

            return(this);
        }
Пример #30
0
 public ConsoleCommand(string name, MethodDelegate method, string description, int tag, AutocompleteDelegate autocompleteMethod)
 {
     this.name               = name;
     this.method             = method;
     this.description        = description;
     this.tag                = tag;
     this.autocompleteMethod = autocompleteMethod;
 }
Пример #31
0
        public static WorkerThread CreateWorkerThread(string name, MethodDelegate method, bool continous)
        {
            WorkerThread newWorkerThread = new WorkerThread(name, method, continous);

            myWorkerThreads.Add(newWorkerThread);
            newWorkerThread.Start();
            return(newWorkerThread);
        }
Пример #32
0
 //Method to actually open serial port for communication
 public void openPort() 
 {
     arduinoPort.Open();
     arduinoPort.DiscardInBuffer();
     // Delegate for DoUpdate.
     ReadSerialData = new MethodDelegate(DoUpdate);
     arduinoPort.DataReceived += new SerialDataReceivedEventHandler(arduinoPort_DataReceived);
 }
Пример #33
0
 /// <summary>
 /// Loads the segment data from the source
 /// </summary>
 /// <typeparam name="T">The data point type</typeparam>
 /// <param name="session">The session this is part of</param>
 /// <param name="segment">The segment to populate</param>
 public override void LoadSegment <T>(StockDataSet <T> segment, StockSession session = null)
 {
     if ((this.LoadMethod == null) && (session != null))
     {
         this.LoadMethod = session.ScriptInstance.GetStaticMethod("*.Load", this, "", DateTime.Now);
     }
     segment.DataSet.Initialize((T[])LoadMethod(this, segment.Symbol, segment.Start));
 }
Пример #34
0
 //Method to actually open serial port for communication
 public void openPort()
 {
     arduinoPort.Open();
     arduinoPort.DiscardInBuffer();
     // Delegate for DoUpdate.
     ReadSerialData            = new MethodDelegate(DoUpdate);
     arduinoPort.DataReceived += new SerialDataReceivedEventHandler(arduinoPort_DataReceived);
 }
        //Constructor
        public Timer(uint delay, MethodDelegate executeMethod)
        {
            this.Delay = delay;
            this.MethodProp = executeMethod;

            Thread newThread = new Thread(() =>
                { 
                    while (true)
                    {
                        this.MethodProp();
                        Thread.Sleep((int)this.Delay);
                    }
                });
            newThread.Start();
        }
Пример #36
0
        /// <summary>
        /// Creates a new instance of the safe method wrapper.
        /// </summary>
        /// <param name="methodInfo">Method to wrap.</param>
        public SafeMethod(MethodInfo methodInfo)
        {
            Guard.ArgumentNotNull(methodInfo, "methodInfo", "You cannot create a dynamic method for a null value.");

            this.methodInfo = methodInfo;
            this.Name = methodInfo.Name;
            ParameterInfo[] infoParams = methodInfo.GetParameters();
            int pCount = infoParams.Length;
            if (pCount > 0 &&
               ((pCount == 1 && infoParams[0].ParameterType.IsArray) ||
               (infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0)))
            {
                this.hasFinalArrayParam = true;
                this.methodParamsLength = pCount;
                this.finalArrayElementType = infoParams[pCount - 1].ParameterType;
            }

            this.method = DynamicReflectionManager.CreateMethod(methodInfo);
        }
Пример #37
0
 public ChartController(IHubConnectionContext<dynamic> clients)
 {
     Clients = clients;
     MethodDelegate metho = new MethodDelegate(this.start);
     metho.BeginInvoke(null, null);
 }
    public static int Main()
    {
        SCMethod ();

        try {
            CMethod ();
            error ("static critical method called");
        } catch (MethodAccessException) {
        }

        SCClass sc = new SCClass ();
        sc.Method ();

        try {
            CClass c = new CClass (); // Illegal
            error ("critical object instantiated");
            c.Method ();	// Illegal
            error ("critical method called");
        } catch (MethodAccessException) {
        }

        try {
            doSCDev ();
            error ("security-critical-derived class error");
        } catch (TypeLoadException) {
        }

        try {
            doCMethodDev ();
        } catch (TypeLoadException) {
        }

        try {
            getpid ();
            error ("pinvoke called");
        } catch (MethodAccessException) {
        }

        try {
            MethodDelegate md = new MethodDelegate (CClass.StaticMethod);
            md ();
            error ("critical method called via delegate");
        } catch (MethodAccessException) {
        }

        try {
            CriticalClass.NestedClassInsideCritical.Method ();
        } catch (MethodAccessException) {
        }

        try {
            doSCInterfaceDev ();
        } catch (TypeLoadException) {
        }

        /*
        try {
            unsafeMethod ();
        } catch (VerificationException) {
        }
        */

        try {
            Type type = Type.GetType ("Test");
            MethodInfo method = type.GetMethod ("TransparentReflectionCMethod");

            method.Invoke(null, null);
        } catch (MethodAccessException) {
            error ("transparent method not called via reflection");
        }

        try {
            Type type = Type.GetType ("Test");
            MethodInfo method = type.GetMethod ("ReflectionCMethod");

            method.Invoke(null, null);
        } catch (MethodAccessException) {
        }

        try {
            Type type = Type.GetType ("Test");
            MethodInfo method = type.GetMethod ("TransparentReflectionCMethod");
            InvokeDelegate id = new InvokeDelegate (method.Invoke);

            id (null, null);
        } catch (MethodAccessException) {
            error ("transparent method not called via reflection delegate");
        }

        try {
            Type type = Type.GetType ("Test");
            MethodInfo method = type.GetMethod ("ReflectionCMethod");
            InvokeDelegate id = new InvokeDelegate (method.Invoke);

            id (null, null);
        } catch (MethodAccessException) {
        }

        //Console.WriteLine ("ok");

        if (haveError)
            return 1;

        return 0;
    }
    public TBalancer(int portIndex, byte protocolVersion, ISettings settings)
      : base("T-Balancer bigNG",  new Identifier("bigng",
        portIndex.ToString(CultureInfo.InvariantCulture)), settings) 
    {

      this.portIndex = portIndex;
      this.protocolVersion = protocolVersion;

      ParameterDescription[] parameter = new [] {
        new ParameterDescription("Offset [°C]", "Temperature offset.", 0)
      };
      int offset = 0;
      for (int i = 0; i < digitalTemperatures.Length; i++)
        digitalTemperatures[i] = new Sensor("Digital Sensor " + i,
          offset + i, SensorType.Temperature, this, parameter, settings);
      offset += digitalTemperatures.Length;

      for (int i = 0; i < analogTemperatures.Length; i++)
        analogTemperatures[i] = new Sensor("Analog Sensor " + (i + 1),
          offset + i, SensorType.Temperature, this, parameter, settings);
      offset += analogTemperatures.Length;

      for (int i = 0; i < sensorhubTemperatures.Length; i++)
        sensorhubTemperatures[i] = new Sensor("Sensorhub Sensor " + i,
          offset + i, SensorType.Temperature, this, parameter, settings);
      offset += sensorhubTemperatures.Length;

      for (int i = 0; i < miniNGTemperatures.Length; i++)
        miniNGTemperatures[i] = new Sensor("miniNG #" + (i / 2 + 1) +
          " Sensor " + (i % 2 + 1), offset + i, SensorType.Temperature,
          this, parameter, settings);
      offset += miniNGTemperatures.Length;

      for (int i = 0; i < sensorhubFlows.Length; i++)
        sensorhubFlows[i] = new Sensor("Flowmeter " + (i + 1),
          i, SensorType.Flow, this, new [] {
            new ParameterDescription("Impulse Rate", 
              "The impulse rate of the flowmeter in pulses/L", 509)
          }, settings);

      for (int i = 0; i < controls.Length; i++) {
        controls[i] = new Sensor("Fan Channel " + i, i, SensorType.Control, 
          this, settings);
      }

      for (int i = 0; i < miniNGControls.Length; i++) {
        miniNGControls[i] = new Sensor("miniNG #" + (i / 2 + 1) +
          " Fan Channel " + (i % 2 + 1), 4 + i, SensorType.Control, this, 
          settings);
      }

      alternativeRequest = new MethodDelegate(DelayedAlternativeRequest);

      Open();
      Update(); 
    }
Пример #40
0
            public void KeepRemoteObjectAlive()
            {
                sum = CSScript.Evaluator
                              .CreateDelegateRemotely(@"int Sum(int a, int b)
                                                        {
                                                            return a+b;
                                                        }");

                //Normally remote objects are disposed if they are not accessed withing a default timeout period.
                //It is not even enough to keep transparent proxies or their wrappers (e.g. 'sum') referenced. 
                //To prevent GC collection in the remote domain use .NET ClientSponsor mechanism as below.
                sumSponsor = sum.ExtendLifeFromMinutes(30);
            }
Пример #41
0
	public static int Main ()
	{
		SCMethod ();

		try {
			CMethod ();
			error ("static critical method called");
		} catch (MethodAccessException) {
		}

		SCClass sc = new SCClass ();
		sc.Method ();

		try {
			CClass c = new CClass (); // Illegal
			error ("critical object instantiated");
			c.Method ();	// Illegal
			error ("critical method called");
		} catch (MethodAccessException) {
		}

		try {
			doSCDev ();
			error ("security-critical-derived class error");
		} catch (TypeLoadException) {
		}

		try {
			doCMethodDev ();
		} catch (TypeLoadException) {
		}

		try {
			getpid ();
			error ("pinvoke called");
		} catch (MethodAccessException) {
		}

		try {
			MethodDelegate md = new MethodDelegate (CClass.StaticMethod);
			md ();
			error ("critical method called via delegate");
		} catch (MethodAccessException) {
		}

		try {
			CriticalClass.NestedClassInsideCritical.Method ();
		} catch (MethodAccessException) {
		}

		try {
			doSCInterfaceDev ();
		} catch (TypeLoadException) {
		}

		/*
		try {
			unsafeMethod ();
		} catch (VerificationException) {
		}
		*/

		try {
			Type type = Type.GetType ("Test");
			MethodInfo method = type.GetMethod ("TransparentReflectionCMethod");

			method.Invoke(null, null);
		} catch (MethodAccessException) {
			error ("transparent method not called via reflection");
		}

		try {
			Type type = Type.GetType ("Test");
			MethodInfo method = type.GetMethod ("ReflectionCMethod");

			method.Invoke(null, null);
		} catch (MethodAccessException) {
		}

		try {
			Type type = Type.GetType ("Test");
			MethodInfo method = type.GetMethod ("TransparentReflectionCMethod");
			InvokeDelegate id = new InvokeDelegate (method.Invoke);

			id (null, null);
		} catch (MethodAccessException) {
			error ("transparent method not called via reflection delegate");
		}

		try {
			Type type = Type.GetType ("Test");
			MethodInfo method = type.GetMethod ("ReflectionCMethod");
			InvokeDelegate id = new InvokeDelegate (method.Invoke);

			id (null, null);
		} catch (MethodAccessException) {
		}


		// wrapper 7
		try {
			CallStringTest ();
		} catch (MethodAccessException) {
			error ("string test failed");
		}

		try {
			doBadTransparentOverrideClass ();
			error ("BadTransparentOverrideClass error");
		} catch (TypeLoadException) {
		}

		try {
			doBadSafeCriticalOverrideClass ();
			error ("BadSafeCriticalOverrideClass error");
		} catch (TypeLoadException) {
		}

		try {
			doBadCriticalOverrideClass ();
			error ("BadCriticalOverrideClass error");
		} catch (TypeLoadException) {
		}

		new TransparentClassWithSafeCriticalDefaultConstructor ();
		try {
			new TransparentInheritFromSafeCriticalDefaultConstructor ();
		} catch (TypeLoadException) {
		}
		new SafeInheritFromSafeCriticalDefaultConstructor ();

		// arrays creation tests
		ArraysCreatedByTransparentCaller ();
		ArraysCreatedBySafeCriticalCaller ();
		// the above also calls ArraysCreatedBySafeCriticalCaller since (Transparent) Main cannot call it directly

		if (haveError)
			return 1;

//		Console.WriteLine ("ok");
		return 0;
	}
Пример #42
0
        private void button1_Click(object sender, EventArgs e)
        {
            List<Guid> list = new List<Guid>();

            string ex = "";
            DataTable tb = MQMsgCommonHelper.QueryMQLog("1=1",out ex);
            if (tb != null)
            {
                foreach (DataRow row in tb.Rows)
                {
                    //list.Add(new Guid(row["GUID"].ToString()));
                    MethodDelegate test = new MethodDelegate(OnMultiTest);
                    test.BeginInvoke(new Guid(row["GUID"].ToString()), null, null);
                }
            }
            

        }
Пример #43
0
            /// <summary>
            /// Creates a method map for the tag
            /// </summary>
            /// <param name="name">the name of the method</param>
            /// <param name="parameters">space separated list of attributes for the tag</param>
            /// <param name="method">the delegate</param>
            public MethodMap(string name, string parameters, MethodDelegate method)
            {
                this._name = name;
                _parameters = new NameValueCollection();
                int i = 0;
                foreach (string s in parameters.Split(' ')) {
                    _parameters.Add(s, i.ToString());
                    i++;
                }

                this._method = method;
            }
Пример #44
0
 /// <summary>
 /// Low now method
 /// </summary>
 /// <param name="errors">error list</param>
 public static void LogNow(List<string> errors)
 {
     var log = new ErrorLogFactory().GetErrorLogInstance();
     var callGenerateFileAsync = new MethodDelegate(log.LogError);
     callGenerateFileAsync.BeginInvoke(errors, null, null);
 }
		/// <summary>
		/// catches the event that the backgroundworker has finished.
		/// in that case we should select the returned node
		/// </summary>
		/// <param name="sender">the backgroundworder</param>
		/// <param name="e">the parameters</param>
		private void treeBackgroundRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                //nothing?
                
            }
            else if (!(e.Error == null))
            {
                //nothing?
            }
            else
            {
            	            	
            	//do the visual work for the new treenode
            	TreeNode elementNode = (TreeNode)e.Result;
            	
            	//remove duplicate
            	if (this.removeRootNode((UML.UMLItem)elementNode.Tag))
				{
            		try
            		{
						//no parentNode, add as new root node before any others
						//inserting a node sometimes causes an InvalidOperationException because its being called in the wrong thread
						//doing it using the invoke should help.
						invoker = new MethodDelegate(ThreadSaveInsertNode); 
						this.NavigatorTree.Invoke(invoker, elementNode); 
						//this.NavigatorTree.Nodes.Insert(0,elementNode);
						//remove the excess nodes
						this.removeExcessNodes();
						//expand the node
						elementNode.Expand();
						
            		}
            		catch (Exception exception)
            		{
            			MessageBox.Show(exception.Message + Environment.NewLine + exception.StackTrace,"An error occured"
            			                ,MessageBoxButtons.OK,MessageBoxIcon.Error);
            		}
				}
				else 
				{
					//first node is already the one we need
					elementNode = this.NavigatorTree.Nodes[0];
				}
            	this.NavigatorTree.SelectedNode = (TreeNode)e.Result;
            	            	
            	//check if there's still something int the queue
            	if (this.workQueue.Count > 0)
            	{
            		//get the last element in the queue
            		UML.UMLItem nextElement = this.workQueue[this.workQueue.Count -1];
            		//remove it
            		this.workQueue.RemoveAt(this.workQueue.Count -1);
            		//process it
            		this.setElement(nextElement);
            	}
            }
        }
Пример #46
0
        //Close port on disconnect
        public void closePort()
        {
            try
            {
                arduinoPort.DiscardInBuffer();
                arduinoPort.Close();
            }
            catch (Exception)
            {

            }
            ReadSerialData = null;
            arduinoPort.DataReceived -= arduinoPort_DataReceived;
        }
Пример #47
0
 protected override void OnStart(string[] args)
 {
     MethodDelegate metho = new MethodDelegate(this.start);
     metho.BeginInvoke(null, null);
 }