Example #1
0
        private static void RemoveObject(IXenObject ixmo)
        {
            InvokeHelper.AssertOnEventThread();

            XenRef <Folder> path   = new XenRef <Folder>(ixmo.Path);
            Folder          folder = ixmo.Connection.Resolve(path);

            if (folder != null)
            {
                folder.RemoveObject(ixmo);
                PotentiallyRemoveFolder(folder);
            }
        }
Example #2
0
        /// <summary>
        ///   Invokes setindex.
        /// </summary>
        /// <param name="target"> The target. </param>
        /// <param name="indexesThenValue"> The indexes then value. </param>
        public static void InvokeSetIndex(object target, params object[] indexesThenValue)
        {
            string[] tArgNames;
            Type     tContext;
            bool     tStaticContext;

            target           = target.GetTargetContext(out tContext, out tStaticContext);
            indexesThenValue = Util.GetArgsAndNames(indexesThenValue, out tArgNames);

            CallSite tCallSite = null;

            InvokeHelper.InvokeSetIndexCallSite(target, indexesThenValue, tArgNames, tContext, tStaticContext, ref tCallSite);
        }
Example #3
0
        /// <summary>
        /// Invokes the action using the DLR
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="args">The args.</param>
        public static void InvokeAction(object target, params object[] args)
        {
            string[] tArgNames;
            Type     tContext;
            bool     tStaticContext;

            target = target.GetTargetContext(out tContext, out tStaticContext);
            args   = Util.GetArgsAndNames(args, out tArgNames);

            CallSite tCallSite = null;

            InvokeHelper.InvokeDirectActionCallSite(target, args, tArgNames, tContext, tStaticContext, ref tCallSite);
        }
Example #4
0
        /// <summary>
        /// Dynamically Invokes a set member using the DLR.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="name">The name.</param>
        /// <param name="value">The value.</param>
        /// <example>
        /// Unit test that exhibits usage:
        /// <code>
        /// <![CDATA[
        ///    dynamic tExpando = new ExpandoObject();
        ///
        ///    var tSetValue = "1";
        ///
        ///    Impromptu.InvokeSet(tExpando, "Test", tSetValue);
        ///
        ///    Assert.AreEqual(tSetValue, tExpando.Test);
        /// ]]>
        /// </code>
        /// </example>
        /// <remarks>
        /// if you call a static property off a type with a static context the csharp dlr binder won't do it, so this method reverts to reflection
        /// </remarks>
        public static object InvokeSet(object target, string name, object value)
        {
            Type tContext;
            bool tStaticContext;

            target   = target.GetTargetContext(out tContext, out tStaticContext);
            tContext = tContext.FixContext();


            CallSite tCallSite = null;

            return(InvokeHelper.InvokeSetCallSite(target, name, value, tContext, tStaticContext, ref tCallSite));
        }
Example #5
0
        /// <summary>
        /// Dynamically Invokes indexer using the DLR.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="indexes">The indexes.</param>
        /// <returns></returns>
        public static dynamic InvokeGetIndex(object target, params object[] indexes)
        {
            string[] tArgNames;
            Type     tContext;
            bool     tStaticContext;

            target  = target.GetTargetContext(out tContext, out tStaticContext);
            indexes = Util.GetArgsAndNames(indexes, out tArgNames);
            CallSite tCallSite = null;

            return(InvokeHelper.InvokeGetIndexCallSite(target, indexes, tArgNames, tContext, tStaticContext,
                                                       ref tCallSite));
        }
Example #6
0
        /// <summary>
        /// Dynamically Invokes a member method using the DLR
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="name">The name. Can be a string it will be implicitly converted</param>
        /// <param name="args">The args.</param>
        /// <returns> The result</returns>
        /// <example>
        /// Unit test that exhibits usage:
        /// <code>
        /// <![CDATA[
        ///    dynamic tExpando = new ExpandoObject();
        ///    tExpando.Func = new Func<int, string>(it => it.ToString());
        ///
        ///    var tValue = 1;
        ///    var tOut = Impromptu.InvokeMember(tExpando, "Func", tValue);
        ///
        ///    Assert.AreEqual(tValue.ToString(), tOut);
        /// ]]>
        /// </code>
        /// </example>
        public static dynamic InvokeMember(object target, String_OR_InvokeMemberName name, params object[] args)
        {
            string[] tArgNames;
            Type     tContext;
            bool     tStaticContext;

            target = target.GetTargetContext(out tContext, out tStaticContext);
            args   = Util.GetArgsAndNames(args, out tArgNames);
            CallSite tCallSite = null;

            return(InvokeHelper.InvokeMemberCallSite(target, (InvokeMemberName)name, args, tArgNames, tContext, tStaticContext,
                                                     ref tCallSite));
        }
Example #7
0
        public static void Main(string[] args)
        {
            LogHelper.AddLogProvider(new Log4NetLogHelperProvider());
            Console.WriteLine("----------DotNetFxSample----------");

            // 数据库扩展
            // DataExtensionTest.MainTest();

            InvokeHelper.TryInvoke(LoggerTest.Test);
            var emptyArray = ArrayHelper.Empty <int>();

            Console.ReadLine();
        }
Example #8
0
        public static void EInvokeRepeating(this  MonoBehaviour self, string methodKey, float delay, float repeatTime, System.Action callback)
        {
            InvokeHelper helper = self.GetComponent <InvokeHelper> ();

            if (helper == null)
            {
                helper = self.gameObject.AddComponent <InvokeHelper> ();
            }
            if (helper.enabled == false)
            {
                helper.enabled = true;
            }
            helper.HelperInvokeRepeating(self, methodKey, delay, repeatTime, callback);
        }
Example #9
0
        /// <summary>
        /// Coerces any invokable to specified delegate type.
        /// </summary>
        /// <param name="invokeableObject">The invokeable object.</param>
        /// <param name="delegateType">Type of the delegate.</param>
        /// <returns></returns>
        public static dynamic CoerceToDelegate(object invokeableObject, Type delegateType)
        {
            var delegateTypeInfo = delegateType.GetTypeInfo();

            if (!typeof(Delegate).GetTypeInfo().IsAssignableFrom(delegateTypeInfo.BaseType))
            {
                return(null);
            }
            var tDelMethodInfo = delegateTypeInfo.GetMethod("Invoke");

            if (tDelMethodInfo is null)
            {
                throw new Exception("This Delegate Didn't have and Invoke method! Impossible!");
            }
            var      tReturnType   = tDelMethodInfo.ReturnType;
            var      tAction       = tReturnType == typeof(void);
            var      tParams       = tDelMethodInfo.GetParameters();
            var      tLength       = tDelMethodInfo.GetParameters().Length;
            Delegate tBaseDelegate = tAction
                                             ? InvokeHelper.WrapAction(invokeableObject, tLength)
                                             : InvokeHelper.WrapFunc(tReturnType, invokeableObject, tLength);


            if (InvokeHelper.IsActionOrFunc(delegateType) &&
                !tParams.Any(it => it.ParameterType.GetTypeInfo().IsValueType))
            {
                return(tBaseDelegate);
            }

            if (CompiledExpressions.TryGetValue(delegateType, out var tGetResult))
            {
                return(tGetResult.DynamicInvoke(tBaseDelegate));
            }

            var tParamTypes  = tParams.Select(it => it.ParameterType).ToArray();
            var tDelParam    = Expression.Parameter(tBaseDelegate.GetType());
            var tInnerParams = tParamTypes.Select(Expression.Parameter).ToArray();

            var tI = Expression.Invoke(tDelParam,
                                       tInnerParams.Select(it => (Expression)Expression.Convert(it, typeof(object))));
            var tL = Expression.Lambda(delegateType, tI, tInnerParams);

            tGetResult =
                Expression.Lambda(Expression.GetFuncType(tBaseDelegate.GetType(), delegateType), tL,
                                  tDelParam).Compile();
            CompiledExpressions[delegateType] = tGetResult;

            return(tGetResult.DynamicInvoke(tBaseDelegate));
        }
Example #10
0
        //Elimna Detalle
        private bool SaveDataDetalle(int id_plan_seguro_detalle)
        {
            bool result = false;

            try
            {
                var jsonResponse = new JsonResponse {
                    Success = false
                };
                switch (this.estadoActual)
                {
                case EstadoActual.Eliminar:
                    jsonResponse = InvokeHelper.MakeRequest(ConstantesWindows.WS_CVN_PLAN_SEGURO_DETALLE_Delete, new CVN_PLAN_SEGURO_DETALLEDTO {
                        id_plan_seguro_detalle = Convert.ToInt32(id_plan_seguro_detalle), IdUsuarioActual = Convert.ToInt32(WindowsSession.UserIdActual)
                    }, ConstantesWindows.METHODPOST);
                    break;
                }

                if (jsonResponse.Success)
                {
                    if (jsonResponse.Warning)
                    {
                        result = false;
                        //Mensaje.ShowMessageAlert(this.ParentForm, ConstantesWindows.TituloMensaje, jsonResponse.Message);
                    }
                    else
                    {
                        result = true;
                    }
                }
                else
                {
                    result = false;
                    Mensaje.ShowMessageAlert(this.ParentForm, ConstantesWindows.TituloMensaje, jsonResponse.Message);
                }

                if (result)
                {
                    //this.Close();
                    //Mensaje.ShowMessageAlert(this.ParentForm, ConstantesWindows.TituloMensaje, jsonResponse.Message);
                    //DialogResult = DialogResult.OK;
                }
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, ConstantesWindows.TituloMensaje, ex.Message);
            }
            return(result);
        }
Example #11
0
        /// <summary>
        /// Disables current user account option.
        /// </summary>
        private void DisableCurrentUserAccount()
        {
            using (InvokeHelper ih = new InvokeHelper(radUseCurrentUserAccount))
            {
                ih.InvokeMethod(() => radUseCurrentUserAccount.Checked = false);

                using (InvokeHelper ih1 = new InvokeHelper(radSpecifyCredentials))
                {
                    ih1.InvokeMethod(() => radSpecifyCredentials.Checked = true);
                }

                ih.InvokeMethod(() => radUseCurrentUserAccount.Enabled = false);
            }
            ImportProfile.ADUseCurrentUserAccount = false;
        }
Example #12
0
    public static async Task TaskWhenAllTest()
    {
        ThreadPool.GetMaxThreads(out var workerThreads, out var completionPortThreads);
        Console.WriteLine($"threadpool max threads setting:workerThreads:{workerThreads}, completionPortThreads:{completionPortThreads}");

        var time = await InvokeHelper.ProfileAsync(() => Task.WhenAll(Enumerable.Range(1, 5).Select(_ => Task.Delay(1000))));

        Console.WriteLine("await Task.WhenAll time:{0} ms", time);

        time = InvokeHelper.Profile(() => Task.WhenAll(Enumerable.Range(1, 5).Select(_ => Task.Delay(1000))));
        Console.WriteLine("Task.WhenAll no wait time:{0} ms", time);

        time = InvokeHelper.Profile(() => Task.WhenAll(Enumerable.Range(1, 5).Select(_ => Task.Delay(1000))).Wait());
        Console.WriteLine("Task.WhenAll wait time:{0} ms", time);
    }
Example #13
0
        public static async Task MainAsync(string[] args)
        {
            InvokeHelper.OnInvokeException = Console.WriteLine;

            await InvokeHelper.TryInvokeAsync(FormUrlEncodeContentTest.FormUrlEncodedContentLengthTest);

            Console.WriteLine();
            await InvokeHelper.TryInvokeAsync(FormUrlEncodeContentTest.StringContentLengthTest);

            Console.WriteLine();
            await InvokeHelper.TryInvokeAsync(FormUrlEncodeContentTest.ByteArrayContentLengthTest);

            Console.WriteLine("Completed!");
            Console.ReadLine();
        }
Example #14
0
        /// <summary>
        /// Invokes setindex.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="indexesThenValue">The indexes then value.</param>
        public static object InvokeSetIndex(object target, params object[] indexesThenValue)
        {
            if (indexesThenValue.Length < 2)
            {
                throw new ArgumentException("Requires at least one index and one value", nameof(indexesThenValue));
            }

            target           = target.GetTargetContext(out var tContext, out var tStaticContext);
            indexesThenValue = Util.GetArgsAndNames(indexesThenValue, out var tArgNames);

            CallSite tCallSite = null;

            return(InvokeHelper.InvokeSetIndexCallSite(target, indexesThenValue, tArgNames, tContext, tStaticContext,
                                                       ref tCallSite));
        }
Example #15
0
        /// <summary>
        /// Invokes add assign with correct behavior for events.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="name">The name.</param>
        /// <param name="value">The value.</param>
        public static void InvokeAddAssignMember(object target, string name, object value)
        {
            CallSite callSiteAdd     = null;
            CallSite callSiteGet     = null;
            CallSite callSiteSet     = null;
            CallSite callSiteIsEvent = null;

            target = target.GetTargetContext(out var context, out var staticContext);

            var args = new[] { value };

            args = Util.GetArgsAndNames(args, out var argNames);

            InvokeHelper.InvokeAddAssignCallSite(target, name, args, argNames, context, staticContext, ref callSiteIsEvent, ref callSiteAdd, ref callSiteGet, ref callSiteSet);
        }
Example #16
0
        private static void UpdateDockerContainer(VM vm)
        {
            InvokeHelper.AssertOnEventThread();

            if (vm == null)
            {
                return;
            }

            IXenConnection connection = vm.Connection;

            var dockerVMs = GetDockerVMs(vm);

            connection.Cache.UpdateDockerContainersForVM(dockerVMs, vm);
        }
Example #17
0
        private static void _WindowSizeChanged(Object sender, SizeChangedEventArgs e)
        {
            Type GraphicsWindowType = typeof(GraphicsWindow);

            try
            {
                RenderTargetBitmap _renderBitmap = (RenderTargetBitmap)GraphicsWindowType.GetField("_renderBitmap", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
                if (e.NewSize.Width > _renderBitmap.Width || e.NewSize.Height > _renderBitmap.Height)
                {
                    Window       _window          = (Window)GraphicsWindowType.GetField("_window", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
                    Image        _bitmapContainer = (Image)GraphicsWindowType.GetField("_bitmapContainer", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
                    InvokeHelper ret = delegate
                    {
                        try
                        {
                            Object       content      = _window.Content;
                            ScrollViewer scrollViewer = (ScrollViewer)content;
                            Grid         grid         = (Grid)(scrollViewer.Content);

                            double width  = System.Math.Max(e.NewSize.Width, grid.Width);
                            double height = System.Math.Max(e.NewSize.Height, grid.Height);

                            DrawingVisual  drawingVisual  = new DrawingVisual();
                            DrawingContext drawingContext = drawingVisual.RenderOpen();
                            drawingContext.DrawImage(_renderBitmap, new Rect(0.0, 0.0, _renderBitmap.Width, _renderBitmap.Height));
                            drawingContext.Close();

                            RenderTargetBitmap _renderBitmapNew = new RenderTargetBitmap((int)width + 120, (int)height + 120, 96.0, 96.0, PixelFormats.Default);
                            _renderBitmapNew.Render(drawingVisual);

                            GraphicsWindowType.GetField("_renderBitmap", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, _renderBitmapNew);
                            _bitmapContainer.Width  = _renderBitmapNew.Width;
                            _bitmapContainer.Height = _renderBitmapNew.Height;
                            _bitmapContainer.Source = _renderBitmapNew;
                        }
                        catch (Exception ex)
                        {
                            Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                        }
                    };
                    FastThread.Invoke(ret);
                }
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #18
0
        /// <summary>
        /// Invokes the constuctor.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="args">The args.</param>
        /// <returns></returns>
        public static dynamic InvokeConstructor(Type type, params object[] args)
        {
            string[] tArgNames;
            bool     tValue = type.IsValueType;

            if (tValue && args.Length == 0)  //dynamic invocation doesn't see constructors of value types
            {
                return(Activator.CreateInstance(type));
            }

            args = Util.GetArgsAndNames(args, out tArgNames);
            CallSite tCallSite = null;


            return(InvokeHelper.InvokeConstructorCallSite(type, tValue, args, tArgNames, ref tCallSite));
        }
        protected bool IsBindingElementsMatch(TcpRelayTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding)
        {
            if (!this.transport.IsMatch(transport))
            {
                return(false);
            }
            Type type = typeof(BindingElement);
            BinaryMessageEncodingBindingElement binaryMessageEncodingBindingElement = this.encoding;

            object[] objArray = new object[] { encoding };
            if (!(bool)InvokeHelper.InvokeInstanceMethod(type, binaryMessageEncodingBindingElement, "IsMatch", objArray))
            {
                return(false);
            }
            return(true);
        }
        internal SecurityBindingElement CreateMessageSecurity(bool isSecureTransportMode)
        {
            SecurityBindingElement algorithmSuite;

            if (!isSecureTransportMode)
            {
                if (this.clientCredentialType != BasicHttpMessageCredentialType.Certificate)
                {
                    throw Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(Microsoft.ServiceBus.SR.GetString(Resources.BasicHttpMessageSecurityRequiresCertificate, new object[0])));
                }
                algorithmSuite = SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, true);
            }
            else
            {
                MessageSecurityVersion wSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10 = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                switch (this.clientCredentialType)
                {
                case BasicHttpMessageCredentialType.UserName:
                {
                    algorithmSuite = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
                    algorithmSuite.MessageSecurityVersion = wSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                    algorithmSuite.DefaultAlgorithmSuite  = this.AlgorithmSuite;
                    algorithmSuite.SecurityHeaderLayout   = SecurityHeaderLayout.Lax;
                    algorithmSuite.SetKeyDerivation(false);
                    InvokeHelper.InvokeInstanceSet(algorithmSuite.GetType(), algorithmSuite, "DoNotEmitTrust", true);
                    return(algorithmSuite);
                }

                case BasicHttpMessageCredentialType.Certificate:
                {
                    algorithmSuite = SecurityBindingElement.CreateCertificateOverTransportBindingElement(wSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
                    algorithmSuite.DefaultAlgorithmSuite = this.AlgorithmSuite;
                    algorithmSuite.SecurityHeaderLayout  = SecurityHeaderLayout.Lax;
                    algorithmSuite.SetKeyDerivation(false);
                    InvokeHelper.InvokeInstanceSet(algorithmSuite.GetType(), algorithmSuite, "DoNotEmitTrust", true);
                    return(algorithmSuite);
                }
                }
                Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.DebugAssert("Unsupported basic http message credential type");
                throw Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
            }
            algorithmSuite.DefaultAlgorithmSuite = this.AlgorithmSuite;
            algorithmSuite.SecurityHeaderLayout  = SecurityHeaderLayout.Lax;
            algorithmSuite.SetKeyDerivation(false);
            InvokeHelper.InvokeInstanceSet(algorithmSuite.GetType(), algorithmSuite, "DoNotEmitTrust", true);
            return(algorithmSuite);
        }
        //Obtiene datos por el id
        private void GetDatosContacto()
        {
            if (txtId.Text != "0")
            {
                var jsonResponse = new JsonResponse {
                    Success = false
                };

                jsonResponse = InvokeHelper.MakeRequest(ConstantesWindows.WS_CON_CONTACTO_GetById, GetContacto(), ConstantesWindows.METHODPOST);

                if (jsonResponse.Success && !jsonResponse.Warning)
                {
                    var contactoListDTO = (List <CON_CONTACTODTO>)JsonConvert.DeserializeObject(jsonResponse.Data.ToString(), (new List <CON_CONTACTODTO>()).GetType());
                    //this.ETUsuariobindingSource.DataSource = usuarioListDTO;
                    //--------------------------

                    for (int i = 0; i < contactoListDTO.Count; i++)
                    {
                        txtCodigo.Text = string.IsNullOrEmpty(contactoListDTO[i].c_codigo) ? string.Empty : contactoListDTO[i].c_codigo.ToString();
                        int x = contactoListDTO[i].id_tipo_contacto;     //) ? "0" : contactoListDTO[i].id_tipo_contacto.ToString();
                        CbTipoContacto.SelectedValue = Convert.ToInt32(x);
                        TxtCodigoSunat.Text          = string.IsNullOrEmpty(contactoListDTO[i].c_codigo_sunat) ? string.Empty : contactoListDTO[i].c_codigo_sunat.ToString();
                        TxtApellidos.Text            = string.IsNullOrEmpty(contactoListDTO[i].t_apellidos) ? string.Empty : contactoListDTO[i].t_apellidos.ToString();
                        TxtNombres.Text            = string.IsNullOrEmpty(contactoListDTO[i].t_nombres) ? string.Empty : contactoListDTO[i].t_nombres.ToString();
                        TxtRazonSocial.Text        = string.IsNullOrEmpty(contactoListDTO[i].t_razon_social) ? string.Empty : contactoListDTO[i].t_razon_social.ToString();
                        TxtRazonComercial.Text     = string.IsNullOrEmpty(contactoListDTO[i].t_razon_comercial) ? string.Empty : contactoListDTO[i].t_razon_comercial.ToString();
                        TxtObservacion.Text        = string.IsNullOrEmpty(contactoListDTO[i].t_observacion) ? string.Empty : contactoListDTO[i].t_observacion.ToString();
                        TxtDireccion.Text          = string.IsNullOrEmpty(contactoListDTO[i].t_direccion) ? string.Empty : contactoListDTO[i].t_direccion.ToString();
                        TxtContacto.Text           = string.IsNullOrEmpty(contactoListDTO[i].t_contacto) ? string.Empty : contactoListDTO[i].t_contacto.ToString();
                        TxtActividadEconomica.Text = string.IsNullOrEmpty(contactoListDTO[i].t_actividad_economica) ? string.Empty : contactoListDTO[i].t_actividad_economica.ToString();
                        TxtTelefono1.Text          = string.IsNullOrEmpty(contactoListDTO[i].c_telefono1) ? string.Empty : contactoListDTO[i].c_telefono1.ToString();
                        TxtTelefono2.Text          = string.IsNullOrEmpty(contactoListDTO[i].c_telefono2) ? string.Empty : contactoListDTO[i].c_telefono2.ToString();
                        TxtEMail.Text            = string.IsNullOrEmpty(contactoListDTO[i].t_email_ffee) ? string.Empty : contactoListDTO[i].t_email_ffee.ToString();
                        TxtDiasCredito.Text      = contactoListDTO[i].n_dias_credito.ToString();
                        ChkEsGarante.Checked     = contactoListDTO[i].n_flag_garante.Equals(1);
                        ChkEsContratante.Checked = contactoListDTO[i].n_flag_contratante.Equals(1);
                        ChkEsProveedor.Checked   = contactoListDTO[i].n_flag_proveedor.Equals(1);
                        ChkHabido.Checked        = contactoListDTO[i].n_flag_habido.Equals(1);
                        cmbEstado.SelectedValue  = Convert.ToInt32(contactoListDTO[i].f_estado.ToString());
                    }
                }
                else if (jsonResponse.Warning)
                {
                    Mensaje.ShowMessageAlert(this.ParentForm, ConstantesWindows.TituloMensaje, jsonResponse.Message);
                }
            }
        }
Example #22
0
        public static Task <TResult> InvokeAsync <TViewModel, TResult>(this ViewModel viewModel, Action <TViewModel, Page> activateAction, bool animation = true)
            where TViewModel : FunctionViewModel <TResult>
        {
            var helper = new InvokeHelper <TViewModel, TResult>();

            viewModel.Navigation.PushAsync <TViewModel>(
                (vm, v) =>
            {
                vm.Result = default(TResult);
                if (activateAction != null)
                {
                    activateAction(vm, v);
                }
                helper.Attach(vm, v);
            });
            return(helper.TaskCompletionSource.Task);
        }
Example #23
0
        private void UpdateProgressbar(int progress)
        {
            InvokeHelper.Invoke(stateProgress, delegate() {
                int value = Math.Max(0, Math.Min(100, progress));
                value     = (int)Math.Floor((540f / 100f) * value);
                if (stateProgress.Width != value)
                {
                    stateProgress.Width = value;
                    stateProgress.Invalidate();
                }

                if (TaskbarManager.IsPlatformSupported)
                {
                    mWin7Taskbar.SetProgressValue(value, 100);
                }
            });
        }
Example #24
0
            public void setActive()
            {
                InvokeHelper ret = delegate
                {
                    try
                    {
                        GraphicsWindow.Show();
                        window.Activate();
                    }
                    catch (Exception ex)
                    {
                        Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                    }
                };

                FastThread.Invoke(ret);
            }
Example #25
0
File: Curry.cs Project: caoxk/coapp
        internal static bool TryConvert(object target, ConvertBinder binder, out object result)
        {
            result = null;
            if (!typeof(Delegate).IsAssignableFrom(binder.Type.BaseType))
            {
                return(false);
            }
            var      tDelMethodInfo = binder.Type.GetMethod("Invoke");
            var      tReturnType    = tDelMethodInfo.ReturnType;
            var      tAction        = tReturnType == typeof(void);
            var      tParams        = tDelMethodInfo.GetParameters();
            var      tLength        = tDelMethodInfo.GetParameters().Length;
            Delegate tBaseDelegate  = tAction
                ? InvokeHelper.WrapAction(target, tLength)
                : InvokeHelper.WrapFunc(tReturnType, target, tLength);

            if (!InvokeHelper.IsActionOrFunc(binder.Type) || tParams.Any(it => it.ParameterType.IsValueType))
            //Conditions that aren't contravariant;
            {
                Delegate tGetResult;

                if (!CompiledExpressions.TryGetValue(binder.Type, out tGetResult))
                {
                    var tParamTypes  = tParams.Select(it => it.ParameterType).ToArray();
                    var tDelParam    = Expression.Parameter(tBaseDelegate.GetType());
                    var tInnerParams = tParamTypes.Select(Expression.Parameter).ToArray();

                    var tI = Expression.Invoke(tDelParam,
                                               tInnerParams.Select(it => (Expression)Expression.Convert(it, typeof(object))));
                    var tL = Expression.Lambda(binder.Type, tI, tInnerParams);

                    tGetResult =
                        Expression.Lambda(Expression.GetFuncType(tBaseDelegate.GetType(), binder.Type), tL,
                                          tDelParam).Compile();
                    CompiledExpressions[binder.Type] = tGetResult;
                }

                result = tGetResult.DynamicInvoke(tBaseDelegate);

                return(true);
            }
            result = tBaseDelegate;

            return(true);
        }
Example #26
0
        private async Task <StreamingResult> InvokeStreamingMethodAsync(object instance, MethodInfo methodInfo, params object[] parameters)
        {
            var ch = await InvokeHelper.InvokeMethodAsync <object>(instance, methodInfo, parameters).ConfigureAwait(false);

            Type taskType = methodInfo.ReturnType;

            if (taskType.GetGenericTypeDefinition() == typeof(Task <>))
            {
                taskType = methodInfo.ReturnType.GenericTypeArguments[0];
            }


            var convType = typeof(StreamingResult <>).MakeGenericType(taskType.GenericTypeArguments[0]);

            var conv = (StreamingResult)Activator.CreateInstance(convType, ch, ClientContext, methodInfo);

            return(conv);
        }
Example #27
0
        private static void UpdateEmptyFolders(IXenConnection connection)
        {
            InvokeHelper.AssertOnEventThread();

            String[] emptyFolders = GetEmptyFolders(connection);

            Folder root = connection.Resolve(new XenRef <Folder>(PATH_SEPARATOR));

            if (root != null)
            {
                PurgeEmptyFolders(emptyFolders, root);
            }

            foreach (String path in emptyFolders)
            {
                GetOrCreateFolder(connection, path);
            }
        }
Example #28
0
        //Cambia de estado al registo
        private void EliminaRegistro(int idOcupacion)
        {
            bool result = false;

            try
            {
                var jsonResponse = new JsonResponse {
                    Success = false
                };

                jsonResponse = InvokeHelper.MakeRequest(ConstantesWindows.WS_Ocupacion_Delete, new ADM_OCUPACIONDTO {
                    id_ocupacion = idOcupacion, IdUsuarioActual = WindowsSession.UserIdActual, FechaModificacion = DateTime.Now
                }, ConstantesWindows.METHODPOST);

                if (jsonResponse.Success)
                {
                    if (jsonResponse.Warning)
                    {
                        result = false;
                        Mensaje.ShowMessageAlert(this.ParentForm, ConstantesWindows.TituloMensaje, jsonResponse.Message);
                    }
                    else
                    {
                        result = true;
                    }
                }
                else
                {
                    result = false;
                    Mensaje.ShowMessageAlert(this.ParentForm, ConstantesWindows.TituloMensaje, jsonResponse.Message);
                }

                if (result)
                {
                    //this.Close();
                    Mensaje.ShowMessageAlert(this.ParentForm, ConstantesWindows.TituloMensaje, jsonResponse.Message);
                    DialogResult = DialogResult.OK;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        //Obtiene datos por el id
        private void GetDatosProfesional()
        {
            if (txtIdProfesional.Text != "0")
            {
                var jsonResponse = new JsonResponse {
                    Success = false
                };

                jsonResponse = InvokeHelper.MakeRequest(ConstantesWindows.WS_ADM_PROFESIONAL_GetById, GetProfesional(), ConstantesWindows.METHODPOST);

                if (jsonResponse.Success && !jsonResponse.Warning)
                {
                    var ProfListDTO = (List <ADM_PROFESIONALDTO>)JsonConvert.DeserializeObject(jsonResponse.Data.ToString(), (new List <ADM_PROFESIONALDTO>()).GetType());
                    //this.ETUsuariobindingSource.DataSource = usuarioListDTO;
                    //--------------------------

                    for (int i = 0; i < ProfListDTO.Count; i++)
                    {
                        txtCodigo.Text        = string.IsNullOrEmpty(ProfListDTO[i].c_codigo) ? string.Empty : ProfListDTO[i].c_codigo.ToString();
                        txtApellidos.Text     = string.IsNullOrEmpty(ProfListDTO[i].t_apellidos) ? string.Empty : ProfListDTO[i].t_apellidos.ToString();
                        txtNombres.Text       = string.IsNullOrEmpty(ProfListDTO[i].t_nombres) ? string.Empty : ProfListDTO[i].t_nombres.ToString();
                        txtProfesional.Text   = string.IsNullOrEmpty(ProfListDTO[i].t_medico) ? string.Empty : ProfListDTO[i].t_medico.ToString();
                        txtDireccion.Text     = string.IsNullOrEmpty(ProfListDTO[i].t_direccion) ? string.Empty : ProfListDTO[i].t_direccion.ToString();
                        dtpFechaNac.Text      = ProfListDTO[i].d_fecha_nace.ToString();
                        cmbSexo.SelectedValue = Convert.ToInt32(ProfListDTO[i].id_genero.ToString());
                        cmbDocumentoIdentidad.SelectedValue = Convert.ToInt32(ProfListDTO[i].id_tipo_documento.ToString());
                        txtNumeroDocumento.Text             = string.IsNullOrEmpty(ProfListDTO[i].c_numero_documento) ? string.Empty : ProfListDTO[i].c_numero_documento.ToString();
                        cmbEspecialidad.SelectedValue       = Convert.ToInt32(ProfListDTO[i].id_especialidad.ToString());
                        txtNumeroEspecialidad.Text          = string.IsNullOrEmpty(ProfListDTO[i].c_nro_especialidad) ? string.Empty : ProfListDTO[i].c_nro_especialidad.ToString();
                        cmbTipoProfesional.SelectedValue    = Convert.ToInt32(ProfListDTO[i].id_tipo_profesional.ToString());
                        txtNumeroColegiatura.Text           = string.IsNullOrEmpty(ProfListDTO[i].c_colegiatura) ? string.Empty : ProfListDTO[i].c_colegiatura.ToString();
                        cmbCondicion.SelectedValue          = Convert.ToInt32(ProfListDTO[i].id_condicion_profesional.ToString());
                        txtTelefono1.Text       = string.IsNullOrEmpty(ProfListDTO[i].c_telefono_1) ? string.Empty : ProfListDTO[i].c_telefono_1.ToString();
                        txtTelefono2.Text       = string.IsNullOrEmpty(ProfListDTO[i].c_telefono_2) ? string.Empty : ProfListDTO[i].c_telefono_2.ToString();
                        cmbEstado.SelectedValue = Convert.ToInt32(ProfListDTO[i].f_estado.ToString());
                        txtObservacion.Text     = string.IsNullOrEmpty(ProfListDTO[i].t_observacion) ? string.Empty : ProfListDTO[i].t_observacion.ToString();
                    }
                }
                else if (jsonResponse.Warning)
                {
                    Mensaje.ShowMessageAlert(this.ParentForm, ConstantesWindows.TituloMensaje, jsonResponse.Message);
                }
            }
        }
Example #30
0
        internal static bool TryCreate(SecurityBindingElement sbe, EndToEndSecurityMode mode, Microsoft.ServiceBus.RelayClientAuthenticationType relayClientAuthenticationType, out NetOnewayRelaySecurity security)
        {
            MessageSecurityOverRelayOneway messageSecurityOverRelayOneway;

            security = null;
            if (!MessageSecurityOverRelayOneway.TryCreate(sbe, out messageSecurityOverRelayOneway))
            {
                messageSecurityOverRelayOneway = null;
            }
            security = new NetOnewayRelaySecurity(mode, relayClientAuthenticationType, null, messageSecurityOverRelayOneway);
            if (sbe == null)
            {
                return(true);
            }
            Type type = typeof(SecurityElementBase);

            object[] objArray = new object[] { security.CreateMessageSecurity(), sbe, false };
            return((bool)InvokeHelper.InvokeStaticMethod(type, "AreBindingsMatching", objArray));
        }
Example #31
0
        /// <summary>
        /// Set the background as an image.
        /// The backgound is auto rescaled to fill whatever size the GraphicsWindow is.
        /// </summary>
        /// <param name="imageName">
        /// The image to load as the background.
        /// Value returned from ImageList.LoadImage or local or network image file.
        /// </param>
        /// <returns>
        /// None.
        /// </returns>
        public static void BackgroundImage(Primitive imageName)
        {
            Type GraphicsWindowType = typeof(GraphicsWindow);
            Window _window;
            Type ImageListType = typeof(ImageList);
            Dictionary<string, BitmapSource> _savedImages;
            BitmapSource img;

            try
            {
                _window = (Window)GraphicsWindowType.GetField("_window", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                _savedImages = (Dictionary<string, BitmapSource>)ImageListType.GetField("_savedImages", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                if (!_savedImages.TryGetValue((string)imageName, out img))
                {
                    imageName = ImageList.LoadImage(imageName);
                    if (!_savedImages.TryGetValue((string)imageName, out img))
                    {
                        return;
                    }
                }
                InvokeHelper ret = new InvokeHelper(delegate
                {
                    try
                    {
                        _window.Background = new ImageBrush(img);
                    }
                    catch (Exception ex)
                    {
                        Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                    }
                });
                FastThread.Invoke(ret);
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #32
0
        /// <summary>
        /// Scale and move all Shapes and Contols within the GraphicsWindow.
        /// This method resizes and moves the view rather than the shapes, so their positions and other properties remain unchanged but appear scaled within the repositioned region.
        /// For example Shapes.GetLeft remains unchanged although the view has been repositioned and GraphicsWindow.MouseX reports the coordinates relative to the repositioned view.
        /// Imagine the entire view is repositioned as if it were a shape inside the GrapicsWindow.
        /// The transformation between view coordinates (vX,vY) and GraphicsWindow coordinates (gwX,gwY) is:
        /// gwX = (vX+panX)*scaleX + gw*(1-scaleX)/2
        /// gwY = (vY+panY)*scaleY + gh*(1-scaleY)/2
        /// All drawing remains within the original GraphicsWindow.
        /// </summary>
        /// <param name="scaleX">The X direction scaling of the view.</param>
        /// <param name="scaleY">The Y direction scaling of the view.</param>
        /// <param name="panX">Pan the view in the X direction in the view scaling, 0 is centered in the GraphicsWindow.</param>
        /// <param name="panY">Pan the view in the Y direction in the view scaling, 0 is centered in the GraphicsWindow.</param>
        /// <param name="angle">An angle to rotate the view.</param>
        public static void Reposition(Primitive scaleX, Primitive scaleY, Primitive panX, Primitive panY, Primitive angle)
        {
            Type GraphicsWindowType = typeof(GraphicsWindow);
            Canvas _mainCanvas;

            try
            {
                _mainCanvas = (Canvas)GraphicsWindowType.GetField("_mainCanvas", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                InvokeHelper ret = new InvokeHelper(delegate
                {
                    try
                    {
                        GetTransforms(_mainCanvas);

                        translateTransform.X = panX;
                        translateTransform.Y = panY;

                        scaleTransform.ScaleX = scaleX;
                        scaleTransform.ScaleY = scaleY;

                        rotateTransform.Angle = angle;

                        //Grid grid = (Grid)_mainCanvas.Parent;
                        //System.Windows.Point pointView = new System.Windows.Point(GraphicsWindow.Width / 2, GraphicsWindow.Height / 2);
                        //System.Windows.Point pointGW = grid.PointFromScreen(_mainCanvas.PointToScreen(pointView));
                        //TextWindow.WriteLine(rotateTransform.CenterX + " , " + pointGW.X);
                        //rotateTransform.CenterX = pointGW.X;
                        //rotateTransform.CenterY = pointGW.Y;

                        _mainCanvas.InvalidateVisual();
                    }
                    catch (Exception ex)
                    {
                        Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                    }
                });
                FastThread.Invoke(ret);
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #33
0
        /// <summary>
        /// Create a transparent GraphicsWindow.
        /// This must be the called before any other GraphicsWindow, Controls or Shapes methods that create a window.
        /// To see anything you must add something to the transparent GraphicsWindow.
        /// For example, create a non-rectangular window using a transparent border png with LDShapes.BackgroundImage.
        /// The transparency can be altered with GraphicsWindow.BackgroundColor.
        /// Sometimes less than 100% transparency can be required (e.g. to register mouse movements).
        /// </summary>
        public static void TransparentGW()
        {
            Type GraphicsWindowType = typeof(GraphicsWindow);
            Window _window;

            try
            {
                GraphicsWindowType.GetField("_isHidden", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).SetValue(null, true);
                GraphicsWindowType.GetMethod("CreateWindow", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, new object[] { });
                _window = (Window)GraphicsWindowType.GetField("_window", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                InvokeHelper ret = new InvokeHelper(delegate
                {
                    try
                    {
                        _window.AllowsTransparency = true;
                        _window.WindowStyle = WindowStyle.None;
                    }
                    catch (Exception ex)
                    {
                        Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                    }
                });
                FastThread.Invoke(ret);
                GraphicsWindow.BackgroundColor = LDColours.Transparent;
                GraphicsWindow.Show();
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #34
0
 /// <summary>
 /// Set a shape to animate opacity, flash (fade out and in).
 /// </summary>
 /// <param name="shapeName">The shape or control to flash.</param>
 /// <param name="interval">The interval in ms for a complete flash cycle.
 /// A value of 0 will stop the flashing.</param>
 /// <param name="count">The number of flashes.
 /// A value of 0 will flash continuously.</param>
 public static void AnimateOpacity(Primitive shapeName, Primitive interval, Primitive count)
 {
     try
     {
         if (_objectsMap.TryGetValue((string)shapeName, out obj))
         {
             try
             {
                 InvokeHelper ret = new InvokeHelper(delegate
                 {
                     if (interval > 0)
                     {
                         DoubleAnimation animation = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(interval / 2));
                         animation.AccelerationRatio = 0.4;
                         animation.DecelerationRatio = 0.4;
                         animation.RepeatBehavior = (count > 0) ? new RepeatBehavior(count) : RepeatBehavior.Forever;
                         animation.AutoReverse = true;
                         obj.BeginAnimation(UIElement.OpacityProperty, animation);
                     }
                     else
                     {
                         obj.BeginAnimation(UIElement.OpacityProperty, null);
                     }
                 });
                 FastThread.Invoke(ret);
             }
             catch (Exception ex)
             {
                 Utilities.OnError(Utilities.GetCurrentMethod(), ex);
             }
         }
         else
         {
             Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }
Example #35
0
        /// <summary>
        /// Set a shape to animate zooming (in and out).
        /// </summary>
        /// <param name="shapeName">The shape or control to zoom.</param>
        /// <param name="interval">The interval in ms for a complete zoom cycle.
        /// A value of 0 will stop the zooming.</param>
        /// <param name="count">The number of zoom cycles.
        /// A value of 0 will zoom continuously.</param>
        /// <param name="scaleX">The X zoom scale factor.</param>
        /// <param name="scaleY">The Y zoom scale factor.</param>
        public static void AnimateZoom(Primitive shapeName, Primitive interval, Primitive count, Primitive scaleX, Primitive scaleY)
        {
            Type ShapesType = typeof(Shapes);
            Dictionary<string, ScaleTransform> _scaleTransformMap;
            ScaleTransform scaleTransform;

            try
            {
                _scaleTransformMap = (Dictionary<string, ScaleTransform>)ShapesType.GetField("_scaleTransformMap", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                if (!_scaleTransformMap.TryGetValue((string)shapeName, out scaleTransform))
                {
                    Shapes.Zoom(shapeName, 1, 1);
                    Utilities.doUpdates();
                }
                if (_objectsMap.TryGetValue((string)shapeName, out obj) && _scaleTransformMap.TryGetValue((string)shapeName, out scaleTransform))
                {
                    InvokeHelper ret = new InvokeHelper(delegate
                    {
                        try
                        {
                            if (interval != 0)
                            {
                                DoubleAnimation animationX = new DoubleAnimation(1, scaleX, TimeSpan.FromMilliseconds(interval / 2));
                                animationX.RepeatBehavior = (count > 0) ? new RepeatBehavior(count) : RepeatBehavior.Forever;
                                animationX.AutoReverse = true;
                                animationX.AccelerationRatio = 0.4;
                                animationX.DecelerationRatio = 0.4;
                                DoubleAnimation animationY = new DoubleAnimation(1, scaleY, TimeSpan.FromMilliseconds(interval / 2));
                                animationY.RepeatBehavior = (count > 0) ? new RepeatBehavior(count) : RepeatBehavior.Forever;
                                animationY.AutoReverse = true;
                                animationY.AccelerationRatio = 0.4;
                                animationY.DecelerationRatio = 0.4;
                                scaleTransform.BeginAnimation(ScaleTransform.ScaleXProperty, animationX);
                                scaleTransform.BeginAnimation(ScaleTransform.ScaleYProperty, animationY);
                            }
                            else
                            {
                                scaleTransform.BeginAnimation(ScaleTransform.ScaleXProperty, null);
                                scaleTransform.BeginAnimation(ScaleTransform.ScaleYProperty, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                        }
                    });
                    FastThread.Invoke(ret);
                }
                else
                {
                    Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
                }
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #36
0
 /// <summary>
 /// Set shape Pen width.
 /// </summary>
 /// <param name="shapeName">
 /// The shape or control name.
 /// </param>
 /// <param name="width">
 /// The new pen width.
 /// </param>
 /// <returns>
 /// None.
 /// </returns>
 public static void PenWidth(Primitive shapeName, Primitive width)
 {
     try
     {
         if (_objectsMap.TryGetValue((string)shapeName, out obj))
         {
             InvokeHelper ret = new InvokeHelper(delegate
             {
                 try
                 {
                     if (obj.GetType() == typeof(Ellipse))
                     {
                         Ellipse shape = (Ellipse)obj;
                         shape.StrokeThickness = width;
                     }
                     else if (obj.GetType() == typeof(Rectangle))
                     {
                         Rectangle shape = (Rectangle)obj;
                         shape.StrokeThickness = width;
                     }
                     else if (obj.GetType() == typeof(Polygon))
                     {
                         Polygon shape = (Polygon)obj;
                         shape.StrokeThickness = width;
                     }
                     else if (obj.GetType() == typeof(Line))
                     {
                         Line shape = (Line)obj;
                         shape.StrokeThickness = width;
                     }
                 }
                 catch (Exception ex)
                 {
                     Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                 }
             });
             FastThread.Invoke(ret);
         }
         else
         {
             Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }
Example #37
0
 /// <summary>
 /// Set shape z index (layer position negative are background and positive are foreground - default 0).
 /// </summary>
 /// <param name="shapeName">
 /// The shape or control name.
 /// </param>
 /// <param name="z_index">
 /// The z-index (zero, positive or negative interger).
 /// </param>
 /// <returns>
 /// None.
 /// </returns>
 public static void ZIndex(Primitive shapeName, Primitive z_index)
 {
     try
     {
         if (_objectsMap.TryGetValue((string)shapeName, out obj))
         {
             InvokeHelper ret = new InvokeHelper(delegate
             {
                 try
                 {
                     Canvas.SetZIndex(obj, z_index);
                 }
                 catch (Exception ex)
                 {
                     Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                 }
             });
             FastThread.Invoke(ret);
         }
         else
         {
             Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }
Example #38
0
 /// <summary>
 /// Set shape Pen colour.
 /// </summary>
 /// <param name="shapeName">
 /// The shape or control name.
 /// </param>
 /// <param name="colour">
 /// The new pen colour.
 /// </param>
 /// <returns>
 /// None.
 /// </returns>
 public static void PenColour(Primitive shapeName, Primitive colour)
 {
     try
     {
         if (_objectsMap.TryGetValue((string)shapeName, out obj))
         {
             InvokeHelper ret = new InvokeHelper(delegate
             {
                 try
                 {
                     if (obj.GetType() == typeof(Ellipse))
                     {
                         Ellipse shape = (Ellipse)obj;
                         shape.Stroke = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(Rectangle))
                     {
                         Rectangle shape = (Rectangle)obj;
                         shape.Stroke = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(Polygon))
                     {
                         Polygon shape = (Polygon)obj;
                         shape.Stroke = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(Line))
                     {
                         Line shape = (Line)obj;
                         shape.Stroke = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(Button))
                     {
                         Button shape = (Button)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(TextBlock))
                     {
                         TextBlock shape = (TextBlock)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(TextBox))
                     {
                         TextBox shape = (TextBox)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(PasswordBox))
                     {
                         PasswordBox shape = (PasswordBox)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(CheckBox))
                     {
                         CheckBox shape = (CheckBox)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(ComboBox))
                     {
                         ComboBox shape = (ComboBox)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(RadioButton))
                     {
                         RadioButton shape = (RadioButton)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(RichTextBox))
                     {
                         RichTextBox shape = (RichTextBox)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(TreeView))
                     {
                         TreeView shape = (TreeView)obj;
                         treeViewPenColour(shape.Items, new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour)));
                     }
                     else if (obj.GetType() == typeof(DocumentViewer))
                     {
                         DocumentViewer shape = (DocumentViewer)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(ListBox))
                     {
                         ListBox shape = (ListBox)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(ListView))
                     {
                         ListView shape = (ListView)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(WindowsFormsHost))
                     {
                         WindowsFormsHost shape = (WindowsFormsHost)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                         if (shape.Child.GetType() == typeof(System.Windows.Forms.DataGridView))
                         {
                             System.Windows.Forms.DataGridView dataView = (System.Windows.Forms.DataGridView)shape.Child;
                         }
                     }
                     else if (obj.GetType() == typeof(ProgressBar))
                     {
                         ProgressBar shape = (ProgressBar)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(Slider))
                     {
                         Slider shape = (Slider)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                     else if (obj.GetType() == typeof(Menu))
                     {
                         Menu shape = (Menu)obj;
                         shape.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colour));
                     }
                 }
                 catch (Exception ex)
                 {
                     Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                 }
             });
             FastThread.Invoke(ret);
         }
         else
         {
             Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }
Example #39
0
 /// <summary>
 /// Set shape Pen style (dash, dot etc).
 /// </summary>
 /// <param name="shapeName">
 /// The shape name.
 /// </param>
 /// <param name="dash">
 /// The dash length.
 /// </param>
 /// <param name="space">
 /// The space length.
 /// </param>
 /// <returns>
 /// None.
 /// </returns>
 public static void PenStyle(Primitive shapeName, Primitive dash, Primitive space)
 {
     try
     {
         if (_objectsMap.TryGetValue((string)shapeName, out obj))
         {
             InvokeHelper ret = new InvokeHelper(delegate
             {
                 try
                 {
                     if (obj.GetType() == typeof(Ellipse))
                     {
                         Ellipse shape = (Ellipse)obj;
                         DoubleCollection style = new DoubleCollection();
                         style.Add(dash);
                         style.Add(space);
                         shape.StrokeDashArray = style;
                     }
                     else if (obj.GetType() == typeof(Rectangle))
                     {
                         Rectangle shape = (Rectangle)obj;
                         DoubleCollection style = new DoubleCollection();
                         style.Add(dash);
                         style.Add(space);
                         shape.StrokeDashArray = style;
                     }
                     else if (obj.GetType() == typeof(Polygon))
                     {
                         Polygon shape = (Polygon)obj;
                         DoubleCollection style = new DoubleCollection();
                         style.Add(dash);
                         style.Add(space);
                         shape.StrokeDashArray = style;
                     }
                     else if (obj.GetType() == typeof(Line))
                     {
                         Line shape = (Line)obj;
                         DoubleCollection style = new DoubleCollection();
                         style.Add(dash);
                         style.Add(space);
                         shape.StrokeDashArray = style;
                     }
                 }
                 catch (Exception ex)
                 {
                     Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                 }
             });
             FastThread.Invoke(ret);
         }
         else
         {
             Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }
Example #40
0
 /// <summary>
 /// Moves a triangle shape.
 /// </summary>
 /// <param name="shapeName">
 /// The shape name (a triangle created with Shapes.AddTriangle).
 /// </param>
 /// <param name="x1">
 /// The first X coordinate to move the triangle to.
 /// </param>
 /// <param name="y1">
 /// The first Y coordinate to move the triangle to.
 /// </param>
 /// <param name="x2">
 /// The second X coordinate to move the triangle to.
 /// </param>
 /// <param name="y2">
 /// The second Y coordinate to move the triangle to.
 /// </param>
 /// <param name="x3">
 /// The third X coordinate to move the triangle to.
 /// </param>
 /// <param name="y3">
 /// The third Y coordinate to move the triangle to.
 /// </param>
 /// <returns>
 /// None.
 /// </returns>
 public static void MoveTriangle(Primitive shapeName, Primitive x1, Primitive y1, Primitive x2, Primitive y2, Primitive x3, Primitive y3)
 {
     try
     {
         if (_objectsMap.TryGetValue((string)shapeName, out obj))
         {
             InvokeHelper ret = new InvokeHelper(delegate
             {
                 try
                 {
                     Polygon shape = (Polygon)obj;
                     System.Windows.Point Point1 = new System.Windows.Point(x1, y1);
                     System.Windows.Point Point2 = new System.Windows.Point(x2, y2);
                     System.Windows.Point Point3 = new System.Windows.Point(x3, y3);
                     PointCollection pointCollection = new PointCollection();
                     pointCollection.Add(Point1);
                     pointCollection.Add(Point2);
                     pointCollection.Add(Point3);
                     shape.Points = pointCollection;
                 }
                 catch (Exception ex)
                 {
                     Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                 }
             });
             FastThread.Invoke(ret);
         }
         else
         {
             Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }
Example #41
0
 /// <summary>
 /// Moves a polygon shape.
 /// </summary>
 /// <param name="shapeName">
 /// The shape name (a polygon created with LDShapes.AddPolygon).
 /// </param>
 /// <param name="points">
 /// An array of new coordinates for the polygon corners with the form points[i][1] = x, points[i][2] = y.
 /// 
 /// The number of points must be 3 or more and can change with each call.
 /// </param>
 /// <returns>
 /// None.
 /// </returns>
 public static void MovePolygon(Primitive shapeName, Primitive points)
 {
     try
     {
         if (_objectsMap.TryGetValue((string)shapeName, out obj))
         {
             InvokeHelper ret = new InvokeHelper(delegate
             {
                 try
                 {
                     Polygon shape = (Polygon)obj;
                     PointCollection _points = getPoints(points);
                     if (_points.Count >= 3) shape.Points = _points;
                 }
                 catch (Exception ex)
                 {
                     Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                 }
             });
             FastThread.Invoke(ret);
         }
         else
         {
             Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }
Example #42
0
 /// <summary>
 /// Moves a line shape.
 /// </summary>
 /// <param name="shapeName">
 /// The shape name (a line created with Shapes.AddLine).
 /// </param>
 /// <param name="x1">
 /// The first X coordinate to move the line to.
 /// </param>
 /// <param name="y1">
 /// The first Y coordinate to move the line to.
 /// </param>
 /// <param name="x2">
 /// The second X coordinate to move the line to.
 /// </param>
 /// <param name="y2">
 /// The second Y coordinate to move the line to.
 /// </param>
 /// <returns>
 /// None.
 /// </returns>
 public static void MoveLine(Primitive shapeName, Primitive x1, Primitive y1, Primitive x2, Primitive y2)
 {
     try
     {
         if (_objectsMap.TryGetValue((string)shapeName, out obj))
         {
             InvokeHelper ret = new InvokeHelper(delegate
             {
                 try
                 {
                     Line shape = (Line)obj;
                     shape.X1 = x1;
                     shape.X2 = x2;
                     shape.Y1 = y1;
                     shape.Y2 = y2;
                 }
                 catch (Exception ex)
                 {
                     Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                 }
             });
             FastThread.Invoke(ret);
         }
         else
         {
             Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }
Example #43
0
 /// <summary>
 /// Set a shape Brush style as a gradient of colours.
 /// </summary>
 /// <param name="shapeName">
 /// The shape or control name.
 /// </param>
 /// <param name="brush">
 /// A previously created gradient or image brush (LDShapes.BrushGradient LDShapes.BrushImage).
 /// </param>
 /// <returns>
 /// None.
 /// </returns>
 public static void BrushShape(Primitive shapeName, Primitive brush)
 {
     try
     {
         if (_objectsMap.TryGetValue((string)shapeName, out obj))
         {
             InvokeHelper ret = new InvokeHelper(delegate
             {
                 try
                 {
                     foreach (GradientBrush i in brushes)
                     {
                         if (i.name == brush)
                         {
                             if (obj.GetType() == typeof(Ellipse))
                             {
                                 Ellipse shape = (Ellipse)obj;
                                 shape.Fill = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(Rectangle))
                             {
                                 Rectangle shape = (Rectangle)obj;
                                 shape.Fill = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(Polygon))
                             {
                                 Polygon shape = (Polygon)obj;
                                 shape.Fill = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(Button))
                             {
                                 Button shape = (Button)obj;
                                 shape.Background = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(TextBlock))
                             {
                                 TextBlock shape = (TextBlock)obj;
                                 shape.Background = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(TextBox))
                             {
                                 TextBox shape = (TextBox)obj;
                                 shape.Background = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(PasswordBox))
                             {
                                 PasswordBox shape = (PasswordBox)obj;
                                 shape.Background = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(CheckBox))
                             {
                                 CheckBox shape = (CheckBox)obj;
                                 shape.Background = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(ComboBox))
                             {
                                 ComboBox shape = (ComboBox)obj;
                                 shape.Background = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(RadioButton))
                             {
                                 RadioButton shape = (RadioButton)obj;
                                 shape.Background = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(RichTextBox))
                             {
                                 RichTextBox shape = (RichTextBox)obj;
                                 shape.Background = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(TreeView))
                             {
                                 TreeView shape = (TreeView)obj;
                                 shape.Background = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(DocumentViewer))
                             {
                                 DocumentViewer shape = (DocumentViewer)obj;
                                 shape.Background = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(ListBox))
                             {
                                 ListBox shape = (ListBox)obj;
                                 shape.Background = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(ListView))
                             {
                                 ListView shape = (ListView)obj;
                                 shape.Background = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(WindowsFormsHost))
                             {
                                 WindowsFormsHost shape = (WindowsFormsHost)obj;
                                 shape.Background = i.getBrush();
                                 if (shape.Child.GetType() == typeof(System.Windows.Forms.DataGridView))
                                 {
                                     System.Windows.Forms.DataGridView dataView = (System.Windows.Forms.DataGridView)shape.Child;
                                 }
                             }
                             else if (obj.GetType() == typeof(ProgressBar))
                             {
                                 ProgressBar shape = (ProgressBar)obj;
                                 shape.Background = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(Slider))
                             {
                                 Slider shape = (Slider)obj;
                                 shape.Background = i.getBrush();
                             }
                             else if (obj.GetType() == typeof(Menu))
                             {
                                 Menu shape = (Menu)obj;
                                 shape.Background = i.getBrush();
                             }
                         }
                     }
                 }
                 catch (Exception ex)
                 {
                     Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                 }
             });
             FastThread.Invoke(ret);
         }
         else
         {
             Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }
Example #44
0
        /// <summary>
        /// Rasterise all turtle trail lines.
        /// When the number of turtle trails is large the program may slow due to the number of line shapes (trails) present.
        /// This converts the turtle trails from line shapes to background drawings. 
        /// </summary>
        public static void RasteriseTurtleLines()
        {
            FieldInfo _penField;
            Pen _pen;

            try
            {
                _penField = GraphicsWindowType.GetField("_pen", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase);
                _pen = (Pen)_penField.GetValue(null);
                InvokeHelper ret = new InvokeHelper(delegate
                {
                    try
                    {
                        Pen pen = new Pen();
                        Line line;
                        List<string> shapes = new List<string>();
                        foreach (KeyValuePair<string, UIElement> obj in _objectsMap)
                        {
                            if (obj.Key.StartsWith("_turtleLine"))
                            {
                                line = (Line)obj.Value;
                                pen.Brush = line.Stroke;
                                pen.Thickness = line.StrokeThickness;
                                _penField.SetValue(null, pen);
                                GraphicsWindow.DrawLine(line.X1, line.Y1, line.X2, line.Y2);
                                shapes.Add(obj.Key);
                            }
                        }
                        foreach (string shape in shapes)
                        {
                            Shapes.Remove(shape);
                        }
                        _penField.SetValue(null, _pen);
                    }
                    catch (Exception ex)
                    {
                        Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                    }
                });
                FastThread.Invoke(ret);
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #45
0
        /// <summary>
        /// Skews the shape with the specified name by the specified angles.
        /// </summary>
        /// <param name="shapeName">
        /// The name of the shape to skew.
        /// </param>
        /// <param name="angleX">
        /// The angle to skew the shape in the X direction.
        /// </param>
        /// <param name="angleY">
        /// The angle to skew the shape in the Y direction.
        /// </param>
        /// <returns>
        /// None.
        /// </returns>
        public static void Skew(Primitive shapeName, Primitive angleX, Primitive angleY)
        {
            try
            {
                if (!_objectsMap.TryGetValue((string)shapeName, out obj))
                {
                    Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
                    return;
                }

                InvokeHelper ret = new InvokeHelper(delegate
                {
                    try
                    {
                        if (!(obj.RenderTransform is TransformGroup))
                        {
                            obj.RenderTransform = new TransformGroup();
                        }
                        SkewTransform skewTransform;
                        if (!_skewTransformMap.TryGetValue(shapeName, out skewTransform))
                        {
                            skewTransform = new SkewTransform();
                            _skewTransformMap[shapeName] = skewTransform;
                            FrameworkElement frameworkElement = obj as FrameworkElement;
                            if (frameworkElement != null)
                            {
                                skewTransform.CenterX = frameworkElement.ActualWidth / 2.0;
                                skewTransform.CenterY = frameworkElement.ActualHeight / 2.0;
                            }
                            ((TransformGroup)obj.RenderTransform).Children.Add(skewTransform);
                        }
                        skewTransform.AngleX = angleX;
                        skewTransform.AngleY = angleY;
                    }
                    catch (Exception ex)
                    {
                        Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                    }
                });
                FastThread.Invoke(ret);
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #46
0
        /// <summary>
        /// Resize shape width and height (an absolute version of zoom).
        /// </summary>
        /// <param name="shapeName">
        /// The shape or control name.
        /// </param>
        /// <param name="width">
        /// The shape width.
        /// </param>
        /// <param name="height">
        /// The shape height.
        /// </param>
        /// <returns>
        /// None.
        /// </returns>
        public static void ReSize(Primitive shapeName, Primitive width, Primitive height)
        {
            Dictionary<string, ScaleTransform> _scaleTransformMap;
            ScaleTransform scaleTransform;

            try
            {
                _scaleTransformMap = (Dictionary<string, ScaleTransform>)GraphicsWindowType.GetField("_scaleTransformMap", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                if (_objectsMap.TryGetValue((string)shapeName, out obj))
                {
                    InvokeHelper ret = new InvokeHelper(delegate
                    {
                        try
                        {
                            FrameworkElement frameworkElement = obj as FrameworkElement;
                            if (!(obj.RenderTransform is TransformGroup))
                            {
                                obj.RenderTransform = new TransformGroup();
                            }
                            if (!_scaleTransformMap.TryGetValue((string)shapeName, out scaleTransform))
                            {
                                scaleTransform = new ScaleTransform();
                                _scaleTransformMap[shapeName] = scaleTransform;
                                if (frameworkElement != null)
                                {
                                    scaleTransform.CenterX = frameworkElement.ActualWidth / 2.0;
                                    scaleTransform.CenterY = frameworkElement.ActualHeight / 2.0;
                                }
                                ((TransformGroup)obj.RenderTransform).Children.Add(scaleTransform);
                            }
                            if (frameworkElement != null)
                            {
                                scaleTransform.ScaleX = width / frameworkElement.Width;
                                scaleTransform.ScaleY = height / frameworkElement.Height;
                            }
                        }
                        catch (Exception ex)
                        {
                            Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                        }
                    });
                    FastThread.Invoke(ret);
                }
                else
                {
                    Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
                }
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #47
0
        /// <summary>
        /// Zoom all shapes.
        /// </summary>
        /// <param name="scaleX">The x-axis zoom level.</param>
        /// <param name="scaleY">The y-axis zoom level.</param>
        public static void ZoomAll(Primitive scaleX, Primitive scaleY)
        {
            Type ShapesType = typeof(Shapes);
            Dictionary<string, ScaleTransform> _scaleTransformMap;
            string shapeName;
            ScaleTransform scaleTransform;

            try
            {
                _scaleTransformMap = (Dictionary<string, ScaleTransform>)GraphicsWindowType.GetField("_scaleTransformMap", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                InvokeHelper ret = new InvokeHelper(delegate
                {
                    try
                    {
                        foreach (var pair in _objectsMap)
                        {
                            shapeName = pair.Key;
                            if (_scaleTransformMap.TryGetValue(shapeName, out scaleTransform))
                            {
                                scaleTransform.ScaleX = scaleX;
                                scaleTransform.ScaleY = scaleY;
                            }
                            else
                            {
                                Shapes.Zoom(shapeName, scaleX, scaleY);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                    }
                });
                FastThread.Invoke(ret);
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #48
0
        /// <summary>
        /// Rotate a shape about a point.
        /// </summary>
        /// <param name="shapeName">
        /// The shape name.
        /// </param>
        /// <param name="x">
        /// The X coordinate to rotate the shape about.
        /// </param>
        /// <param name="y">
        /// The Y coordinate to rotate the shape about.
        /// </param>
        /// <param name="angle">
        /// The angle in degrees to rotate the shape.
        /// </param>
        /// <returns>
        /// None.
        /// </returns>
        public static void RotateAbout(Primitive shapeName, Primitive x, Primitive y, Primitive angle)
        {
            Type ShapesType = typeof(Shapes);
            Dictionary<string, RotateTransform> _rotateTransformMap;

            try
            {
                _rotateTransformMap = (Dictionary<string, RotateTransform>)ShapesType.GetField("_rotateTransformMap", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                if (_objectsMap.TryGetValue((string)shapeName, out obj))
                {
                    InvokeHelper ret = new InvokeHelper(delegate
                    {
                        try
                        {
                            if (!(obj.RenderTransform is TransformGroup))
                            {
                                obj.RenderTransform = new TransformGroup();
                            }
                            RotateTransform rotateTransform;
                            if (!_rotateTransformMap.TryGetValue(shapeName, out rotateTransform))
                            {
                                rotateTransform = new RotateTransform();
                                ((TransformGroup)obj.RenderTransform).Children.Add(rotateTransform);
                                _rotateTransformMap[shapeName] = rotateTransform;
                            }
                            rotateTransform.CenterX = x - Shapes.GetLeft(shapeName);
                            rotateTransform.CenterY = y - Shapes.GetTop(shapeName);
                            rotateTransform.Angle = angle;
                        }
                        catch (Exception ex)
                        {
                            Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                        }
                    });
                    FastThread.Invoke(ret);
                }
                else
                {
                    Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
                }
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #49
0
        /// <summary>
        /// Set a shape to animate rotation (rotate continuously).
        /// </summary>
        /// <param name="shapeName">The shape or control to rotate.</param>
        /// <param name="interval">The interval in ms for a complete 360 degree rotation.
        /// A value of 0 will stop the rotation.
        /// A value less than 0 will rotate anti-clockwise.</param>
        /// <param name="count">The number of rotations.
        /// A value of 0 will rotate continuously.</param>
        public static void AnimateRotation(Primitive shapeName, Primitive interval, Primitive count)
        {
            Type ShapesType = typeof(Shapes);
            Dictionary<string, RotateTransform> _rotateTransformMap;
            RotateTransform rotateTransform;

            try
            {
                _rotateTransformMap = (Dictionary<string, RotateTransform>)ShapesType.GetField("_rotateTransformMap", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                if (!_rotateTransformMap.TryGetValue((string)shapeName, out rotateTransform))
                {
                    Shapes.Rotate(shapeName, 0);
                    Utilities.doUpdates();
                }
                if (_objectsMap.TryGetValue((string)shapeName, out obj) && _rotateTransformMap.TryGetValue((string)shapeName, out rotateTransform))
                {
                    InvokeHelper ret = new InvokeHelper(delegate
                    {
                        try
                        {
                            if (interval != 0)
                            {
                                double start = interval > 0 ? 0 : 360;
                                double end = interval > 0 ? 360 : 0;
                                DoubleAnimation animation = new DoubleAnimation(start, end, TimeSpan.FromMilliseconds(System.Math.Abs(interval)));
                                animation.RepeatBehavior = (count > 0) ? new RepeatBehavior(count) : RepeatBehavior.Forever;
                                animation.AutoReverse = false;
                                rotateTransform.BeginAnimation(RotateTransform.AngleProperty, animation);
                            }
                            else
                            {
                                rotateTransform.BeginAnimation(RotateTransform.AngleProperty, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                        }
                    });
                    FastThread.Invoke(ret);
                }
                else
                {
                    Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
                }
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #50
0
        /// <summary>
        /// Set or change an image in a button or image shape.
        /// </summary>
        /// <param name="shapeName">
        /// The image or button name.
        /// </param>
        /// <param name="imageName">
        /// The image to load.
        /// Value returned from ImageList.LoadImage or local or network image file.
        /// </param>
        /// <returns>
        /// None.
        /// </returns>
        public static void SetImage(Primitive shapeName, Primitive imageName)
        {
            Type ImageListType = typeof(ImageList);
            Dictionary<string, BitmapSource> _savedImages;
            BitmapSource img;

            try
            {
                if (!_objectsMap.TryGetValue((string)shapeName, out obj))
                {
                    Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
                    return;
                }
                _savedImages = (Dictionary<string, BitmapSource>)ImageListType.GetField("_savedImages", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                if (!_savedImages.TryGetValue((string)imageName, out img))
                {
                    imageName = ImageList.LoadImage(imageName);
                    if (!_savedImages.TryGetValue((string)imageName, out img))
                    {
                        return;
                    }
                }

                InvokeHelper ret = new InvokeHelper(delegate
                {
                    try
                    {
                        if (obj.GetType() == typeof(Image))
                        {
                            Image shape = ((Image)obj);
                            shape.Source = img;
                            shape.Stretch = Stretch.Fill;
                        }
                        else if (obj.GetType() == typeof(Button))
                        {
                            Image image = new Image();
                            image.Source = img;
                            image.Stretch = Stretch.Fill;
                            Button shape = ((Button)obj);
                            shape.Content = image;
                            shape.Padding = new Thickness(0.0);
                        }
                    }
                    catch (Exception ex)
                    {
                        Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                    }
                });
                FastThread.Invoke(ret);
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #51
0
        /// <summary>
        /// Fill a region surrounding a specified pixel.
        /// All neighbour pixels of the same colour are changed.
        /// This only applies to the drawing layer of the GraphicsWindow.
        /// </summary>
        /// <param name="x">
        /// The x co-ordinate of the pixel to start the fill.
        /// </param>
        /// <param name="y">
        /// The y co-ordinate of the pixel to start the fill.
        /// </param>
        /// <param name="colour">
        /// The colour to fill with.
        /// </param>
        public static void FloodFill(Primitive x, Primitive y, Primitive colour)
        {
            Type GraphicsWindowType = typeof(GraphicsWindow);
            x = (int)x;
            y = (int)y;

            try
            {
                InvokeHelper ret = new InvokeHelper(delegate
                {
                    try
                    {
                        //Prepare bitmap
                        GraphicsWindowType.GetMethod("Rasterize", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, new object[] { });
                        RenderTargetBitmap _renderBitmap = (RenderTargetBitmap)GraphicsWindowType.GetField("_renderBitmap", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
                        FastPixel fp = new FastPixel(_renderBitmap);
                        System.Drawing.Color colNew = ColorTranslator.FromHtml(colour);
                        System.Drawing.Color colOld = fp.GetPixel(x, y);
                        if (colNew == colOld) return;
                        int nx = fp.Width;
                        int ny = fp.Height;

                        Stack<int> points = new Stack<int>();
                        int point, _x, _y;
                        points.Push(y * nx + x);
                        while (points.Count > 0)
                        {
                            point = points.Pop();
                            _x = point % nx;
                            _y = point / nx;
                            fp.SetPixel(_x, _y, colNew);
                            if (_x > 0 && colOld == fp.GetPixel(_x - 1, _y)) points.Push(_y * nx + _x - 1);
                            if (_x < nx - 1 && colOld == fp.GetPixel(_x + 1, _y)) points.Push(_y * nx + _x + 1);
                            if (_y > 0 && colOld == fp.GetPixel(_x, _y - 1)) points.Push((_y - 1) * nx + _x);
                            if (_y < ny - 1 && colOld == fp.GetPixel(_x, _y + 1)) points.Push((_y + 1) * nx + _x);
                        }
                        fp.Unlock(true);

                        //Display bitmap
                        BitmapImage bitmapImage = fp.BitmapImage;
                        DrawingGroup _mainDrawing = (DrawingGroup)GraphicsWindowType.GetField("_mainDrawing", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                        DrawingContext drawingContext = _mainDrawing.Append();
                        drawingContext.DrawImage(bitmapImage, new Rect(0, 0, nx, ny));
                        drawingContext.Close();
                        _renderBitmap.Clear();
                        GraphicsWindowType.GetMethod("AddRasterizeOperationToQueue", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).Invoke(null, new object[] { });
                    }
                    catch (Exception ex)
                    {
                        Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                    }
                });
                FastThread.Invoke(ret);
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #52
0
 /// <summary>
 /// Set a shape property.  This is a .Net UIElement property.
 /// </summary>
 /// <param name="shapeName">The shape or control name.</param>
 /// <param name="property">The property name to set.</param>
 /// <param name="value">The value to set the property to.</param>
 public static void SetProperty(Primitive shapeName, Primitive property, Primitive value)
 {
     try
     {
         if (_objectsMap.TryGetValue((string)shapeName, out obj))
         {
             InvokeHelper ret = new InvokeHelper(delegate
             {
                 try
                 {
                     PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
                     propertyInfo.SetValue(obj, TypeDescriptor.GetConverter(propertyInfo.PropertyType).ConvertFromString((string)value), null);
                 }
                 catch (Exception ex)
                 {
                     Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                 }
             });
             FastThread.Invoke(ret);
         }
         else
         {
             Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }
Example #53
0
        /// <summary>
        /// Get coordinates transformed between GraphicsWindow and a repositioned View (See Reposition).
        /// </summary>
        /// <param name="x">The x coordinate to transform.</param>
        /// <param name="y">The x coordinate to transform.</param>
        /// <param name="toGW">Transfer from View to GraphicsWindow ("True") or from GraphicsWindow to View ("False").</param>
        /// <returns>A 2D array of transformed coordinates indexed by 1 and 2.</returns>
        public static Primitive RepositionPoint(Primitive x, Primitive y, Primitive toGW)
        {
            Type GraphicsWindowType = typeof(GraphicsWindow);
            Canvas _mainCanvas;
            Primitive result = "";

            try
            {
                _mainCanvas = (Canvas)GraphicsWindowType.GetField("_mainCanvas", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                InvokeHelper ret = new InvokeHelper(delegate
                {
                    try
                    {
                        Grid grid = (Grid)_mainCanvas.Parent;
                        if (toGW)
                        {
                            System.Windows.Point pointView = new System.Windows.Point(x, y);
                            //System.Windows.Point pointGW = grid.PointFromScreen(_mainCanvas.PointToScreen(pointView));
                            GeneralTransform transform = _mainCanvas.TransformToVisual(grid);
                            System.Windows.Point pointGW = transform.Transform(pointView);
                            result[1] = pointGW.X;
                            result[2] = pointGW.Y;
                        }
                        else
                        {
                            System.Windows.Point pointGW = new System.Windows.Point(x, y);
                            //System.Windows.Point pointView = _mainCanvas.PointFromScreen(grid.PointToScreen(pointGW));
                            GeneralTransform transform = grid.TransformToVisual(_mainCanvas);
                            System.Windows.Point pointView = transform.Transform(pointGW);
                            result[1] = pointView.X;
                            result[2] = pointView.Y;
                        }
                    }
                    catch (Exception ex)
                    {
                        Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                    }
                });
                FastThread.Invoke(ret);
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
            return result;
        }
Example #54
0
 /// <summary>
 /// Register a shape to record mouse events: MouseDown, MouseUp, MouseEnter, MouseLeave, GotFocus and LostFocus.
 /// </summary>
 /// <param name="shapeName">The shape or control to add.</param>
 public static void SetShapeEvent(Primitive shapeName)
 {
     try
     {
         if (_objectsMap.TryGetValue((string)shapeName, out obj))
         {
             InvokeHelper ret = new InvokeHelper(delegate
             {
                 try
                 {
                     ((FrameworkElement)obj).Name = shapeName;
                     obj.MouseDown += new MouseButtonEventHandler(_ShapeEventsMouseDown);
                     obj.MouseUp += new MouseButtonEventHandler(_ShapeEventsMouseUp);
                     obj.MouseEnter += new MouseEventHandler(_ShapeEventsMouseEnter);
                     obj.MouseLeave += new MouseEventHandler(_ShapeEventsMouseLeave);
                     obj.GotFocus += new RoutedEventHandler(_ShapeEventsGotFocus);
                     obj.LostFocus += new RoutedEventHandler(_ShapeEventsLostFocus);
                 }
                 catch (Exception ex)
                 {
                     Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                 }
             });
             FastThread.Invoke(ret);
         }
         else
         {
             Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }
Example #55
0
        /// <summary>
        /// Set the background as a gradient of colours.
        /// </summary>
        /// <param name="brush">
        /// A previously created gradient or image brush (LDShapes.BrushGradient LDShapes.BrushImage).
        /// </param>
        /// <returns>
        /// None.
        /// </returns>
        public static void BackgroundBrush(Primitive brush)
        {
            Type GraphicsWindowType = typeof(GraphicsWindow);
            Window _window;

            try
            {
                _window = (Window)GraphicsWindowType.GetField("_window", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                InvokeHelper ret = new InvokeHelper(delegate
                {
                    try
                    {
                        foreach (GradientBrush i in LDShapes.brushes)
                        {
                            if (i.name == brush)
                            {
                                _window.Background = i.getBrush();
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                    }
                });
                FastThread.Invoke(ret);
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #56
0
 /// <summary>
 /// Reset the size of a shape as if it was created with the new size.
 /// The position (top left point) is unchanged.
 /// </summary>
 /// <param name="shapeName">
 /// The shape or control name.
 /// </param>
 /// <param name="width">
 /// The shape width.
 /// </param>
 /// <param name="height">
 /// The shape height.
 /// </param>
 /// <returns>
 /// None.
 /// </returns>
 public static void SetSize(Primitive shapeName, Primitive width, Primitive height)
 {
     try
     {
         if (_objectsMap.TryGetValue((string)shapeName, out obj))
         {
             InvokeHelper ret = new InvokeHelper(delegate
             {
                 try
                 {
                     FrameworkElement frameworkElement = obj as FrameworkElement;
                     frameworkElement.Width = width;
                     frameworkElement.Height = height;
                 }
                 catch (Exception ex)
                 {
                     Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                 }
             });
             FastThread.Invoke(ret);
         }
         else
         {
             Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }
Example #57
0
        private static string TakeSnapshot(string fileName)
        {
            string imageName = "";
            if (connected && null != dImg)
            {
                try
                {
                    if (null == fileName)
                    {
                        try
                        {
                            Type ShapesType = typeof(Shapes);
                            Type ImageListType = typeof(Microsoft.SmallBasic.Library.ImageList);
                            Dictionary<string, BitmapSource> _savedImages;

                            imageName = method3.Invoke(null, new object[] { "ImageList" }).ToString();
                            _savedImages = (Dictionary<string, BitmapSource>)ImageListType.GetField("_savedImages", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);

                            InvokeHelper ret = new InvokeHelper(delegate
                            {
                                try
                                {
                                    MemoryStream ms = new MemoryStream();
                                    dImg.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                                    BitmapImage bImg = new BitmapImage();
                                    bImg.BeginInit();
                                    bImg.StreamSource = ms;
                                    bImg.EndInit();
                                    _savedImages[imageName] = bImg;
                                }
                                catch (Exception ex)
                                {
                                    Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                                }
                            });
                            FastThread.Invoke(ret);
                        }
                        catch (Exception ex)
                        {
                            Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                        }
                    }
                    else if (fileName.Length == 0)
                    {
                        System.Drawing.Image image = (System.Drawing.Image)dImg.Clone();
                        SaveFileDialog dlg = new SaveFileDialog();
                        dlg.Filter = "JPG Images|*.jpg";
                        dlg.OverwritePrompt = true;
                        dlg.ValidateNames = true;
                        dlg.DefaultExt = "jpg";
                        if (dlg.ShowDialog(Utilities.ForegroundHandle()) == DialogResult.OK)
                        {
                            image.Save(dlg.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                    }
                    else
                    {
                        dImg.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }
                catch (Exception ex)
                {
                    Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                }
            }
            return imageName;
        }
Example #58
0
        /// <summary>
        /// Set the turtle to an image.
        /// </summary>
        /// <param name="imageName">
        /// The image to load for the turtle.
        /// Value returned from ImageList.LoadImage or local or network image file.
        /// </param>
        /// <param name="size">
        /// The size to scale the turtle to (default turtle is 16).
        /// </param>
        public static void SetTurtleImage(Primitive imageName, Primitive size)
        {
            Type GraphicsWindowType = typeof(GraphicsWindow);
            Type ImageListType = typeof(ImageList);
            Type TurtleType = typeof(Turtle);
            Dictionary<string, BitmapSource> _savedImages;
            BitmapSource img;
            RotateTransform _rotateTransform;

            try
            {
                TurtleType.GetMethod("VerifyAccess", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).Invoke(null, new object[] { });
                _savedImages = (Dictionary<string, BitmapSource>)ImageListType.GetField("_savedImages", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                if (!_savedImages.TryGetValue((string)imageName, out img))
                {
                    imageName = ImageList.LoadImage(imageName);
                    if (!_savedImages.TryGetValue((string)imageName, out img))
                    {
                        return;
                    }
                }
                _rotateTransform = (RotateTransform)TurtleType.GetField("_rotateTransform", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null);
                if (_objectsMap.TryGetValue("_turtle", out obj) && null != _rotateTransform)
                {
                    InvokeHelper ret = new InvokeHelper(delegate
                    {
                        try
                        {
                            if (obj.GetType() == typeof(Image))
                            {
                                Image shape = ((Image)obj);
                                shape.Source = img;
                                shape.Stretch = Stretch.Fill;
                                shape.Width = size;
                                shape.Height = size;
                                shape.Margin = new Thickness(-size / 2, -size / 2, 0.0, 0.0);
                                _rotateTransform.CenterX = size / 2;
                                _rotateTransform.CenterY = size / 2;
                            }
                        }
                        catch (Exception ex)
                        {
                            Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                        }
                    });
                    FastThread.Invoke(ret);
                }
                else
                {
                    Utilities.OnShapeError(Utilities.GetCurrentMethod(), "_turtle");
                }
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
            }
        }
Example #59
0
 /// <summary>
 /// Moves a triangle or polygon top-left position.
 /// This method also works for lines (Shapes.AddLine).
 /// </summary>
 /// <param name="shapeName">
 /// The shape name (a triangle, polygon or line shape).
 /// </param>
 /// <param name="x">
 /// The X (left) coordinate for the triangle, polygon or line.
 /// </param>
 /// <param name="y">
 /// The Y (top) coordinate for the triangle, polygon or line.
 /// </param>
 /// <returns>
 /// None.
 /// </returns>
 public static void Move(Primitive shapeName, Primitive x, Primitive y)
 {
     try
     {
         if (_objectsMap.TryGetValue((string)shapeName, out obj))
         {
             InvokeHelper ret = new InvokeHelper(delegate
             {
                 try
                 {
                     if (obj.GetType() == typeof(Polygon))
                     {
                         Polygon shape = (Polygon)obj;
                         int numPoint = shape.Points.Count;
                         double left = double.MaxValue;
                         double top = double.MaxValue;
                         for (int i = 0; i < numPoint; i++)
                         {
                             left = System.Math.Min(shape.Points[i].X, left);
                             top = System.Math.Min(shape.Points[i].Y, top);
                         }
                         PointCollection pointCollection = new PointCollection();
                         for (int i = 0; i < numPoint; i++)
                         {
                             pointCollection.Add(new Point(shape.Points[i].X + x - left, shape.Points[i].Y + y - top));
                         }
                         shape.Points = pointCollection;
                     }
                     else if (obj.GetType() == typeof(Line))
                     {
                         Line shape = (Line)obj;
                         double left = System.Math.Min(shape.X1, shape.X2);
                         double top = System.Math.Min(shape.Y1, shape.Y2);
                         shape.X1 += x - left;
                         shape.X2 += x - left;
                         shape.Y1 += y - top;
                         shape.Y2 += y - top;
                     }
                     else
                     {
                         Shapes.Move(shapeName, x, y);
                     }
                 }
                 catch (Exception ex)
                 {
                     Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                 }
             });
             FastThread.Invoke(ret);
         }
         else
         {
             Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }
Example #60
0
 /// <summary>
 /// Set shape Font.
 /// </summary>
 /// <param name="shapeName">
 /// The shape or control name.
 /// </param>
 /// <param name="family">The new font family name
 /// See LDUtilities.FontList() for available font families.</param>
 /// <param name="size">The new font size.</param>
 /// <param name="bold">The new font bold state ("True" or "False").</param>
 /// <param name="italic">The new font italic state ("True" or "False").</param>
 /// <returns>
 /// None.
 /// </returns>
 public static void Font(Primitive shapeName, Primitive family, Primitive size, Primitive bold, Primitive italic)
 {
     try
     {
         if (_objectsMap.TryGetValue((string)shapeName, out obj))
         {
             InvokeHelper ret = new InvokeHelper(delegate
             {
                 try
                 {
                     if (obj.GetType() == typeof(Button))
                     {
                         Button shape = (Button)obj;
                         shape.FontFamily = new FontFamily(family);
                         shape.FontSize = size;
                         shape.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal;
                         shape.FontStyle = italic ? FontStyles.Italic : FontStyles.Normal;
                     }
                     else if (obj.GetType() == typeof(TextBlock))
                     {
                         TextBlock shape = (TextBlock)obj;
                         shape.FontFamily = new FontFamily(family);
                         shape.FontSize = size;
                         shape.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal;
                         shape.FontStyle = italic ? FontStyles.Italic : FontStyles.Normal;
                     }
                     else if (obj.GetType() == typeof(TextBox))
                     {
                         TextBox shape = (TextBox)obj;
                         shape.FontFamily = new FontFamily(family);
                         shape.FontSize = size;
                         shape.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal;
                         shape.FontStyle = italic ? FontStyles.Italic : FontStyles.Normal;
                     }
                     else if (obj.GetType() == typeof(PasswordBox))
                     {
                         PasswordBox shape = (PasswordBox)obj;
                         shape.FontFamily = new FontFamily(family);
                         shape.FontSize = size;
                         shape.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal;
                         shape.FontStyle = italic ? FontStyles.Italic : FontStyles.Normal;
                     }
                     else if (obj.GetType() == typeof(CheckBox))
                     {
                         CheckBox shape = (CheckBox)obj;
                         shape.FontFamily = new FontFamily(family);
                         shape.FontSize = size;
                         shape.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal;
                         shape.FontStyle = italic ? FontStyles.Italic : FontStyles.Normal;
                     }
                     else if (obj.GetType() == typeof(ComboBox))
                     {
                         ComboBox shape = (ComboBox)obj;
                         shape.FontFamily = new FontFamily(family);
                         shape.FontSize = size;
                         shape.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal;
                         shape.FontStyle = italic ? FontStyles.Italic : FontStyles.Normal;
                     }
                     else if (obj.GetType() == typeof(RadioButton))
                     {
                         RadioButton shape = (RadioButton)obj;
                         shape.FontFamily = new FontFamily(family);
                         shape.FontSize = size;
                         shape.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal;
                         shape.FontStyle = italic ? FontStyles.Italic : FontStyles.Normal;
                     }
                     else if (obj.GetType() == typeof(RichTextBox))
                     {
                         RichTextBox shape = (RichTextBox)obj;
                         shape.FontFamily = new FontFamily(family);
                         shape.FontSize = size;
                         shape.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal;
                         shape.FontStyle = italic ? FontStyles.Italic : FontStyles.Normal;
                     }
                     else if (obj.GetType() == typeof(TreeView))
                     {
                         TreeView shape = (TreeView)obj;
                         shape.FontFamily = new FontFamily(family);
                         shape.FontSize = size;
                         shape.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal;
                         shape.FontStyle = italic ? FontStyles.Italic : FontStyles.Normal;
                     }
                     else if (obj.GetType() == typeof(DocumentViewer))
                     {
                         DocumentViewer shape = (DocumentViewer)obj;
                         shape.FontFamily = new FontFamily(family);
                         shape.FontSize = size;
                         shape.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal;
                         shape.FontStyle = italic ? FontStyles.Italic : FontStyles.Normal;
                     }
                     else if (obj.GetType() == typeof(ListBox))
                     {
                         ListBox shape = (ListBox)obj;
                         shape.FontFamily = new FontFamily(family);
                         shape.FontSize = size;
                         shape.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal;
                         shape.FontStyle = italic ? FontStyles.Italic : FontStyles.Normal;
                     }
                     else if (obj.GetType() == typeof(ListView))
                     {
                         ListView shape = (ListView)obj;
                         shape.FontFamily = new FontFamily(family);
                         shape.FontSize = size;
                         shape.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal;
                         shape.FontStyle = italic ? FontStyles.Italic : FontStyles.Normal;
                     }
                     else if (obj.GetType() == typeof(WindowsFormsHost))
                     {
                         WindowsFormsHost shape = (WindowsFormsHost)obj;
                         shape.FontFamily = new FontFamily(family);
                         shape.FontSize = size;
                         shape.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal;
                         shape.FontStyle = italic ? FontStyles.Italic : FontStyles.Normal;
                         if (shape.Child.GetType() == typeof(System.Windows.Forms.DataGridView))
                         {
                             System.Windows.Forms.DataGridView dataView = (System.Windows.Forms.DataGridView)shape.Child;
                         }
                     }
                     else if (obj.GetType() == typeof(Menu))
                     {
                         Menu shape = (Menu)obj;
                         shape.FontFamily = new FontFamily(family);
                         shape.FontSize = size;
                         shape.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal;
                         shape.FontStyle = italic ? FontStyles.Italic : FontStyles.Normal;
                     }
                 }
                 catch (Exception ex)
                 {
                     Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                 }
             });
             FastThread.Invoke(ret);
         }
         else
         {
             Utilities.OnShapeError(Utilities.GetCurrentMethod(), shapeName);
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }