Esempio n. 1
0
        internal object ToDictionary(object input)
        {
            var dictionary = new System.Dynamic.ExpandoObject() as IDictionary <string, object>;

            switch (input)
            {
            case DatabaseObject databaseObject:
                foreach (var property in databaseObject.Properties)
                {
                    dictionary.Add(property.Key, ToDictionary(property.Value));
                }
                break;

            case BigDBObjectValue objectValue:
                switch (objectValue.Type)
                {
                case ObjectType.DatabaseArray:
                case ObjectType.DatabaseObject:
                    foreach (var property in (dynamic)objectValue.Value)
                    {
                        dictionary.Add(property.Key.ToString(), ToDictionary(property.Value));
                    }
                    break;

                default: return(ToDictionary(objectValue.Value));
                }
                break;

            default: return(input);
            }

            return(dictionary);
        }
Esempio n. 2
0
        private string GenerateMarkup(Dictionary <string, string> Attributes)
        {
            try
            {
                PortalSettings ps = PortalController.Instance.GetCurrentSettings() as PortalSettings;

                if (ps != null && ps.ActiveTab != null && ps.ActiveTab.BreadCrumbs == null)
                {
                    ps.ActiveTab.BreadCrumbs = new System.Collections.ArrayList();
                }

                Dictionary <string, string> BaseAttributes = Core.Managers.BlockManager.GetGlobalConfigs(ps, "login");
                if (Attributes["data-block-global"] == "true")
                {
                    Attributes = BaseAttributes;
                }
                else
                {
                    //Loop on base attributes and add missing attribute
                    foreach (KeyValuePair <string, string> attr in BaseAttributes)
                    {
                        if (!Attributes.ContainsKey(attr.Key))
                        {
                            Attributes.Add(attr.Key, attr.Value);
                        }
                    }
                }

                Entities.Login login = new Entities.Login
                {
                    ButtonAlign          = Attributes["data-block-buttonalign"],
                    ShowLabel            = Convert.ToBoolean(Attributes["data-block-showlabel"]),
                    ShowResetPassword    = Convert.ToBoolean(Attributes["data-block-showresetpassword"]),
                    ShowRememberPassword = Convert.ToBoolean(Attributes["data-block-showrememberpassword"]),
                    ResetPassword        = Convert.ToBoolean(Attributes["data-block-resetpassword"]),
                    ShowRegister         = Convert.ToBoolean(Attributes["data-block-showregister"])
                };

                login.RegisterUrl = Globals.RegisterURL(HttpUtility.UrlEncode(ServiceProvider.NavigationManager.NavigateURL()), Null.NullString);
                IDictionary <string, object> Objects = new System.Dynamic.ExpandoObject() as IDictionary <string, object>;
                Objects.Add("Login", login);
                Objects.Add("UseEmailAsUserName", (PortalController.Instance.GetCurrentSettings() as PortalSettings).Registration.UseEmailAsUserName);
                string Template = RazorEngineManager.RenderTemplate(ExtensionInfo.GUID, BlockPath, Attributes["data-block-template"], Objects);
                Template = new DNNLocalizationEngine(null, ResouceFilePath, false).Parse(Template);
                return(Template);
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                return(ex.Message);
            }
        }
        private string GenerateMarkup(Dictionary <string, string> Attributes)
        {
            try
            {
                PortalSettings ps = PortalController.Instance.GetCurrentSettings() as PortalSettings;

                if (ps != null && ps.ActiveTab != null && ps.ActiveTab.BreadCrumbs == null)
                {
                    ps.ActiveTab.BreadCrumbs = new System.Collections.ArrayList();
                }

                Dictionary <string, string> BaseAttributes = Core.Managers.BlockManager.GetGlobalConfigs(ps, "register");
                if (Attributes["data-block-global"] == "true")
                {
                    Attributes = BaseAttributes;
                }
                else
                {
                    //Loop on base attributes and add missing attribute
                    foreach (KeyValuePair <string, string> attr in BaseAttributes)
                    {
                        if (!Attributes.ContainsKey(attr.Key))
                        {
                            Attributes.Add(attr.Key, attr.Value);
                        }
                    }
                }
                DotNetNuke.Security.RegistrationSettings RegistrationSettings = (PortalController.Instance.GetCurrentSettings() as PortalSettings).Registration;
                int UserRegistration = (PortalController.Instance.GetCurrentSettings() as PortalSettings).UserRegistration;
                IDictionary <string, object> dynObjects = new System.Dynamic.ExpandoObject() as IDictionary <string, object>;
                Entities.Register            register   = new Entities.Register
                {
                    ButtonAlign  = Attributes["data-block-buttonalign"],
                    ShowLabel    = Convert.ToBoolean(Attributes["data-block-showlabel"]),
                    TermsPrivacy = Convert.ToBoolean(Attributes["data-block-termsprivacy"])
                };
                dynObjects.Add("Register", register);
                dynObjects.Add("RegistrationSettings", RegistrationSettings);
                dynObjects.Add("UserRegistration", UserRegistration);

                string Template = RazorEngineManager.RenderTemplate(ExtensionInfo.GUID, BlockPath, Attributes["data-block-template"], dynObjects);
                Template = new DNNLocalizationEngine(null, ResouceFilePath, false).Parse(Template);
                return(Template);
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                return(ex.Message);
            }
        }
Esempio n. 4
0
        public static object ToExpando(object value, IEnumerable <MemberInfo> include)
        {
            IDictionary <string, object> expando = new System.Dynamic.ExpandoObject();

            //foreach (var member in include.Where(IsInstance))
            foreach (var member in include)
            {
                try
                {
                    if (member is FieldInfo)
                    {
                        expando[member.Name] = ((FieldInfo)member).GetValue(value);
                    }
                    else if (member is PropertyInfo && ((PropertyInfo)member).GetIndexParameters().Length == 0)
                    {
                        expando[member.Name] = ((PropertyInfo)member).GetValue(value);
                    }
                    else if (member is MethodInfo && ((MethodInfo)member).GetParameters().Length == 0)
                    {
                        expando[member.Name] = ((MethodInfo)member).Invoke(value, null);
                    }
                    // Ignore other kinds of member
                }
                catch (Exception ex)   // If it faults, record the error in the expando.
                {
                    expando.Add(member.Name, ex.GetBaseException());
                }
            }

            return(expando);
        }
Esempio n. 5
0
        public static List <Dictionary <string, object> > ReaderToList(this DbDataReader reader, string includeColumns = "")
        {
            var expandolist = new List <Dictionary <string, object> >();
            var listColumns = new List <string>();

            // convert columns to list base on comma
            if (!string.IsNullOrEmpty(includeColumns))
            {
                listColumns = includeColumns.Split(',').ToList();
            }

            while (reader.Read())
            {
                IDictionary <string, object> expando = new System.Dynamic.ExpandoObject();

                for (int i = 0; i < reader.FieldCount; i++)
                {
                    string columnName = reader.GetName(i);

                    if (listColumns.Count() == 0 || listColumns.Contains(columnName))
                    {
                        expando.Add(Convert.ToString(columnName), reader.GetValue(i));
                    }
                }

                expandolist.Add(new Dictionary <string, object>(expando));
            }

            return(expandolist);
        }
Esempio n. 6
0
        public static string CreatePosXML(Request request, string content)
        {
            try
            {
                dynamic model = new System.Dynamic.ExpandoObject();

                IDictionary <string, object> property = new System.Dynamic.ExpandoObject();
                foreach (var item in request.Accounts)
                {
                    property.Add(item.Key, item.Value);
                }

                model.Pay     = request.Pos;
                model.Account = (System.Dynamic.ExpandoObject)property;

                if (request.Is3D)
                {
                    dynamic extra3d = new System.Dynamic.ExpandoObject();
                    extra3d.Url        = request.Url;
                    extra3d.SuccessUrl = request.SuccessUrl;
                    extra3d.ErrorUrl   = request.ErrorUrl;
                    model.Extra        = extra3d;
                }

                string renderResult = RazorEngine.Razor.Parse(content, model);

                return(renderResult);
            }
            catch (Exception EX)
            {
                throw EX;
            }
        }
Esempio n. 7
0
        public static void Demo()
        {
            Console.WriteLine("# Rules of Dynamics");

            dynamic text = "My text";
            var     my   = text.Substring(2);
            //var my = text.SUBSTR(2);

            // there is an implict conversion between dynamic and
            // any non-pointer type
            string str = text;

            // operations containing a dynamic result in a dynamic
            // in most cases and are bound at EXECUTION TIME
            var alsoDynamic = text + " is here";

            // even if it contains a dynamic parameter,
            // constructors are bound at compile time
            var test = new TestObj(text);


            // in a static context, expando object is a dictionary
            IDictionary <string, object> expando = new System.Dynamic.ExpandoObject();

            expando.Add("testProperty", "myValue");
            Console.WriteLine(expando["testProperty"]);

            // in a dynamic context, expando object is dynamic
            dynamic dynamicExpando = expando;

            Console.WriteLine(dynamicExpando.testProperty);

            // can add keys dynamically even
            dynamicExpando.secondProperty = "thisToo";
            Console.WriteLine(expando["secondProperty"]);


            // anonymous methods can only be dynamic if casted
            // dynamic sqr = x => x * x;
            dynamic sqr = (Func <dynamic, dynamic>)(x => x * x);

            // same concept applies to LINQ methods
            // extension methods also cannot be called in a dynamic context
            dynamic list = new List <int> {
                2, 4, 6
            };

            // dynamic notHere = list.Select(x => x == "here");

            // This will be invalid since list is dynamic
            // dynamic isHere = list.Find((x => x == 6);


            // expression trees cannot be used with dynamic
            // dynamic there = list.AsQueryable().First();

            Console.WriteLine("=====");
        }
Esempio n. 8
0
        public static dynamic ToDynamic <T>(this Dictionary <string, T> dict)
        {
            IDictionary <string, object> eo = new System.Dynamic.ExpandoObject() as IDictionary <string, object>;

            foreach (KeyValuePair <string, T> kvp in dict)
            {
                eo.Add(new KeyValuePair <string, object>(kvp.Key, kvp.Value));
            }
            return(eo);
        }
Esempio n. 9
0
 public static System.Dynamic.ExpandoObject ToExpando(this object anonymousObject)
 {
     System.Collections.Generic.IDictionary <string, object> anonymousDictionary = Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelper.AnonymousObjectToHtmlAttributes(anonymousObject);
     System.Collections.Generic.IDictionary <string, object> expando             = new System.Dynamic.ExpandoObject();
     foreach (var item in anonymousDictionary)
     {
         expando.Add(item);
     }
     return((System.Dynamic.ExpandoObject)expando);
 }
Esempio n. 10
0
 public static System.Dynamic.ExpandoObject ToExpando(this object anonymousObject)
 {
     System.Collections.Generic.IDictionary <string, object> anonymousDictionary = new System.Web.Routing.RouteValueDictionary(anonymousObject);
     System.Collections.Generic.IDictionary <string, object> expando             = new System.Dynamic.ExpandoObject();
     foreach (var item in anonymousDictionary)
     {
         expando.Add(item);
     }
     return((System.Dynamic.ExpandoObject)expando);
 }
Esempio n. 11
0
    private static IDictionary <string, object> ExpandoGroupBy <T>(T x, string[] columnsToGroup) where T : class
    {
        var groupByColumns = new System.Dynamic.ExpandoObject() as IDictionary <string, object>;

        groupByColumns.Clear();
        foreach (string column in columnsToGroup)
        {
            groupByColumns.Add(column, typeof(T).GetProperty(column).GetValue(x, null));
        }
        return(groupByColumns);
    }
Esempio n. 12
0
        private static dynamic CreateExpando(XElement xElement)
        {
            var result = new System.Dynamic.ExpandoObject() as IDictionary <string, object>;

            if (xElement.Elements().Any(x => x.HasElements))
            {
                var list = new List <System.Dynamic.ExpandoObject>();
                result.Add(xElement.Name.ToString(), list);
                foreach (var childElement in xElement.Elements())
                {
                    list.Add(CreateExpando(childElement));
                }
            }
            else
            {
                foreach (var leafElement in xElement.Elements())
                {
                    result.Add(leafElement.Name.ToString(), leafElement.Value);
                }
            }
            return(result);
        }
Esempio n. 13
0
        public static dynamic MakeExpandoFromMethod(this Type type, string methodName, bool ignoreCase = true)
        {
            IDictionary <string, Object> obj =
                new System.Dynamic.ExpandoObject() as IDictionary <string, Object>;

            MethodInfo method = type.GetStaticMethod(methodName, ignoreCase);
            IEnumerable <ParameterInfo> props = method.GetParameters().OrderBy(p => p.Position);

            foreach (var prop in props)
            {
                obj.Add(prop.Name, prop.HasDefaultValue ? prop.DefaultValue : prop.ParameterType.GetDefaultValue());
            }

            return(obj);
        }
Esempio n. 14
0
 private string GenerateMarkup(Dictionary <string, string> Attributes)
 {
     try
     {
         Entities.SearchInput         searchInput = new Entities.SearchInput();
         IDictionary <string, object> Objects     = new System.Dynamic.ExpandoObject() as IDictionary <string, object>;
         Objects.Add("SearchInput", searchInput);
         string Template = RazorEngineManager.RenderTemplate(ExtensionInfo.GUID, BlockPath, Attributes["data-block-template"], Objects);
         Template = new DNNLocalizationEngine(null, ResouceFilePath, false).Parse(Template);
         return(Template);
     }
     catch (Exception ex)
     {
         DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
         return(ex.Message);
     }
 }
Esempio n. 15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="_object"></param>
        /// <returns></returns>
        public IDictionary <string, Object> FormatJson(dynamic _object)
        {
            var postObject = new System.Dynamic.ExpandoObject() as IDictionary <string, Object>;

            foreach (var descriptor in TypeDescriptor.GetProperties(_object))
            {
                foreach (var attribute in descriptor.Attributes)
                {
                    if (attribute is JsonPropertyAttribute)
                    {
                        var jsonProperty = (JsonPropertyAttribute)attribute;
                        postObject.Add(jsonProperty.PropertyName, _object.GetType().GetProperty(descriptor.DisplayName).GetValue(_object));
                        break;
                    }
                }
            }
            return(postObject);
        }
Esempio n. 16
0
        /// <summary>
        /// 获取查询结果字段,绑定成对象
        /// </summary>
        /// <param name="dataReader"></param>
        /// <returns></returns>
        public static dynamic GetDataReader(this MySqlDataReader dataReader)
        {
            //dynamic dymodel = new System.Dynamic.ExpandoObject();
            List <string> fider = new List <string>();

            for (int i = 0; i < dataReader.FieldCount; i++)
            {
                fider.Add(dataReader.GetName(i));
            }

            ICollection <KeyValuePair <string, object> > fde = new System.Dynamic.ExpandoObject();//在运行时动态添加和删除其成员的对象。

            foreach (var item in fider)
            {
                var nm = new KeyValuePair <string, object>(item, dataReader[item]);
                if (!fde.Contains(nm))
                {
                    fde.Add(new KeyValuePair <string, object>(item, dataReader[item]));
                }
            }
            dynamic dymodel = fde;

            return(dymodel);
        }
Esempio n. 17
0
        private async Task ConfigMappersContabilidad(MapperConfig mConfig)
        {
            //ObservableApuntesList
            //mConfig
            //    .AddConstructor<ObservableApuntesList>(x =>
            //    {
            //        var store = new MapperStore();
            //        DapperMapper<Apunte> mapper = (DapperMapper<Apunte>)store.GetMapper(typeof(Apunte));
            //        List<Apunte> lista = mapper.Map(x, "Id", false); //Obtiene lista de apuntes con sobrecarga de Map()

            //        return new ObservableApuntesList(lista.First().Asiento, lista); //crea objeto a partir de esa lista
            //    })
            //    .MapOnlyConstructor<ObservableApuntesList>()
            //    .EndConfig<ObservableApuntesList>();

            //Apunte
            mConfig
            //.AddNestedProperty<Apunte>(true, "_Asiento")
            .AddMemberCreator <Apunte>("_Asiento", x =>
            {
                Asiento asiento = AsientoRepo.AsientoMapperGetFromDictionary((int)x.Asiento);
                return(asiento);
            })
            .AddMemberCreator <Apunte>("_DebeHaber", x => (DebitCredit)x.DebeHaber)
            .AddIgnoreProperty <Apunte, decimal>(x => x.ImporteAlDebe)
            .AddIgnoreProperty <Apunte, decimal>(x => x.ImporteAlHaber)
            .AddIgnoreProperty <Apunte, bool>(x => x.IsBeingModifiedFromView)
            .AddIgnoreProperty <Apunte, bool>(x => x.HasBeenModifiedFromView)
            .AddIgnoreProperty <Apunte, List <string> >(x => x.DirtyMembers)
            .AddPrefixes <Apunte>(new string[] { "apu" })
            .EndConfig <Apunte>();
            mConfig
            .AddConstructor <ApunteDLO>(x => new ApunteDLO(x.Id, x.IdOwnerComunidad, x.OrdenEnAsiento, x.Asiento, x.Concepto, x.DebeHaber,
                                                           x.Importe, x.IdCuenta, x.Punteo, x.Factura))
            .MapOnlyConstructor <ApunteDLO>()
            .EndConfig <ApunteDLO>();
            //Asiento
            mConfig
            .AddConstructor <Asiento>(x =>
            {
                var store = new MapperStore();
                DapperMapper <Apunte> mapper = (DapperMapper <Apunte>)store.GetMapper(typeof(Apunte));
                Apunte[] apuntes             = mapper.Map(x, "Id", false); //Obtiene lista de apuntes con sobrecarga de Map()

                return(new Asiento(x.Id, x.IdOwnerComunidad, x.IdOwnerEjercicio, x.Codigo, this.ACData, x.FechaValor, apuntes));
            })
            //.AddNestedProperty<Asiento, ObservableApuntesList>(false, x => x.Apuntes)
            .AddIgnoreProperty <Asiento>("Apuntes")
            .AddIgnoreProperty <Asiento>("Item")
            .AddPrefixes <Asiento>(new string[] { "asi" })
            .EndConfig <Asiento>();
            //Gasto-Pago-GastosPagosBase
            mConfig
            .AddPrefixes <GastosPagosBase.sImporteCuenta>(new string[] { "acreedora_", "deudora_" })
            .EndConfig <GastosPagosBase.sImporteCuenta>();
            mConfig
            .AddConstructor <GastosPagosBase>(x => new GastosPagosBase(x.Id, x.IdOwnerComunidad, x.IdProveedor, x.IdOwnerFactura, x.Fecha))
            .AddMemberCreator <GastosPagosBase>("_CuentasAcreedoras", x =>
            {
                MapperStore store = new MapperStore();
                DapperMapper <GastosPagosBase.sImporteCuenta> mapper =
                    (DapperMapper <GastosPagosBase.sImporteCuenta>)store.GetMapper(typeof(GastosPagosBase.sImporteCuenta));
                IEnumerable <dynamic> distinctAcreedX = mapper.GetDistinctDapperResult(x, false);
                distinctAcreedX = distinctAcreedX.Select(dyn =>
                {
                    IDictionary <string, object> dict = dyn as IDictionary <string, object>;
                    var result = new System.Dynamic.ExpandoObject() as IDictionary <string, object>;
                    foreach (KeyValuePair <string, object> kvp in dict)
                    {
                        if (kvp.Key.Contains("acreedora_"))
                        {
                            result.Add(kvp.Key, kvp.Value);
                        }
                    }

                    return(result);
                });

                return(mapper.Map <List <GastosPagosBase.sImporteCuenta> >(distinctAcreedX, "Id", false));
            })
            .AddMemberCreator <GastosPagosBase>("_CuentasDeudoras", x =>
            {
                MapperStore store = new MapperStore();
                DapperMapper <GastosPagosBase.sImporteCuenta> mapper =
                    (DapperMapper <GastosPagosBase.sImporteCuenta>)store.GetMapper(typeof(GastosPagosBase.sImporteCuenta));
                IEnumerable <dynamic> distinctDeudX = mapper.GetDistinctDapperResult(x, false);
                distinctDeudX = distinctDeudX.Select(dyn =>
                {
                    IDictionary <string, object> dict = dyn as IDictionary <string, object>;
                    var result = new System.Dynamic.ExpandoObject() as IDictionary <string, object>;
                    foreach (KeyValuePair <string, object> kvp in dict)
                    {
                        if (kvp.Key.Contains("deudora_"))
                        {
                            result.Add(kvp.Key, kvp.Value);
                        }
                    }

                    return(result);
                });

                return(mapper.Map <List <GastosPagosBase.sImporteCuenta> >(distinctDeudX, "Id", false));
            })
            //.AddIgnoreProperty<GastosPagosBase>("_CuentasAcreedoras")
            //.AddIgnoreProperty<GastosPagosBase>("_CuentasDeudoras")
            //.AddIgnoreProperty<GastosPagosBase, System.Collections.ObjectModel.ReadOnlyCollection<GastosPagosBase.sImporteCuenta>>(
            //    x => x.CuentasAcreedoras)
            //.AddIgnoreProperty<GastosPagosBase, System.Collections.ObjectModel.ReadOnlyCollection<GastosPagosBase.sImporteCuenta>>(
            //    x => x.CuentasDeudoras)
            .EndConfig <GastosPagosBase>();
            mConfig
            .AddConstructor <Gasto>(x => new Gasto(x.Id, x.IdOwnerComunidad, x.IdProveedor, x.IdOwnerFactura, x.Fecha))
            .EndConfig <Gasto>();
            mConfig
            .AddConstructor <Pago>(x => new Pago(x.Id, x.IdOwnerComunidad, x.IdProveedor, x.IdOwnerFactura, x.Fecha))
            .EndConfig <Pago>();
            //GastosPagosList-ReadOnly
            mConfig
            .AddConstructor <GastosPagosList <Gasto> >(x =>
            {
                MapperStore store           = new MapperStore();
                DapperMapper <Gasto> mapper = (DapperMapper <Gasto>)store.GetMapper(typeof(Gasto));
                List <Gasto> lista          = mapper.Map <List <Gasto> >(x, "Id", false);

                return(new GastosPagosList <Gasto>(lista));
            })
            .MapOnlyConstructor <GastosPagosList <Gasto> >()
            .EndConfig <GastosPagosList <Gasto> >();
            mConfig
            .AddConstructor <GastosPagosList <Pago> >(x =>
            {
                MapperStore store          = new MapperStore();
                DapperMapper <Pago> mapper = (DapperMapper <Pago>)store.GetMapper(typeof(Pago));
                List <Pago> lista          = mapper.Map <List <Pago> >(x, "Id", false);

                return(new GastosPagosList <Pago>(lista));
            })
            .MapOnlyConstructor <GastosPagosList <Pago> >()
            .EndConfig <GastosPagosList <Pago> >();
            mConfig
            .AddConstructor <ReadOnlyGastosPagosList <Gasto> >(x =>
            {
                MapperStore store           = new MapperStore();
                DapperMapper <Gasto> mapper = (DapperMapper <Gasto>)store.GetMapper(typeof(Gasto));
                List <Gasto> lista          = mapper.Map <List <Gasto> >(x, "Id", false);

                return(new ReadOnlyGastosPagosList <Gasto>(lista));
            })
            .MapOnlyConstructor <ReadOnlyGastosPagosList <Gasto> >()
            .EndConfig <ReadOnlyGastosPagosList <Gasto> >();
            mConfig
            .AddConstructor <ReadOnlyGastosPagosList <Pago> >(x =>
            {
                MapperStore store          = new MapperStore();
                DapperMapper <Pago> mapper = (DapperMapper <Pago>)store.GetMapper(typeof(Pago));
                List <Pago> lista          = mapper.Map <List <Pago> >(x, "Id", false);

                return(new ReadOnlyGastosPagosList <Pago>(lista));
            })
            .MapOnlyConstructor <ReadOnlyGastosPagosList <Pago> >()
            .EndConfig <ReadOnlyGastosPagosList <Pago> >();
            //Factura
            mConfig
            .AddNestedProperty <Factura>(false, "_GastosFra")
            .AddIgnoreProperty <Factura, ReadOnlyGastosPagosList <Gasto> >(x => x.GastosFra)
            .AddNestedProperty <Factura>(false, "_PagosFra")
            .AddIgnoreProperty <Factura, ReadOnlyGastosPagosList <Pago> >(x => x.PagosFra)
            .AddMemberCreator <Factura, int?>(x => x.IdOwnerProveedor, x => x.IdProveedor)
            .AddMemberCreator <Factura, TipoPagoFacturas>(x => x.TipoPago, x => (TipoPagoFacturas)x.TipoPago)
            .AddIgnoreProperty <Factura, decimal>(x => x.TotalImpuestos)
            .EndConfig <Factura>();
            mConfig
            .AddConstructor <FacturaDLO>(x => new FacturaDLO(x.Id, x.IdProveedor, x.IdOwnerComunidad, x.NFactura, x.Fecha, x.Concepto, x.Total,
                                                             x.Pendiente, (TipoPagoFacturas)x.TipoPago))
            .MapOnlyConstructor <FacturaDLO>()
            .EndConfig <FacturaDLO>();
            //CuentaMayor
            mConfig
            .AddConstructor <CuentaMayor>(x => new CuentaMayor(x.Codigo, x.Id, x.IdOwnerComunidad, x.IdOwnerEjercicio, x.Nombre))
            .MapOnlyConstructor <CuentaMayor>()
            .EndConfig <CuentaMayor>();
            mConfig
            .AddConstructor <CuentaMayorDLO>(x => new CuentaMayorDLO(int.Parse(x.Codigo), x.Id, x.IdOwnerComunidad, x.IdOwnerEjercicio, x.Nombre))
            .MapOnlyConstructor <CuentaMayorDLO>()
            .EndConfig <CuentaMayorDLO>();
            //Proveedor
            mConfig
            .AddConstructor <Proveedor>(x => new Proveedor(x.Id, x.IdPersona, x.NIF, x.Nombre, true))
            .AddNestedProperty <Proveedor>(false, "_CuentaContableGasto")
            .AddNestedProperty <Proveedor>(false, "_CuentaContablePago")
            .AddNestedProperty <Proveedor>(false, "_CuentaContableProveedor")
            .AddMemberCreator <Proveedor, TipoPagoFacturas>(x => x.DefaultTipoPagoFacturas, x => (TipoPagoFacturas)x.DefaultTipoPagoFacturas)
            .EndConfig <Proveedor>();
            mConfig
            .AddConstructor <ProveedorDLO>(x => new ProveedorDLO(x.Id, x.Nombre, x.NIF, string.Concat(x.TipoVia, " ",
                                                                                                      x.Direccion), x.CuentaBancaria, x.Telefono, x.Email, x.RazonSocial, x.CuentaContableGasto, x.CuentaContablePago,
                                                                 x.CuentaContableProveedor))
            .MapOnlyConstructor <ProveedorDLO>()
            .EndConfig <ProveedorDLO>();
            //Cobros-EntACta-iIngresoPropietario
            mConfig
            .AddInterfaceToObjectCondition <iIngresoPropietario>(x =>
            {
                var dict = x as IDictionary <string, object>;
                return(dict.ContainsKey("IdOwnerCuota"));
            },
                                                                 typeof(Cobro))
            .AddInterfaceToObjectCondition <iIngresoPropietario>(x =>
            {
                var dict = x as IDictionary <string, object>;
                return(dict.ContainsKey("IdOwnerFinca"));
            },
                                                                 typeof(EntACta))
            .EndConfig <iIngresoPropietario>();
            mConfig
            .AddConstructor <Cobro>(x => new Cobro(
                                        x.Id, x.IdOwnerRecibo, x.IdOwnerCuota, x.Importe, x.Fecha, x.IdOwnerPersona, x.Total, (SituacionReciboCobroEntaCta)x.Situacion))
            .AddPrefixes <Cobro>(new string[1] {
                "cobro"
            })
            .MapOnlyConstructor <Cobro>()
            .EndConfig <Cobro>();
            mConfig
            .AddConstructor <EntACta>(x => new EntACta(
                                          x.Id, x.IdOwnerRecibo, x.IdOwnerFinca, x.Importe, x.Fecha, x.IdOwnerPersona, (SituacionReciboCobroEntaCta)x.Situacion))
            .AddPrefixes <EntACtaDict>(new string[1] {
                "eacta"
            })
            .MapOnlyConstructor <Cobro>()
            .EndConfig <EntACta>();
            //Cobros/EntACta - List/Dict
            mConfig
            .AddConstructor <CobrosList>(x =>
            {
                MapperStore store           = new MapperStore();
                DapperMapper <Cobro> mapper = (DapperMapper <Cobro>)store.GetMapper(typeof(Cobro));
                List <Cobro> lista          = mapper.Map <List <Cobro> >(x, "Id", false);

                return(new CobrosList(lista));
            })
            .MapOnlyConstructor <CobrosList>()
            .EndConfig <EntACtaList>();
            mConfig
            .AddConstructor <CobrosDict>(x =>
            {
                MapperStore store           = new MapperStore();
                DapperMapper <Cobro> mapper = (DapperMapper <Cobro>)store.GetMapper(typeof(Cobro));
                IEnumerable <Cobro> lista   = mapper.Map <IEnumerable <Cobro> >(x);

                return(new CobrosDict(lista.ToDictionary(c => (int)c.Id, c => c)));
            })
            .MapOnlyConstructor <CobrosDict>()
            .EndConfig <CobrosDict>();
            mConfig
            .AddConstructor <EntACtaList>(x =>
            {
                MapperStore store             = new MapperStore();
                DapperMapper <EntACta> mapper = (DapperMapper <EntACta>)store.GetMapper(typeof(EntACta));
                List <EntACta> lista          = mapper.Map <List <EntACta> >(x, "Id", false);

                return(new EntACtaList(lista));
            })
            .MapOnlyConstructor <EntACtaList>()
            .EndConfig <EntACtaList>();
            mConfig
            .AddConstructor <EntACtaDict>(x =>
            {
                MapperStore store             = new MapperStore();
                DapperMapper <EntACta> mapper = (DapperMapper <EntACta>)store.GetMapper(typeof(EntACta));
                IEnumerable <EntACta> lista   = mapper.Map <IEnumerable <EntACta> >(x);

                return(new EntACtaDict(lista.ToDictionary(c => (int)c.Id, c => c)));
            })
            .MapOnlyConstructor <EntACtaDict>()
            .EndConfig <EntACtaDict>();
            //IngresoDevuelto
            mConfig
            .AddConstructor <IngresoDevuelto>(x =>
            {
                MapperStore store = new MapperStore();
                DapperMapper <iIngresoPropietario> mapper = (DapperMapper <iIngresoPropietario>)store.GetMapper(typeof(iIngresoPropietario));
                var ingreso = mapper.Map(x);
                return(new IngresoDevuelto(x.Id, x.IdOwnerDevolucion, x.Fecha, ingreso, x.Total, x.Importe, x.Gastos));
            })
            .MapOnlyConstructor <IngresoDevuelto>()
            .EndConfig <IngresoDevuelto>();
            //Devolucion-List
            mConfig
            .AddConstructor <Devolucion>(x =>
            {
                MapperStore store = new MapperStore();
                DapperMapper <IngresoDevuelto> mapper = (DapperMapper <IngresoDevuelto>)store.GetMapper(typeof(IngresoDevuelto));
                List <IngresoDevuelto> lista          = mapper.Map <List <IngresoDevuelto> >(x);

                return(new Devolucion(x.Id, x.IdOwnerComunidad, x.Fecha, lista));
            })
            .MapOnlyConstructor <Devolucion>()
            .EndConfig <Devolucion>();
            mConfig
            .AddConstructor <DevolucionesList>(x =>
            {
                MapperStore store = new MapperStore();
                DapperMapper <Devolucion> mapper = (DapperMapper <Devolucion>)store.GetMapper(typeof(Devolucion));
                IEnumerable <Devolucion> lista   = mapper.Map <IEnumerable <Devolucion> >(x);

                return(new DevolucionesList(lista.ToList()));
            })
            .MapOnlyConstructor <DevolucionesList>()
            .EndConfig <DevolucionesList>();
        }
Esempio n. 18
0
        protected async override void Execute(NativeActivityContext context)
        {
            string WorkflowInstanceId             = context.WorkflowInstanceId.ToString();
            string bookmarkname                   = null;
            bool   waitforcompleted               = WaitForCompleted.Get(context);
            IDictionary <string, object> _payload = new System.Dynamic.ExpandoObject();
            var vars = context.DataContext.GetProperties();

            foreach (dynamic v in vars)
            {
                var value = v.GetValue(context.DataContext);
                if (value != null)
                {
                    //_payload.Add(v.DisplayName, value);
                    try
                    {
                        var test = new { value = value };
                        if (value.GetType() == typeof(System.Data.DataTable))
                        {
                            continue;
                        }
                        if (value.GetType() == typeof(System.Data.DataView))
                        {
                            continue;
                        }
                        if (value.GetType() == typeof(System.Data.DataRowView))
                        {
                            continue;
                        }
                        //
                        var asjson = JObject.FromObject(test);
                        _payload[v.DisplayName] = value;
                    }
                    catch (Exception)
                    {
                    }
                }
                else
                {
                    _payload[v.DisplayName] = value;
                }
            }
            try
            {
                bookmarkname = Guid.NewGuid().ToString().Replace("{", "").Replace("}", "").Replace("-", "");
                if (waitforcompleted)
                {
                    context.CreateBookmark(bookmarkname, new BookmarkCallback(OnBookmarkCallback));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
                throw;
            }
            try
            {
                if (!string.IsNullOrEmpty(bookmarkname))
                {
                    IDictionary <string, object> _robotcommand = new System.Dynamic.ExpandoObject();
                    _robotcommand["workflowid"] = workflow;
                    _robotcommand["command"]    = "invoke";
                    _robotcommand.Add("data", _payload);
                    var result = await global.webSocketClient.QueueMessage(target, _robotcommand, bookmarkname);
                }
            }
            catch (Exception ex)
            {
                var i = WorkflowInstance.Instances.Where(x => x.InstanceId == WorkflowInstanceId).FirstOrDefault();
                if (i != null)
                {
                    i.Abort(ex.Message);
                }
                //context.RemoveBookmark(bookmarkname);
                Log.Error(ex.ToString());
            }
        }
Esempio n. 19
0
        internal object ToDictionary(object input)
        {
            if (input == null)
            {
                return(null);               //null checking for special scenarios
            }
            if (input is KeyValuePair <string, string> kvp && (kvp.Key == null || kvp.Value == null))
            {
                return(null);
            }
            if (input is BigDBObjectValue bdbov && bdbov.Value == null)
            {
                switch (bdbov.Type)  //return special nulls
                {
                default:
                    return(null);

                case ObjectType.DatabaseObject:
                    return(new DatabaseObject());

                case ObjectType.DatabaseArray:
                    return(new DatabaseArray());
                }
            }

            var dictionary = new System.Dynamic.ExpandoObject() as IDictionary <string, object>;

            switch (input)
            {
            case DatabaseObject databaseObject:
                foreach (var property in databaseObject.Properties)
                {
                    dictionary.Add(property.Key, ToDictionary(property.Value));
                }
                break;

            case BigDBObjectValue objectValue:
                switch (objectValue.Type)
                {
                case ObjectType.DatabaseArray:
                    var array = new object[objectValue.ValueArray.Length];
                    for (var i = 0; i < objectValue.ValueArray.Length; i++)
                    {
                        array[i] = ToDictionary(objectValue.ValueArray[i].Value);
                    }
                    return(array);

                case ObjectType.DatabaseObject:
                    foreach (var property in (dynamic)objectValue.Value)
                    {
                        dictionary.Add(property.Key.ToString(), ToDictionary(property.Value));
                    }
                    break;

                default: return(ToDictionary(objectValue.Value));
                }
                break;

            default: return(input);
            }

            return(dictionary);
        }
Esempio n. 20
0
        private object GetObjectFromMetadata(TreeDirectory metadata, TreeDirectory hirachciDirectory)
        {
            if (metadata.Element.Options.IsArray)
            {
                var arreyElemnts = metadata.Childrean.Where(x => x.IsArrayElement).OrderBy(x => x.ElementArrayIndex);
                object[] array = arreyElemnts.Select(y => GetObjectFromMetadata(y, hirachciDirectory)).ToArray();
                if (_delocalizing && array.All(x => x is LocalizedString))
                {
                    CultureInfo systemCulture = System.Globalization.CultureInfo.CurrentCulture;
                    LocalizedString matchingString = null;
                    do
                    {
                        matchingString = array.OfType<LocalizedString>().FirstOrDefault(x => x.Culture.Equals(systemCulture));
                        if (systemCulture.Parent.Equals(systemCulture))
                            break; // We are at the Culture Root. so break or run for ever.
                        systemCulture = systemCulture.Parent;

                    } while (matchingString == null);

                    if (matchingString != null)
                        return matchingString.Value;
                }
                if (_flatten && array.Length == 1)
                    return array[0];
                return array;
            }
            else if (metadata.Element.Options.IsStruct)
            {
                IDictionary<string, object> obj = new System.Dynamic.ExpandoObject();
                List<TreeDirectory> properties = metadata.Childrean;// directories.XmpMeta.Properties.Where(x => x.Path != null && x.Path.StartsWith(metadata.Path))

                foreach (var prop in properties)
                {
                    obj.Add(prop.ElementName, GetObjectFromMetadata(prop, hirachciDirectory));
                }
                return obj;
            }
            else if (metadata.Element.Options.IsSimple)
            {
                //xml:lang, de

                if (metadata.Element.Options.HasLanguage)
                {
                    TreeDirectory langMetadata = metadata.Childrean.Single(x => x.ElementName == "lang" && x.ElementNameSpace == "http://www.w3.org/XML/1998/namespace");
                    System.Globalization.CultureInfo culture;
                    if (langMetadata.ElementValue == "x-default")
                    {
                        culture = System.Globalization.CultureInfo.InvariantCulture;
                    }
                    else
                    {
                        culture = System.Globalization.CultureInfo.GetCultureInfo(langMetadata.ElementValue);
                    }

                    return new LocalizedString() { Culture = culture, Value = metadata.ElementValue };

                }

                return metadata.ElementValue;
            }
            else
            {
                throw new NotSupportedException($"Option {metadata.Element.Options.GetOptionsString()} not supported.");
            }
        }
Esempio n. 21
0
        protected override void Execute(NativeActivityContext context)
        {
            string WorkflowInstanceId             = context.WorkflowInstanceId.ToString();
            var    killifrunning                  = KillIfRunning.Get(context);
            string bookmarkname                   = null;
            bool   waitforcompleted               = WaitForCompleted.Get(context);
            IDictionary <string, object> _payload = new System.Dynamic.ExpandoObject();

            if (Arguments == null || Arguments.Count == 0)
            {
                var vars = context.DataContext.GetProperties();
                foreach (dynamic v in vars)
                {
                    var value = v.GetValue(context.DataContext);
                    if (value != null)
                    {
                        //_payload.Add(v.DisplayName, value);
                        try
                        {
                            var test = new { value = value };

                            if (value.GetType() == typeof(System.Data.DataView))
                            {
                                continue;
                            }
                            if (value.GetType() == typeof(System.Data.DataRowView))
                            {
                                continue;
                            }

                            if (value.GetType() == typeof(System.Data.DataTable))
                            {
                                if (value != null)
                                {
                                    _payload[v.DisplayName] = ((System.Data.DataTable)value).ToJArray();
                                }
                            }
                            else
                            {
                                var asjson = JObject.FromObject(test);
                                _payload[v.DisplayName] = value;
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                    else
                    {
                        _payload[v.DisplayName] = null;
                    }
                }
            }
            else
            {
                Dictionary <string, object> arguments = (from argument in Arguments
                                                         where argument.Value.Direction != ArgumentDirection.Out
                                                         select argument).ToDictionary((KeyValuePair <string, Argument> argument) => argument.Key, (KeyValuePair <string, Argument> argument) => argument.Value.Get(context));
                foreach (var a in arguments)
                {
                    var value = a.Value;
                    if (value != null)
                    {
                        if (value.GetType() == typeof(System.Data.DataView))
                        {
                            continue;
                        }
                        if (value.GetType() == typeof(System.Data.DataRowView))
                        {
                            continue;
                        }

                        if (value.GetType() == typeof(System.Data.DataTable))
                        {
                            if (value != null)
                            {
                                _payload[a.Key] = ((System.Data.DataTable)value).ToJArray();
                            }
                        }
                        else
                        {
                            _payload[a.Key] = a.Value;
                        }
                    }
                    else
                    {
                        _payload[a.Key] = null;
                    }
                }
            }
            try
            {
                bookmarkname = Guid.NewGuid().ToString().Replace("{", "").Replace("}", "").Replace("-", "");
                if (waitforcompleted)
                {
                    context.CreateBookmark(bookmarkname, new BookmarkCallback(OnBookmarkCallback));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
                throw;
            }
            try
            {
                if (!string.IsNullOrEmpty(bookmarkname))
                {
                    int expiration = Expiration.Get(context);
                    IDictionary <string, object> _robotcommand = new System.Dynamic.ExpandoObject();
                    _robotcommand["workflowid"]   = workflow.Get(context);
                    _robotcommand["killexisting"] = killifrunning;
                    _robotcommand["command"]      = "invoke";
                    _robotcommand.Add("data", _payload);
                    var result = global.webSocketClient.QueueMessage(target.Get(context), _robotcommand, RobotInstance.instance.robotqueue, bookmarkname, expiration);
                    result.Wait(5000);
                }
            }
            catch (Exception ex)
            {
                var i = WorkflowInstance.Instances.Where(x => x.InstanceId == WorkflowInstanceId).FirstOrDefault();
                if (i != null)
                {
                    i.Abort(ex.Message);
                }
                //context.RemoveBookmark(bookmarkname);
                Log.Error(ex.ToString());
            }
        }
Esempio n. 22
0
        private object GetObjectFromMetadata(TreeDirectory metadata, TreeDirectory hirachciDirectory)
        {
            if (metadata.Element.Options.IsArray)
            {
                IOrderedEnumerable <TreeDirectory> arreyElemnts = metadata.Childrean.Where(x => x.IsArrayElement).OrderBy(x => x.ElementArrayIndex);
                object[] array = arreyElemnts.Select(y => GetObjectFromMetadata(y, hirachciDirectory)).ToArray();
                if (_delocalizing && array.All(x => x is LocalizedString))
                {
                    CultureInfo     systemCulture  = System.Globalization.CultureInfo.CurrentCulture;
                    LocalizedString matchingString = null;
                    do
                    {
                        matchingString = array.OfType <LocalizedString>().FirstOrDefault(x => x.Culture.Equals(systemCulture));
                        if (systemCulture.Parent.Equals(systemCulture))
                        {
                            // We are at the Culture Root. so break or run for ever.
                            break;
                        }
                        systemCulture = systemCulture.Parent;
                    }while (matchingString == null);

                    if (matchingString != null)
                    {
                        return(matchingString.Value);
                    }
                }
                if (_flatten && array.Length == 1)
                {
                    return(array[0]);
                }

                return(array);
            }
            else if (metadata.Element.Options.IsStruct)
            {
                IDictionary <string, object> obj        = new System.Dynamic.ExpandoObject();
                List <TreeDirectory>         properties = metadata.Childrean; // directories.XmpMeta.Properties.Where(x => x.Path != null && x.Path.StartsWith(metadata.Path))

                foreach (TreeDirectory prop in properties)
                {
                    obj.Add(prop.ElementName, GetObjectFromMetadata(prop, hirachciDirectory));
                }
                return(obj);
            }
            else if (metadata.Element.Options.IsSimple)
            {
                // xml:lang, de

                if (metadata.Element.Options.HasLanguage)
                {
                    TreeDirectory langMetadata = metadata.Childrean.Single(x => x.ElementName == "lang" && x.ElementNameSpace == "http://www.w3.org/XML/1998/namespace");
                    System.Globalization.CultureInfo culture;
                    if (langMetadata.ElementValue == "x-default")
                    {
                        culture = CultureInfo.InvariantCulture;
                    }
                    else
                    {
                        culture = System.Globalization.CultureInfo.GetCultureInfo(langMetadata.ElementValue);
                    }

                    return(new LocalizedString()
                    {
                        Culture = culture, Value = metadata.ElementValue
                    });
                }

                return(metadata.ElementValue);
            }
            else
            {
                throw new NotSupportedException($"Option {metadata.Element.Options.GetOptionsString()} not supported.");
            }
        }
Esempio n. 23
0
        public GraphWindow()
        {
            try
            {
                InitializeComponent();
                CanvasStates.Clear();

                canvas.Children.Clear();
                canvasGraph.Children.Clear();


                if (ConfigurationHelper.ComputeCharts || ConfigurationHelper.ComputeGraph || ConfigurationHelper.ComputeEquations)
                {
                    System.Diagnostics.Stopwatch myStopwatch = new System.Diagnostics.Stopwatch();
                    myStopwatch.Start();

                    var elementInf = new List <ElementInformation>();

                    foreach (var elm in ConfigurationHelper.Modules.DistinctBy(b => b.Name))
                    {
                        elementInf.Add(new ElementInformation()
                        {
                            M = elm.M, L = elm.L, Name = elm.Name, AllRepairCount = ConfigurationHelper.UseRepairModules ? elm.RepairCount : 0
                        });
                    }

                    var systemState = new SystemState(elementInf, ConfigurationHelper.WorkCondition, ConfigurationHelper.Modules.Count);
                    systemState.GetDistinctSystemStates(elementInf);

                    var connections = systemState.SystemStates.Sum(s => s.BaseStates.Count) + systemState.SystemStates.Sum(s => s.ChildStates.Count);

                    dateGrid.ItemsSource = systemState.SystemStates;

                    var textArray = new string[] {
                        "",
                        $"Modules: {systemState.CountModule}",
                        $"CurrentRepairCount: {systemState.SystemElements.First().AllRepairCount}",
                        $"SystemStates: {systemState.SystemStates.Count}",
                        $"connections: {connections}",
                        ""
                    };
                    File.AppendAllLines(@"C:\Users\cemiv\Desktop\1.txt", textArray);


                    SystemState = systemState;
                    myStopwatch.Stop();
                    var ms = myStopwatch.Elapsed;
                    Presenters.Path.logFormElements.Add($"Get system states {ms} ms.");
                }
                if (ConfigurationHelper.ComputeGraph)
                {
                    System.Diagnostics.Stopwatch myStopwatch = new System.Diagnostics.Stopwatch();
                    myStopwatch.Start();
                    //todo ShowGraph();
                    myStopwatch.Stop();
                    var ms = myStopwatch.Elapsed;
                    Presenters.Path.logFormElements.Add($"Get graph {ms} ms.");
                }


                if (ConfigurationHelper.ComputeEquations)
                {
                    System.Diagnostics.Stopwatch myStopwatch = new System.Diagnostics.Stopwatch();
                    myStopwatch.Start();
                    var result = GetEquations();
                    dateGridQ.ItemsSource = result;
                    myStopwatch.Stop();
                    var ms = myStopwatch.Elapsed;
                    Presenters.Path.logFormElements.Add($"Get sysytem equations {ms} ms.");
                }

                if (ConfigurationHelper.ComputeCharts)
                {
                    System.Diagnostics.Stopwatch myStopwatch = new System.Diagnostics.Stopwatch();
                    myStopwatch.Start();


                    List <double> workValues      = new List <double>();
                    List <double> downTimeValues  = new List <double>();
                    List <double> errorTimeValues = new List <double>();
                    List <double> timeList        = new List <double>();


                    baseValues[0] = 1;

                    System.Diagnostics.Stopwatch myStopwatch1 = new System.Diagnostics.Stopwatch();
                    myStopwatch1.Start();

                    //   var result1 = ConfigurationHelper.MatLabContext.ComputeDifferentialEquations(equations, baseValues, ConfigurationHelper.Step, 0, (int)ConfigurationHelper.MaxTime);

                    //var aaa = $"F=@(t,p) [{String.Join("; ", equations).Replace(",", ".")}]; [t p]=ode45(F,[{1} : {1} : {1}], [{String.Join(" ", baseValues)}]);";
                    myStopwatch1.Stop();



                    System.Diagnostics.Stopwatch myStopwatch2 = new System.Diagnostics.Stopwatch();
                    myStopwatch2.Start();

                    var result1 = new List <List <double> >();

                    //var result1 = ConfigurationHelper.MatLabContext.ComputeDifferentialEquations(equations, baseValues, ConfigurationHelper.Step, 0, (int)ConfigurationHelper.MaxTime);

                    var result12 = RungeKuttaMethod.RungeKuttaMethods(equations.Count, (int)ConfigurationHelper.Step, (int)ConfigurationHelper.MaxTime, equationCoefficients, baseValues.Select(s => (double)s).ToArray());

                    var baseValuesq = baseValues.Select(s => (double)s).ToList();

                    result1.Add(baseValuesq);
                    result1.AddRange(result12);
                    myStopwatch2.Stop();



                    double startTime = 0;

                    ConfigurationHelper.RungeKutteStringTable.Clear();



                    // Add columns
                    var headers  = new List <string>();
                    var gridView = new GridView();
                    this.listView.View = gridView;
                    gridView.Columns.Add(new GridViewColumn
                    {
                        Header = $"{Properties.Resources.Time}",
                        DisplayMemberBinding = new Binding($"{Properties.Resources.Time}")
                    });
                    headers.Add(Properties.Resources.Time);


                    for (var i = 0; i <= SystemState.SystemStates.Count; i++)
                    {
                        gridView.Columns.Add(new GridViewColumn
                        {
                            Header = $"S{i+1}",
                            DisplayMemberBinding = new Binding($"S{i+1}")
                        });

                        headers.Add($"S{i + 1}");
                    }

                    gridView.Columns.Add(new GridViewColumn
                    {
                        Header = $"{Properties.Resources.SumWorkingStates}",
                        DisplayMemberBinding = new Binding($"Working")
                    });
                    headers.Add(Properties.Resources.SumWorkingStates);

                    gridView.Columns.Add(new GridViewColumn
                    {
                        Header = $"{Properties.Resources.SumDownTiimeStates}",
                        DisplayMemberBinding = new Binding($"Downtime")
                    });
                    headers.Add(Properties.Resources.SumDownTiimeStates);


                    gridView.Columns.Add(new GridViewColumn
                    {
                        Header = $"{Properties.Resources.SumRefusalStates}",
                        DisplayMemberBinding = new Binding($"Refusal")
                    });
                    headers.Add(Properties.Resources.SumRefusalStates);

                    ConfigurationHelper.RungeKutteStringTable.AppendLine(String.Join(", ", headers));

                    var workDictionary     = new Dictionary <double, double>();
                    var downTimeDictionary = new Dictionary <double, double>();
                    var refusalDictionary  = new Dictionary <double, double>();


                    double indexCount = 0;
                    foreach (var item in result1)
                    {
                        var ListViewObject = new System.Dynamic.ExpandoObject() as IDictionary <string, Object>;

                        timeList.Add(startTime);
                        double workValue     = 0;
                        double downTimeValue = 0;

                        for (var index = 0; index < item.Count; index++)
                        {
                            if (SystemState.WorkStateIndexList.Contains(index))
                            {
                                workValue += item[index];
                            }
                            if (SystemState.DownTimeStateIndexList.Contains(index))
                            {
                                downTimeValue += item[index];
                            }

                            ListViewObject.Add($"S{index + 1}", Math.Round(item[index], 15));
                        }
                        workValues.Add(workValue);
                        downTimeValues.Add(downTimeValue);
                        var sum = downTimeValue + workValue;
                        errorTimeValues.Add(1 - sum);
                        workDictionary.Add(indexCount, workValue);
                        downTimeDictionary.Add(indexCount, downTimeValue);
                        refusalDictionary.Add(indexCount, 1 - sum);
                        indexCount += ConfigurationHelper.Step;



                        ListViewObject.Add("Time", startTime);

                        ListViewObject.Add("Working", Math.Round(workValue, 15));
                        ListViewObject.Add("Downtime", Math.Round(downTimeValue, 15));
                        ListViewObject.Add("Refusal", Math.Round(1 - sum, 15));

                        var tableValues = new List <string>();

                        tableValues.Add(Math.Round(workValue, 15).ToString());
                        tableValues.AddRange(item.Select(s => Math.Round(s, 15).ToString()).ToList());
                        tableValues.Add(Math.Round(workValue, 15).ToString());
                        tableValues.Add(downTimeValue.ToString());
                        tableValues.Add(Math.Round(1 - sum, 15).ToString());
                        ConfigurationHelper.RungeKutteStringTable.AppendLine(String.Join(", ", tableValues));

                        // Populate list
                        this.listView.Items.Add(ListViewObject);



                        startTime += ConfigurationHelper.Step;
                    }



                    var RectangleMethodWork = Integral.RectangleMethod(workDictionary, 0, ConfigurationHelper.MaxTime, (int)(ConfigurationHelper.MaxTime / ConfigurationHelper.Step));
                    var TrapeziumMethodWork = Integral.TrapeziumMethod(workDictionary, 0, ConfigurationHelper.MaxTime, (int)(ConfigurationHelper.MaxTime / ConfigurationHelper.Step));

                    this.T_work.Content = $"{Properties.Resources.AverageWorkTime} = {Math.Round(TrapeziumMethodWork,6)}";


                    var RectangleMethodDownTime = Integral.RectangleMethod(downTimeDictionary, 0, ConfigurationHelper.MaxTime, (int)(ConfigurationHelper.MaxTime / ConfigurationHelper.Step));
                    var TrapeziumMethodDownTime = Integral.TrapeziumMethod(downTimeDictionary, 0, ConfigurationHelper.MaxTime, (int)(ConfigurationHelper.MaxTime / ConfigurationHelper.Step));

                    this.T_down.Content = $"{Properties.Resources.AverageDowntimeTime} = {Math.Round(TrapeziumMethodDownTime, 6)}";


                    var RectangleMethodRefusal = Integral.RectangleMethod(refusalDictionary, 0, ConfigurationHelper.MaxTime, (int)(ConfigurationHelper.MaxTime / ConfigurationHelper.Step));
                    var TrapeziumMethodRefusal = Integral.TrapeziumMethod(refusalDictionary, 0, ConfigurationHelper.MaxTime, (int)(ConfigurationHelper.MaxTime / ConfigurationHelper.Step));
                    this.T_error.Content = $"{Properties.Resources.AverageRefusalTime} = {Math.Round(TrapeziumMethodRefusal, 6)}";

                    var yDataSource = new EnumerableDataSource <double>(workValues);

                    var suumm  = RectangleMethodWork + RectangleMethodDownTime + RectangleMethodRefusal;
                    var suumm1 = TrapeziumMethodWork + TrapeziumMethodDownTime + TrapeziumMethodRefusal;


                    yDataSource.SetYMapping(Y => Y);

                    var xDataSource = new EnumerableDataSource <double>(timeList);
                    xDataSource.SetXMapping(X => X);

                    CompositeDataSource compositeDataSource = new CompositeDataSource(xDataSource, yDataSource);

                    //   plotterWork.AddHandler(CircleElementPointMarker.ToolTipTextProperty, s => String.Format("Y-Data : {0}\nX-Data : {1}", s.Y, s.X));
                    plotterWork.Children.RemoveAll(typeof(LineGraph));
                    plotterWork.AddLineGraph(compositeDataSource, new Pen(Brushes.Green, 2), new PenDescription("Work Line"));
                    plotterWork.FitToView();


                    yDataSource = new EnumerableDataSource <double>(downTimeValues);
                    yDataSource.SetYMapping(Y => Y);

                    xDataSource = new EnumerableDataSource <double>(timeList);
                    xDataSource.SetXMapping(X => X);

                    compositeDataSource = new CompositeDataSource(xDataSource, yDataSource);

                    plotterDownTime.Children.RemoveAll(typeof(LineGraph));
                    plotterDownTime.AddLineGraph(compositeDataSource, new Pen(Brushes.Orange, 2), new PenDescription("Down Time Line"));
                    plotterDownTime.FitToView();

                    yDataSource = new EnumerableDataSource <double>(errorTimeValues);
                    yDataSource.SetYMapping(Y => Y);

                    xDataSource = new EnumerableDataSource <double>(timeList);
                    xDataSource.SetXMapping(X => X);

                    compositeDataSource = new CompositeDataSource(xDataSource, yDataSource);

                    plotterErrorTime.Children.RemoveAll(typeof(LineGraph));
                    plotterErrorTime.AddLineGraph(compositeDataSource, new Pen(Brushes.Red, 2), new PenDescription("Error Time Line"));
                    plotterErrorTime.FitToView();

                    myStopwatch.Stop();
                    var ms = myStopwatch.Elapsed;
                    Presenters.Path.logFormElements.Add($"Get charts of reliability time ex. {ms} ms.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }
Esempio n. 24
0
        protected override async Task ProcessRecordAsync()
        {
            try
            {
                RuntimeDefinedParameter targetnameparameter   = null;
                RuntimeDefinedParameter workflownameparameter = null;
                if (_staticStorage != null)
                {
                    _staticStorage.TryGetValue("TargetName", out targetnameparameter);
                    _staticStorage.TryGetValue("WorkflowName", out workflownameparameter);
                }
                apiuser  robot    = null;
                string   targetid = TargetId;
                workflow workflow;
                string   workflowid = WorkflowId;
                if (targetnameparameter != null && targetnameparameter.Value != null)
                {
                    targetid = targetnameparameter.Value.ToString();
                }
                if (!string.IsNullOrEmpty(targetid))
                {
                    robot = (_robots == null?null: _robots.Where(x => x.name == targetid).FirstOrDefault());
                    if (robot != null)
                    {
                        targetid = robot._id;
                    }
                }
                if (_Collections == null)
                {
                    Initialize().Wait();
                }
                if (_workflows == null && robot != null)
                {
                    _workflows = await global.webSocketClient.Query <workflow>("openrpa", "{_type: 'workflow'}", projection : "{\"projectandname\": 1}", queryas : robot._id, top : 2000);
                }
                if (workflownameparameter != null && workflownameparameter.Value != null)
                {
                    workflow = _workflows.Where(x => x.ProjectAndName == workflownameparameter.Value.ToString()).FirstOrDefault();
                    if (workflow != null)
                    {
                        workflowid = workflow._id;
                    }
                }
                if (string.IsNullOrEmpty(targetid))
                {
                    WriteError(new ErrorRecord(new Exception("Missing robot name or robot id"), "", ErrorCategory.NotSpecified, null));
                    return;
                }
                robot = (_robots == null ? null: _robots.Where(x => x._id == targetid).FirstOrDefault());
                if (string.IsNullOrEmpty(workflowid))
                {
                    WriteError(new ErrorRecord(new Exception("Missing workflow name or workflow id"), "", ErrorCategory.NotSpecified, null));
                    return;
                }
                _staticStorage = null;
                callcount      = 0;
                workflow       = (_workflows == null?null : _workflows.Where(x => x._id == workflowid).FirstOrDefault());
                if (Object != null)
                {
                    json = Object.toJson();
                }
                if (string.IsNullOrEmpty(json))
                {
                    json = "{}";
                }
                await RegisterQueue();

                JObject tmpObject = JObject.Parse(json);
                correlationId = Guid.NewGuid().ToString().Replace("{", "").Replace("}", "").Replace("-", "");

                if (global.webSocketClient != null)
                {
                    global.webSocketClient.OnQueueMessage += WebSocketClient_OnQueueMessage;
                }

                IDictionary <string, object> _robotcommand = new System.Dynamic.ExpandoObject();
                _robotcommand["workflowid"] = workflowid;
                _robotcommand["command"]    = "invoke";
                _robotcommand.Add("data", tmpObject);
                if (robot != null)
                {
                    WriteProgress(new ProgressRecord(0, "Invoking", "Invoking " + workflow.ProjectAndName + " on " + robot.name + "(" + robot.username + ")"));
                }
                if (robot == null)
                {
                    WriteProgress(new ProgressRecord(0, "Invoking", "Invoking " + workflowid + " on " + targetid));
                }
                var result = await global.webSocketClient.QueueMessage(targetid, _robotcommand, psqueue, correlationId);

                workItemsWaiting.WaitOne();
                WriteProgress(new ProgressRecord(0, "Invoking", "completed")
                {
                    RecordType = ProgressRecordType.Completed
                });
                if (command.command == "invokefailed" || command.command == "invokeaborted")
                {
                    var _ex = new Exception("Invoke failed");
                    if (command.data != null && !string.IsNullOrEmpty(command.data.ToString()))
                    {
                        try
                        {
                            _ex = Newtonsoft.Json.JsonConvert.DeserializeObject <Exception>(command.data.ToString());
                        }
                        catch (Exception)
                        {
                        }
                    }
                    WriteError(new ErrorRecord(_ex, "", ErrorCategory.NotSpecified, null));
                    return;
                }
                if (command.data != null && !string.IsNullOrEmpty(command.data.ToString()))
                {
                    var payload = JObject.Parse(command.data.ToString());
                    var _result = payload.toPSObject();
                    WriteObject(_result);
                }
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null));
                WriteProgress(new ProgressRecord(0, "Invoking", "completed")
                {
                    RecordType = ProgressRecordType.Completed
                });
            }
        }
        private string GenerateMarkup(Dictionary <string, string> Attributes)
        {
            try
            {
                string Template = string.Empty;
                Dictionary <string, string> blockAttribute = new Dictionary <string, string>();
                string Keyword = HttpContext.Current.Request.QueryString["Search"];
                if (!string.IsNullOrEmpty(Keyword))
                {
                    PortalSettings ps = PortalController.Instance.GetCurrentSettings() as PortalSettings;
                    if (Attributes.ContainsKey("data-block-pageindex"))
                    {
                        blockAttribute.Add("data-block-pageindex", Attributes["data-block-pageindex"]);
                    }
                    Dictionary <string, string> baseAttributes = Core.Managers.BlockManager.GetGlobalConfigs(ps, "search result");

                    if (Attributes["data-block-global"] == "true")
                    {
                        Attributes.Clear();
                        if (baseAttributes != null)
                        {
                            foreach (KeyValuePair <string, string> baseattr in baseAttributes)
                            {
                                Attributes.Add(baseattr.Key, baseattr.Value);
                            }
                        }
                    }
                    else
                    {
                        //Loop on base attributes and add missing attribute
                        if (baseAttributes != null)
                        {
                            foreach (KeyValuePair <string, string> attr in baseAttributes)
                            {
                                if (!Attributes.ContainsKey(attr.Key))
                                {
                                    Attributes.Add(attr.Key, attr.Value);
                                }
                            }
                        }
                    }

                    foreach (KeyValuePair <string, string> t in blockAttribute)
                    {
                        if (!Attributes.ContainsKey(t.Key))
                        {
                            Attributes.Add(t.Key, t.Value);
                        }
                    }

                    Entities.SearchResult searchResult = new Entities.SearchResult(Keyword, Attributes)
                    {
                        LinkTargetOpenInNewTab = Attributes.ContainsKey("data-block-linktarget") && Attributes["data-block-linktarget"] == "false" ? false : true
                    };
                    IDictionary <string, object> dynObjects = new System.Dynamic.ExpandoObject() as IDictionary <string, object>;
                    dynObjects.Add("SearchResult", searchResult);
                    Template = RazorEngineManager.RenderTemplate(ExtensionInfo.GUID, BlockPath, Attributes["data-block-template"], dynObjects);
                    Template = new DNNLocalizationEngine(null, ResouceFilePath, false).Parse(Template);
                }
                else
                {
                    Template = "<div class='Searchresultempty'><div class='no-search-result-found search-info-msg'>" + Localization.GetString("NoSearchResultFound", Components.Constants.LocalResourcesFile) + "</div></div>";
                }
                return(Template);
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                return(ex.Message);
            }
        }