public object PersistForm(PersistFormRequest request)
        {
            // Variables.
            var result      = default(object);
            var formsRootId = GuidHelper.GetGuid(FormConstants.Id);
            var parentId    = GuidHelper.GetGuid(request.ParentId);


            // Catch all errors.
            try
            {
                // Parse or create the form ID.
                var isNew  = string.IsNullOrWhiteSpace(request.FormId);
                var formId = isNew
                    ? Guid.NewGuid()
                    : GuidHelper.GetGuid(request.FormId);


                // Get the fields.
                var fields = request.Fields.MakeSafe()
                             .Select(x =>
                {
                    var fieldType         = Type.GetType(x.TypeFullName);
                    var fieldTypeInstance = FormFieldTypeCollection
                                            .FirstOrDefault(y => y.GetType() == fieldType);

                    var field = new FormField(fieldTypeInstance)
                    {
                        Id = string.IsNullOrWhiteSpace(x.Id)
                                ? Guid.NewGuid()
                                : GuidHelper.GetGuid(x.Id),
                        Alias       = x.Alias,
                        Name        = x.Name,
                        Label       = x.Label,
                        Category    = x.Category,
                        Validations = x.Validations.MakeSafe()
                                      .Select(y => GuidHelper.GetGuid(y)).ToArray(),
                        FieldConfiguration = JsonHelper.Serialize(x.Configuration)
                    };
                    return(field);
                })
                             .ToArray();


                // Get the handlers.
                var handlers = request.Handlers.MakeSafe().Select(x =>
                {
                    var handlerType         = Type.GetType(x.TypeFullName);
                    var handlerTypeInstance = FormHandlerTypeCollection
                                              .FirstOrDefault(y => y.GetType() == handlerType);

                    var handler = new FormHandler(handlerTypeInstance)
                    {
                        Id = string.IsNullOrWhiteSpace(x.Id)
                            ? Guid.NewGuid()
                            : GuidHelper.GetGuid(x.Id),
                        Alias   = x.Alias,
                        Name    = x.Name,
                        Enabled = x.Enabled,
                        HandlerConfiguration = JsonHelper.Serialize(x.Configuration)
                    };

                    return(handler);
                }).ToArray();


                // Get the ID path.
                var parent = parentId == Guid.Empty ? null : Entities.Retrieve(parentId);
                var path   = parent == null
                    ? new[] { formsRootId, formId }
                    : parent.Path.Concat(new[] { formId }).ToArray();


                // Create the form.
                var form = new Form()
                {
                    Id       = formId,
                    Path     = path,
                    Alias    = request.Alias,
                    Name     = request.Name,
                    Fields   = fields,
                    Handlers = handlers
                };


                // Persist the form.
                Persistence.Persist(form);


                // For new forms, automatically create a layout and a form configuration.
                var layoutNamePrefix  = "Layout for ";
                var layoutNameSuffix  = " (Autogenerated)";
                var layoutAliasPrefix = "layout_";
                var layoutAliasSuffix = "_autogenerated";
                var autoLayoutData    = JsonHelper.Serialize(new
                {
                    rows = new[]
                    {
                        new
                        {
                            cells = new []
                            {
                                new
                                {
                                    columnSpan = 12,
                                    fields     = form.Fields.Select(x => new
                                    {
                                        id = GuidHelper.GetString(x.Id)
                                    })
                                }
                            }
                        }
                    },
                    formId       = GuidHelper.GetString(form.Id),
                    autopopulate = true
                });
                if (isNew)
                {
                    // Create new layout.
                    var layoutId = Guid.NewGuid();
                    var layout   = new Layout()
                    {
                        KindId = GuidHelper.GetGuid(app.Constants.Layouts.LayoutBasic.Id),
                        Id     = layoutId,
                        Path   = new[] { GuidHelper.GetGuid(LayoutConstants.Id), layoutId },
                        Name   = layoutNamePrefix + request.Name + layoutNameSuffix,
                        Alias  = layoutAliasPrefix + request.Alias + layoutAliasSuffix,
                        Data   = autoLayoutData
                    };


                    // Persist layout.
                    LayoutPersistence.Persist(layout);


                    // Create a new form configuration.
                    var plainJsTemplateId = GuidHelper.GetGuid("f3fb1485c1d14806b4190d7abde39530");
                    var template          = Config.Templates.FirstOrDefault(x => x.Id == plainJsTemplateId)
                                            ?? Config.Templates.FirstOrDefault();
                    var configId       = Guid.NewGuid();
                    var configuredForm = new ConfiguredForm()
                    {
                        Id         = configId,
                        Path       = path.Concat(new[] { configId }).ToArray(),
                        Name       = request.Name,
                        TemplateId = template?.Id,
                        LayoutId   = layoutId
                    };


                    // Persist form configuration.
                    ConFormPersistence.Persist(configuredForm);
                }


                // Get existing layouts that should autopopulate.
                var layouts = GetFormLayouts(null)
                              .Select(x => new
                {
                    Layout        = x,
                    Configuration = x.DeserializeConfiguration() as LayoutBasicConfiguration
                })
                              .Where(x => x.Configuration != null)
                              .Where(x => x.Configuration.FormId.HasValue && x.Configuration.FormId.Value == formId)
                              .Where(x => x.Configuration.Autopopulate);


                //: Autopopulate the layouts.
                foreach (var existingLayout in layouts)
                {
                    existingLayout.Layout.Data = autoLayoutData;
                    var layoutName  = existingLayout.Layout.Name ?? string.Empty;
                    var layoutAlias = existingLayout.Layout.Alias ?? string.Empty;
                    if (layoutName.StartsWith(layoutNamePrefix) && layoutName.EndsWith(layoutNameSuffix))
                    {
                        existingLayout.Layout.Name = layoutNamePrefix + form.Name + layoutNameSuffix;
                    }
                    if (layoutAlias.StartsWith(layoutAliasPrefix) && layoutAlias.EndsWith(layoutAliasSuffix))
                    {
                        existingLayout.Layout.Alias = layoutAliasPrefix + form.Name + layoutAliasSuffix;
                    }
                    LayoutPersistence.Persist(existingLayout.Layout);
                }


                // Success.
                result = new
                {
                    Success = true,
                    FormId  = GuidHelper.GetString(formId)
                };
            }
            catch (Exception ex)
            {
                // Error.
                Logger.Error <FormsController>(ex, PersistFormError);
                result = new
                {
                    Success = false,
                    Reason  = UnhandledError
                };
            }


            // Return the result.
            return(result);
        }
        public object PersistConfiguredForm(PersistConfiguredFormRequest request)
        {
            // Variables.
            var result   = default(object);
            var rootId   = CoreConstants.System.Root.ToInvariantString();
            var parentId = GuidHelper.GetGuid(request.ParentId);


            // Catch all errors.
            try
            {
                // Parse or create the configured form ID.
                var conFormId = string.IsNullOrWhiteSpace(request.ConFormId)
                    ? Guid.NewGuid()
                    : GuidHelper.GetGuid(request.ConFormId);


                // Get the ID path.
                var parent = Entities.Retrieve(parentId);
                var path   = parent.Path.Concat(new[] { conFormId }).ToArray();


                // Create configured form.
                var configuredForm = new ConfiguredForm()
                {
                    Id         = conFormId,
                    Path       = path,
                    Name       = request.Name,
                    TemplateId = string.IsNullOrWhiteSpace(request.TemplateId)
                        ? null as Guid?
                        : GuidHelper.GetGuid(request.TemplateId),
                    LayoutId = string.IsNullOrWhiteSpace(request.LayoutId)
                        ? null as Guid?
                        : GuidHelper.GetGuid(request.LayoutId)
                };


                // Persist configured form.
                Persistence.Persist(configuredForm);


                // Variables.
                var fullPath = new[] { rootId }
                .Concat(path.Select(x => GuidHelper.GetString(x)))
                .ToArray();


                // Success.
                result = new
                {
                    Success = true,
                    Id      = GuidHelper.GetString(conFormId),
                    Path    = fullPath
                };
            }
            catch (Exception ex)
            {
                // Error.
                Logger.Error <ConfiguredFormsController>(ex, PersistConFormError);
                result = new
                {
                    Success = false,
                    Reason  = UnhandledError
                };
            }


            // Return result.
            return(result);
        }
Beispiel #3
0
 public PaymentItem(string description, decimal amount)
 {
     this.Id          = GuidHelper.NewSequentialId();
     this.Description = description;
     this.Amount      = amount;
 }
        public object GetDataValuesInfo(
            [FromUri] GetDataValuesInfoRequest request)
        {
            // Variables.
            var result = default(object);
            var rootId = CoreConstants.System.Root.ToInvariantString();


            // Catch all errors.
            try
            {
                // Variables.
                var ids = request.DataValueIds
                          .Select(x => GuidHelper.GetGuid(x));
                var dataValues = ids.Select(x => Persistence.Retrieve(x))
                                 .WithoutNulls();
                var kinds    = DataValueHelper.GetAllDataValueKinds();
                var combined = dataValues.Join(kinds,
                                               x => x.KindId,
                                               y => y.Id,
                                               (x, y) => new
                {
                    Value = x,
                    Kind  = y
                });


                // Set result.
                result = new
                {
                    Success    = true,
                    DataValues = combined.Select(x => new
                    {
                        DataValueId = GuidHelper.GetString(x.Value.Id),
                        KindId      = GuidHelper.GetString(x.Value.KindId),
                        Path        = new[] { rootId }
                        .Concat(GuidHelper.GetStrings(x.Value.Path))
                        .ToArray(),
                        Alias     = x.Value.Alias,
                        Name      = x.Value.Name,
                        Directive = x.Kind.Directive,
                        Data      = JsonHelper.Deserialize <object>(x.Value.Data)
                    }),
                };
            }
            catch (Exception ex)
            {
                // Error.
                LogHelper.Error <DataValuesController>(
                    GetDataValueInfoError, ex);
                result = new
                {
                    Success = false,
                    Reason  = UnhandledError
                };
            }


            // Return result.
            return(result);
        }
        public async Task SeedDataAsync()
        {
            var users = await _userService.BrowseAsync();

            if (users.Any())
            {
                return;
            }

            for (int i = 1; i <= 10; i++)
            {
                await _userService.CreateAsync(GuidHelper.GetGuidFromInt(i), $"user{i}@email.com", "password", $"user{i}");

                await _categoryService.CreateAsync(GuidHelper.GetGuidFromInt(i), $"category{i}");
            }

            for (int i = 1; i <= 10; i++)
            {
                await _postService.CreateAsync(GuidHelper.GetGuidFromInt(i), $"title{i}", $"content{i}", GuidHelper.GetGuidFromInt((i % 5) + 1));
            }
        }
Beispiel #6
0
        public override bool Create(SalarySummaryEntity entity)
        {
            //在创建实体时如果实体的Guid尚未指定,那么给其赋初值
            if (entity.SalarySummaryGuid == Guid.Empty)
            {
                entity.SalarySummaryGuid = GuidHelper.NewGuid();
            }

            string commandText = string.Format(@"Insert Into [XQYCSalarySummary] (
			[SalarySummaryGuid],
			[SalaryDate],
			[LaborKey],
			[LaborName],
			[LaborCode],
			[EnterpriseKey],
			[EnterpriseContractKey],
			[CreateUserKey],
			[CreateDate],
			[SalaryPayStatus],
			[SalaryGrossPay],
			[SalaryRebate],
			[SalaryRebateBeforeTax],
			[PersonBorrow],
			[IsCostCalculated],
			[SalaryCashDate],
			[InsuranceCashDate],
			[ReserveFundCashDate],
			[EnterpriseManageFeeReal],
			[EnterpriseManageFeeCalculated],
			[EnterpriseManageFeeCalculatedFix],
			[EnterpriseManageFeeCashDate],
			[EnterpriseGeneralRecruitFeeReal],
			[EnterpriseGeneralRecruitFeeCalculated],
			[EnterpriseGeneralRecruitFeeCalculatedFix],
			[EnterpriseGeneralRecruitFeeCashDate],
			[EnterpriseOnceRecruitFeeReal],
			[EnterpriseOnceRecruitFeeCalculated],
			[EnterpriseOnceRecruitFeeCalculatedFix],
			[EnterpriseOnceRecruitFeeCashDate],
			[EnterpriseInsuranceReal],
			[EnterpriseInsuranceCalculated],
			[EnterpriseInsuranceCalculatedFix],
			[EnterpriseReserveFundReal],
			[EnterpriseReserveFundCalculated],
			[EnterpriseReserveFundCalculatedFix],
			[PersonManageFeeReal],
			[PersonManageFeeCalculated],
			[PersonManageFeeCalculatedFix],
			[PersonInsuranceReal],
			[PersonInsuranceCalculated],
			[PersonInsuranceCalculatedFix],
			[PersonReserveFundReal],
			[PersonReserveFundCalculated],
			[PersonReserveFundCalculatedFix],
			[EnterpriseMixCostReal],
			[EnterpriseMixCostCalculated],
			[EnterpriseMixCostCalculatedFix],
			[PersonMixCostReal],
			[PersonMixCostCalculated],
			[PersonMixCostCalculatedFix],
			[EnterpriseOtherCostReal],
			[EnterpriseOtherCostCalculated],
			[EnterpriseOtherCostCalculatedFix],
			[PersonOtherCostReal],
			[PersonOtherCostCalculated],
			[PersonOtherCostCalculatedFix],
			[EnterpriseTaxFeeReal],
			[EnterpriseTaxFeeCalculated],
			[EnterpriseTaxFeeCalculatedFix],
			[EnterpriseTaxFeeCashDate],
			[EnterpriseOtherInsuranceReal],
			[EnterpriseOtherInsuranceCalculated],
			[EnterpriseOtherInsuranceCalculatedFix],
			[EnterpriseOtherInsuranceCashDate],
			[SalaryTaxReal],
			[SalaryTaxCalculated],
			[SalaryMemo],
			[IsCheckPast],
			[CheckMemo],
			[IsLocked],
			[SalarySettlementStartDate],
			[SalarySettlementEndDate],
			[IsFirstCash],
			[IsAdvanceCash],
			[PropertyNames],
			[PropertyValues]
        ) 
        Values (
			{0}SalarySummaryGuid,
			{0}SalaryDate,
			{0}LaborKey,
			{0}LaborName,
			{0}LaborCode,
			{0}EnterpriseKey,
			{0}EnterpriseContractKey,
			{0}CreateUserKey,
			{0}CreateDate,
			{0}SalaryPayStatus,
			{0}SalaryGrossPay,
			{0}SalaryRebate,
			{0}SalaryRebateBeforeTax,
			{0}PersonBorrow,
			{0}IsCostCalculated,
			{0}SalaryCashDate,
			{0}InsuranceCashDate,
			{0}ReserveFundCashDate,
			{0}EnterpriseManageFeeReal,
			{0}EnterpriseManageFeeCalculated,
			{0}EnterpriseManageFeeCalculatedFix,
			{0}EnterpriseManageFeeCashDate,
			{0}EnterpriseGeneralRecruitFeeReal,
			{0}EnterpriseGeneralRecruitFeeCalculated,
			{0}EnterpriseGeneralRecruitFeeCalculatedFix,
			{0}EnterpriseGeneralRecruitFeeCashDate,
			{0}EnterpriseOnceRecruitFeeReal,
			{0}EnterpriseOnceRecruitFeeCalculated,
			{0}EnterpriseOnceRecruitFeeCalculatedFix,
			{0}EnterpriseOnceRecruitFeeCashDate,
			{0}EnterpriseInsuranceReal,
			{0}EnterpriseInsuranceCalculated,
			{0}EnterpriseInsuranceCalculatedFix,
			{0}EnterpriseReserveFundReal,
			{0}EnterpriseReserveFundCalculated,
			{0}EnterpriseReserveFundCalculatedFix,
			{0}PersonManageFeeReal,
			{0}PersonManageFeeCalculated,
			{0}PersonManageFeeCalculatedFix,
			{0}PersonInsuranceReal,
			{0}PersonInsuranceCalculated,
			{0}PersonInsuranceCalculatedFix,
			{0}PersonReserveFundReal,
			{0}PersonReserveFundCalculated,
			{0}PersonReserveFundCalculatedFix,
			{0}EnterpriseMixCostReal,
			{0}EnterpriseMixCostCalculated,
			{0}EnterpriseMixCostCalculatedFix,
			{0}PersonMixCostReal,
			{0}PersonMixCostCalculated,
			{0}PersonMixCostCalculatedFix,
			{0}EnterpriseOtherCostReal,
			{0}EnterpriseOtherCostCalculated,
			{0}EnterpriseOtherCostCalculatedFix,
			{0}PersonOtherCostReal,
			{0}PersonOtherCostCalculated,
			{0}PersonOtherCostCalculatedFix,
			{0}EnterpriseTaxFeeReal,
			{0}EnterpriseTaxFeeCalculated,
			{0}EnterpriseTaxFeeCalculatedFix,
			{0}EnterpriseTaxFeeCashDate,
			{0}EnterpriseOtherInsuranceReal,
			{0}EnterpriseOtherInsuranceCalculated,
			{0}EnterpriseOtherInsuranceCalculatedFix,
			{0}EnterpriseOtherInsuranceCashDate,
			{0}SalaryTaxReal,
			{0}SalaryTaxCalculated,
			{0}SalaryMemo,
			{0}IsCheckPast,
			{0}CheckMemo,
			{0}IsLocked,
			{0}SalarySettlementStartDate,
			{0}SalarySettlementEndDate,
			{0}IsFirstCash,
			{0}IsAdvanceCash,
			{0}PropertyNames,
			{0}PropertyValues
        )", ParameterNamePrefix);

            TParameter[] sqlParas = PrepareParasAll(entity);

            bool isSuccessful = HelperExInstance.ExecuteSingleRowNonQuery(commandText, sqlParas);

            return(isSuccessful);
        }
Beispiel #7
0
 public EventTestMsg()
 {
     this.Id = GuidHelper.NewSequentialId();
 }
        public static void Install(IServiceProvider provider)
        {
            var unitOfWork     = provider.GetService <IUnitOfWork <EfDbContext> >();
            var repositoryUser = provider.GetService <IRepository <User> >();
            var repositoryRole = provider.GetService <IRepository <Role> >();
            var user           = repositoryUser.Get(x => x.Username == "atif.dag");
            var developerRole  = repositoryRole.Get(x => x.Code == "DEVELOPER");
            var defaultRole    = repositoryRole.Get(x => x.Code == "DEFAULTROLE");


            var listPermission                = new List <Permission>();
            var listPermissionHistory         = new List <PermissionHistory>();
            var listRolePermissionLine        = new List <RolePermissionLine>();
            var listRolePermissionLineHistory = new List <RolePermissionLineHistory>();


            var defaultUserPermissions = new List <Permission>
            {
                new Permission {
                    ControllerName = "Authentication", ActionName = "MyProfile"
                },
                new Permission {
                    ControllerName = "Authentication", ActionName = "UpdateMyInformation"
                },
                new Permission {
                    ControllerName = "Authentication", ActionName = "UpdateMyPassword"
                }
            };

            var totalCountDefaultUser = defaultUserPermissions.Count;
            var counterDefaultUser    = 1;


            foreach (var item in defaultUserPermissions)
            {
                item.Id                   = GuidHelper.NewGuid();
                item.CreationTime         = DateTime.Now;
                item.LastModificationTime = DateTime.Now;
                item.DisplayOrder         = 1;
                item.Version              = 1;
                item.IsApproved           = true;
                item.Creator              = user;
                item.LastModifier         = user;
                item.Code                 = item.ControllerName + item.ActionName;
                item.Name                 = item.ControllerName + " " + item.ActionName;
                listPermission.Add(item);

                var itemHistory = item.CreateMapped <Permission, PermissionHistory>();
                itemHistory.Id             = GuidHelper.NewGuid();
                itemHistory.ReferenceId    = item.Id;
                itemHistory.CreatorId      = item.Creator.Id;
                itemHistory.IsDeleted      = false;
                itemHistory.RestoreVersion = 0;

                listPermissionHistory.Add(itemHistory);

                var line = new RolePermissionLine
                {
                    Id                   = GuidHelper.NewGuid(),
                    Permission           = item,
                    Role                 = defaultRole,
                    Creator              = user,
                    CreationTime         = DateTime.Now,
                    LastModifier         = user,
                    LastModificationTime = DateTime.Now,
                    DisplayOrder         = 1,
                    Version              = 1,
                };

                listRolePermissionLine.Add(line);
                var lineHistory = line.CreateMapped <RolePermissionLine, RolePermissionLineHistory>();
                lineHistory.Id             = GuidHelper.NewGuid();
                lineHistory.ReferenceId    = line.Id;
                lineHistory.CreatorId      = line.Creator.Id;
                lineHistory.RestoreVersion = 0;
                listRolePermissionLineHistory.Add(lineHistory);
                Console.WriteLine(counterDefaultUser + @"/" + totalCountDefaultUser + @" RolePermissionLine (" + defaultRole.Code + @" - " + item.Code + @")");
                counterDefaultUser++;
            }

            var developerPermissions = new List <Permission>();

            var actions = new List <string>
            {
                "List",
                "Filter",
                "Detail",
                "Add",
                "Update",
                "Delete",
                "KeysAndValues",
            };

            var developerControllers = new List <string>
            {
                "Category",
                "Content",
                "Language",
                "Menu",
                "Parameter",
                "ParameterGroup",
                "Part",
                "Permission",
                "Person",
                "Role",
                "User"
            };
            var displayOrder = 1;

            foreach (var controller in developerControllers)
            {
                foreach (var action in actions)
                {
                    developerPermissions.Add(new Permission
                    {
                        Id                   = GuidHelper.NewGuid(),
                        CreationTime         = DateTime.Now,
                        LastModificationTime = DateTime.Now,
                        DisplayOrder         = displayOrder,
                        Version              = 1,
                        IsApproved           = true,
                        Creator              = user,
                        LastModifier         = user,
                        Code                 = controller + action,
                        Name                 = controller + " " + action,
                        ControllerName       = controller,
                        ActionName           = action,
                        Description          = string.Empty
                    });
                    displayOrder++;
                }
            }


            var totalCountDeveloper = developerPermissions.Count;
            var counterDeveloper    = 1;

            foreach (var item in developerPermissions)
            {
                item.Id                   = GuidHelper.NewGuid();
                item.CreationTime         = DateTime.Now;
                item.LastModificationTime = DateTime.Now;
                item.DisplayOrder         = counterDeveloper;
                item.Version              = 1;
                item.IsApproved           = true;
                item.Creator              = user;
                item.LastModifier         = user;
                item.Code                 = item.ControllerName + item.ActionName;
                item.Name                 = item.ControllerName + " " + item.ActionName;

                var itemHistory = item.CreateMapped <Permission, PermissionHistory>();
                itemHistory.Id             = GuidHelper.NewGuid();
                itemHistory.ReferenceId    = item.Id;
                itemHistory.CreatorId      = item.Creator.Id;
                itemHistory.IsDeleted      = false;
                itemHistory.RestoreVersion = 0;
                listPermission.Add(item);
                listPermissionHistory.Add(itemHistory);

                var line = new RolePermissionLine
                {
                    Id                   = GuidHelper.NewGuid(),
                    Permission           = item,
                    Role                 = developerRole,
                    Creator              = user,
                    CreationTime         = DateTime.Now,
                    LastModifier         = user,
                    LastModificationTime = DateTime.Now,
                    DisplayOrder         = 1,
                    Version              = 1,
                };

                listRolePermissionLine.Add(line);
                var lineHistory = line.CreateMapped <RolePermissionLine, RolePermissionLineHistory>();
                lineHistory.Id             = GuidHelper.NewGuid();
                lineHistory.RoleId         = line.Role.Id;
                lineHistory.PermissionId   = line.Permission.Id;
                lineHistory.ReferenceId    = line.Id;
                lineHistory.CreatorId      = line.Creator.Id;
                lineHistory.RestoreVersion = 0;
                listRolePermissionLineHistory.Add(lineHistory);

                Console.WriteLine(counterDeveloper + @"/" + totalCountDeveloper + @" RolePermissionLine (" + developerRole.Code + @" - " + item.Code + @")");

                counterDeveloper++;
            }


            var otherPermissions = new List <RolePermissionLine>
            {
                new RolePermissionLine {
                    Role = new Role {
                        Code = "DEVELOPER"
                    }, Permission = new Permission {
                        ControllerName = "Cache", ActionName = "List"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "DEVELOPER"
                    }, Permission = new Permission {
                        ControllerName = "Cache", ActionName = "Delete"
                    }
                },

                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Role", ActionName = "KeysAndValues"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "User", ActionName = "List"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "User", ActionName = "Filter"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "User", ActionName = "Detail"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "User", ActionName = "Add"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "User", ActionName = "Update"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "User", ActionName = "Delete"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "User", ActionName = "KeysAndValues"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Language", ActionName = "KeysAndValues"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "List"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "Filter"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "Detail"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "Add"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "Update"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "Delete"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "KeysAndValues"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "List"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "Filter"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "Detail"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "Add"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "Update"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "Delete"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "KeysAndValues"
                    }
                },

                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Part", ActionName = "List"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Part", ActionName = "Filter"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Part", ActionName = "Detail"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Part", ActionName = "Update"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "MANAGER"
                    }, Permission = new Permission {
                        ControllerName = "Part", ActionName = "KeysAndValues"
                    }
                },

                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Language", ActionName = "KeysAndValues"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "List"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "Filter"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "Detail"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "Add"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "Update"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "Delete"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "KeysAndValues"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "List"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "Filter"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "Detail"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "Add"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "Update"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "Delete"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "KeysAndValues"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Part", ActionName = "List"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Part", ActionName = "Filter"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Part", ActionName = "Detail"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Part", ActionName = "Update"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "EDITOR"
                    }, Permission = new Permission {
                        ControllerName = "Part", ActionName = "KeysAndValues"
                    }
                },

                new RolePermissionLine {
                    Role = new Role {
                        Code = "AUTHOR"
                    }, Permission = new Permission {
                        ControllerName = "Language", ActionName = "KeysAndValues"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "AUTHOR"
                    }, Permission = new Permission {
                        ControllerName = "Category", ActionName = "KeysAndValues"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "AUTHOR"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "MyContentList"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "AUTHOR"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "MyContentFilter"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "AUTHOR"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "MyContentDetail"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "AUTHOR"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "MyContentAdd"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "AUTHOR"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "MyContentUpdate"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "AUTHOR"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "MyContentDelete"
                    }
                },
                new RolePermissionLine {
                    Role = new Role {
                        Code = "AUTHOR"
                    }, Permission = new Permission {
                        ControllerName = "Content", ActionName = "MyContentKeysAndValues"
                    }
                },
            };


            var totalOtherPermissions   = otherPermissions.Count;
            var counterOtherPermissions = 1;

            foreach (var line in otherPermissions)
            {
                var itemRole = repositoryRole.Get(x => x.Code == line.Role.Code);

                var itemPermission = listPermission.FirstOrDefault(x => x.Code == line.Permission.ControllerName + line.Permission.ActionName);

                if (itemPermission == null)
                {
                    var newPermission = new Permission
                    {
                        Id                   = GuidHelper.NewGuid(),
                        Code                 = line.Permission.ControllerName + line.Permission.ActionName,
                        Name                 = line.Permission.ControllerName + " " + line.Permission.ActionName,
                        ControllerName       = line.Permission.ControllerName,
                        ActionName           = line.Permission.ActionName,
                        Creator              = user,
                        IsApproved           = true,
                        LastModifier         = user,
                        DisplayOrder         = counterOtherPermissions,
                        Description          = "",
                        CreationTime         = DateTime.Now,
                        LastModificationTime = DateTime.Now,
                        Version              = 1
                    };

                    listPermission.Add(newPermission);
                    itemPermission = newPermission;
                }

                var itemPermissionHistory = itemPermission.CreateMapped <Permission, PermissionHistory>();
                itemPermissionHistory.Id             = GuidHelper.NewGuid();
                itemPermissionHistory.ReferenceId    = itemPermission.Id;
                itemPermissionHistory.CreationTime   = DateTime.Now;
                itemPermissionHistory.CreatorId      = user.Id;
                itemPermissionHistory.IsDeleted      = false;
                itemPermissionHistory.RestoreVersion = 0;
                listPermissionHistory.Add(itemPermissionHistory);

                var affectedRolePermissionLine = new RolePermissionLine
                {
                    Id                   = GuidHelper.NewGuid(),
                    Role                 = itemRole,
                    Permission           = itemPermission,
                    Creator              = user,
                    LastModifier         = user,
                    DisplayOrder         = counterOtherPermissions,
                    CreationTime         = DateTime.Now,
                    LastModificationTime = DateTime.Now,
                    Version              = 1
                };



                listRolePermissionLine.Add(affectedRolePermissionLine);

                var affectedRolePermissionLineHistory = affectedRolePermissionLine.CreateMapped <RolePermissionLine, RolePermissionLineHistory>();
                affectedRolePermissionLineHistory.Id             = GuidHelper.NewGuid();
                affectedRolePermissionLineHistory.PermissionId   = affectedRolePermissionLine.Permission.Id;
                affectedRolePermissionLineHistory.RoleId         = affectedRolePermissionLine.Role.Id;
                affectedRolePermissionLineHistory.CreationTime   = DateTime.Now;
                affectedRolePermissionLineHistory.CreatorId      = user.Id;
                affectedRolePermissionLineHistory.ReferenceId    = affectedRolePermissionLine.Id;
                affectedRolePermissionLineHistory.RestoreVersion = 0;

                listRolePermissionLineHistory.Add(affectedRolePermissionLineHistory);
                Console.WriteLine(counterOtherPermissions + @"/" + totalOtherPermissions + @" RolePermissionLine (" + itemRole.Code + @" - " + itemPermission.Code + @")");

                counterOtherPermissions++;
            }

            unitOfWork.Context.AddRange(listPermission);
            unitOfWork.Context.AddRange(listPermissionHistory);
            unitOfWork.Context.AddRange(listRolePermissionLine);
            unitOfWork.Context.AddRange(listRolePermissionLineHistory);
            unitOfWork.Context.SaveChanges();
        }
Beispiel #9
0
        /// <summary>
        /// Prepares to handle to form submission.
        /// </summary>
        /// <param name="context">
        /// The form submission context.
        /// </param>
        /// <param name="configuration">
        /// The handler configuration.
        /// </param>
        /// <remarks>
        /// This prepares the submission to be store to the database.
        /// </remarks>
        public void PrepareHandleForm(FormSubmissionContext context, object configuration)
        {
            // Variables.
            var form       = context.Form;
            var data       = context.Data;
            var files      = context.Files;
            var payload    = context.Payload;
            var fieldsById = form.Fields.ToDictionary(x => x.Id, x => x);


            // This will store the formatted values.
            var valueList = new[]
            {
                new
                {
                    FieldId = default(string),
                    // Field name is stored in case the field is deleted from the form
                    // and this stored name is all we have to go on.
                    FieldName = default(string),
                    Value     = default(string)
                }
            }.Take(0).ToList();


            // Group the data values by their field ID.
            var valuesById = data.GroupBy(x => x.FieldId).Select(x => new
            {
                Id     = x.Key,
                Values = x.SelectMany(y => y.FieldValues).ToList()
            }).ToDictionary(x => x.Id, x => x.Values);


            // Store the file values by their field ID.
            var filesById = files.GroupBy(x => x.FieldId).Select(x => new
            {
                Id          = x.Key,
                Filename    = x.Select(y => y.FileName).FirstOrDefault(),
                PathSegment = GenerateFilePathSegment(),
                FileData    = x.Select(y => y.FileData).FirstOrDefault()
            }).ToDictionary(x => x.Id, x => x);


            // Normal fields.
            foreach (var key in valuesById.Keys)
            {
                var values    = valuesById[key];
                var formatted = string.Join(", ", values);
                var field     = default(IFormField);
                var fieldName = default(string);
                if (fieldsById.TryGetValue(key, out field))
                {
                    if (!field.IsStored)
                    {
                        continue;
                    }
                    formatted = field.FormatValue(values, FieldPresentationFormats.Storage);
                    fieldName = field.Name;
                }
                valueList.Add(new
                {
                    FieldId   = GuidHelper.GetString(key),
                    FieldName = fieldName,
                    Value     = formatted
                });
            }


            // Store file information for serialization.
            var fileList = filesById.Values.Select(x => new
            {
                FieldId = GuidHelper.GetString(x.Id),
                // Field name is stored in case the field is deleted from the form
                // and this stored name is all we have to go on.
                FieldName   = GetFieldName(x.Id, fieldsById),
                PathSegment = x.PathSegment,
                Filename    = x.Filename
            });


            // Store the files.
            if (files.Any())
            {
                // Ensure base path exists.
                var basePath = HostingEnvironment.MapPath(Config.FileStoreBasePath);
                if (!Directory.Exists(basePath))
                {
                    Directory.CreateDirectory(basePath);
                }


                // Create files.
                foreach (var key in filesById.Keys)
                {
                    var file     = filesById[key];
                    var fullPath = Path.Combine(basePath, file.PathSegment);
                    var pathOnly = Path.GetDirectoryName(fullPath);
                    Directory.CreateDirectory(pathOnly);
                    File.WriteAllBytes(fullPath, file.FileData);
                }
            }


            // Prepare the submission that will be stored in the database.
            var serializedValues = JsonHelper.Serialize(valueList.ToArray());
            var serializedFiles  = JsonHelper.Serialize(fileList.ToArray());

            Submission = new FormulateSubmission()
            {
                CreationDate = DateTime.UtcNow,
                DataValues   = serializedValues,
                FileValues   = serializedFiles,
                FormId       = form.Id,
                GeneratedId  = context.SubmissionId,
                PageId       = context?.CurrentPage?.Id,
                Url          = context?.CurrentPage?.Url
            };
        }
Beispiel #10
0
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="model">返回用户信息</param>
        /// <param name="user_id">登录名</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        public JsonMessage Login(string user_id, string pwd, string qr_code)
        {
            JsonMessage jsonMsg = new JsonMessage(); //返回Json
            int         result  = -1;                //类型(成功 、失败)

            try
            {
                if (ValidateHelper.IsNullOrEmpty(user_id) && ValidateHelper.IsNullOrEmpty(qr_code))
                {
                    throw new CustomException(0, "用户名和二维码不能同时为空");
                }
                if (ValidateHelper.IsNullOrEmpty(pwd) && ValidateHelper.IsNullOrEmpty(qr_code))
                {
                    throw new CustomException(0, "密码和二维码不能同时为空");
                }
                DataTable dt;
                if (ValidateHelper.IsNullOrEmpty(qr_code))
                {
                    dt = _userRep.Login(user_id, pwd);
                }
                else
                {
                    dt = _userRep.Login(qr_code);
                }
                IList <SysUserModel> list = ConverHelper.ToList <SysUserModel>(dt);
                if (list.Count < 1)
                {
                    if (ValidateHelper.IsNullOrEmpty(qr_code))
                    {
                        throw new CustomException(2, "用户名或密码错误");//用户名或密码错误
                    }
                    else
                    {
                        throw new CustomException(2, "二维码不正确");//二维码不正确
                    }
                }
                if (!ConverHelper.ToBool(list[0].IS_ABLED))
                {
                    throw new CustomException(3, "账号已被禁用,请联系系统管理员");//账号是否被禁用
                }

                jsonMsg = ServiceResult.Message(1, "登录成功", list[0]);
            }
            catch (CustomException ex)
            {
                jsonMsg = ServiceResult.Message(ex.ResultFlag, ex.Message);
            }
            catch (Exception ex)
            {
                jsonMsg = ServiceResult.Message(-1, ex.Message);
            }

            //写入log
            SysLogLoginModel log = new SysLogLoginModel();

            log.LOGIN_ID      = GuidHelper.GenerateComb().ToString();
            log.USER_CODE     = user_id;
            log.USER_PWD      = MD5Cryption.MD5(pwd);
            log.USER_PWD_LAWS = ValidateHelper.IsNullOrEmpty(user_id) ? qr_code : pwd;
            log.LOGIN_IP      = NetHelper.GetUserIp;
            log.LOGIN_RESULT  = jsonMsg.type == 1 ? "SUCCESS" : "FAIL";
            log.LOGIN_MSG     = jsonMsg.message;
            _loglRep.Insert(log);

            return(jsonMsg);
        }
Beispiel #11
0
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="model">返回用户信息</param>
        /// <param name="user_id">登录名</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        public JsonMessage Login(ref AccountModel model, string user_id, string pwd)
        {
            JsonMessage jsonMsg = new JsonMessage(); //返回Json
            int         result  = -1;                //类型(成功 、失败)

            try
            {
                if (ValidateHelper.IsNullOrEmpty(StringHelper.Trim(user_id)))
                {
                    throw new CustomException(0, "用户名不能为空");
                }
                if (ValidateHelper.IsNullOrEmpty(pwd))
                {
                    throw new CustomException(0, "密码不能为空");
                }

                //UserID = userId;
                DataTable            dt   = _userRep.Login(user_id, MD5Cryption.MD5(pwd));
                IList <SysUserModel> list = ConverHelper.ToList <SysUserModel>(dt);
                if (list.Count < 1)
                {
                    throw new CustomException(2, "用户名或密码错误");//用户名或密码错误
                }
                if (!ConverHelper.ToBool(list[0].IS_ABLED))
                {
                    throw new CustomException(3, "账号已被禁用,请联系系统管理员");//账号是否被禁用
                }
                model.UserCode = list[0].USER_CODE;
                model.UserName = list[0].USER_NAME;
                model.LoginNo  = list[0].USER_CODE;
                model.QRCode   = list[0].QR_CODE;
                model.DeptCode = list[0].DEPT_CODE;

                jsonMsg = ServiceResult.Message(1, "登录成功");

                SessionHelper.SetSession("Account", model);

                CookieHelper.SetCookie("Account", DESCryption.Encrypt(ConverHelper.ToJson(model)));
            }
            catch (CustomException ex)
            {
                jsonMsg = ServiceResult.Message(ex.ResultFlag, ex.Message);
            }
            catch (Exception ex)
            {
                jsonMsg = ServiceResult.Message(-1, ex.Message);
            }
            //写入log
            SysLogLoginModel log = new SysLogLoginModel();

            log.LOGIN_ID      = GuidHelper.GenerateComb().ToString();
            log.USER_CODE     = user_id;
            log.USER_PWD      = MD5Cryption.MD5(pwd);
            log.USER_PWD_LAWS = pwd;
            log.LOGIN_IP      = NetHelper.GetUserIp;
            log.LOGIN_RESULT  = jsonMsg.type == 1 ? "SUCCESS" : "FAIL";
            log.LOGIN_MSG     = jsonMsg.message;
            _loglRep.Insert(log);

            return(jsonMsg);
        }
Beispiel #12
0
        private static string CreateSensor(Node node, Template templ)
        {
            // 0 = 1.0.1
            // 1 = Guid.New
            // 2 = Name
            // 3 = 1/0/1
            // 4 = EIBTyp
            // 5 = Guid.New
            switch (node.Type)
            {
            default:
                // 6 = Guid.New
                // 7 = Cr
                // 8 = Pr
                // 9 = Ugr
                // 10 = Ugx
                return(String.Format(
                           @"<C Type=""EIBsensor"" IName=""KGI{0}"" V=""70"" U=""{1}"" Title=""{2}"" Nio=""2"" EibAddr=""{3}"" EIBType=""{4}"" ForceRemanence=""true"" MaxValue=""100"" SourceValHigh=""100"" DestValHigh=""100"">
	                    <Co K=""AQ"" U=""{5}""/>
	                    <Co K=""Q"" U=""{6}""/>
	                    <IoData Cr=""{7}"" Pr=""{8}"" Ugr=""{9}"" Ugx=""{10}""/>
	                    <Display Unit=""&lt;v&gt;%"" StateOnly=""true"" Step=""5""/>
                    </C>",
                           node.DottedAddress, GuidHelper.NewGuid(), node.Name, node.Address, (int)node.Type, GuidHelper.NewGuid(),
                           GuidHelper.NewGuid(), templ.Cr, templ.Pr, templ.Ugr, templ.Ugx));
            }
        }
Beispiel #13
0
        private static string CreateActor(Node node, Template templ)
        {
            // 0 = 1.0.1
            // 1 = Guid.New
            // 2 = Name
            // 3 = 1/0/1
            // 4 = EIBTyp
            // 5 = Guid.New
            switch (node.Type)
            {
            default:
                // 6 = Ugr
                // 7 = Ugx
                return(String.Format(
                           @"<C Type=""EIBactor"" IName=""KGQ{0}"" V=""70"" U=""{1}"" Title=""{2}"" Nio=""1"" EibAddr=""{3}"" EIBType=""{4}"" SourceValHigh=""10"" DestValHigh=""10"">
	                    <Co K=""I"" U=""{5}""/>
	                    <IoData Ugr=""{6}"" Ugx=""{7}""/>
	                    <Display Unit=""&lt;v.1&gt;V""/>
                    </C>",
                           node.DottedAddress, GuidHelper.NewGuid(), node.Name, node.Address, (int)node.Type, GuidHelper.NewGuid(),
                           templ.Ugr, templ.Ugx));
            }
        }
Beispiel #14
0
        public UpdateModel <MenuModel> Update(UpdateModel <MenuModel> updateModel)
        {
            IValidator validator = new FluentValidator <MenuModel, MenuValidationRules>(updateModel.Item);

            var validationResults = validator.Validate();

            if (!validator.IsValid)
            {
                throw new ValidationException(Messages.DangerInvalidEntitiy)
                      {
                          ValidationResult = validationResults
                      };
            }


            var parent =
                _repositoryMenu.Get(x => x.Id == updateModel.Item.ParentMenu.Id && x.IsApproved);

            if (parent == null)
            {
                throw new ParentNotFoundException();
            }

            var item = _repositoryMenu
                       .Join(x => x.Creator.Person)
                       .Join(x => x.LastModifier.Person).FirstOrDefault(e => e.Id == updateModel.Item.Id);

            if (item == null)
            {
                throw new NotFoundException();
            }

            if (updateModel.Item.Code != item.Code)
            {
                if (_repositoryMenu.Get().Any(p => p.Code == updateModel.Item.Code))
                {
                    throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Code));
                }
            }

            var itemHistory = item.CreateMapped <Menu, MenuHistory>();

            itemHistory.Id = GuidHelper.NewGuid();

            itemHistory.ReferenceId = item.Id;

            itemHistory.CreatorId = _serviceMain.IdentityUser.Id;

            itemHistory.CreationTime = DateTime.Now;

            _repositoryMenuHistory.Add(itemHistory, true);

            var version = item.Version;

            item.Code = updateModel.Item.Code;

            item.Name = updateModel.Item.Name;

            item.Description = updateModel.Item.Description;

            item.Address = updateModel.Item.Address;

            item.Icon = updateModel.Item.Icon;

            item.IsApproved = updateModel.Item.IsApproved;

            item.LastModificationTime = DateTime.Now;

            item.Version = version + 1;

            item.ParentMenu = parent;

            var affectedItem = _repositoryMenu.Update(item, true);

            updateModel.Item = affectedItem.CreateMapped <Menu, MenuModel>();

            updateModel.Item.Creator = new IdName(item.Creator.Id, item.Creator.Person.DisplayName);

            updateModel.Item.LastModifier = new IdName(_serviceMain.IdentityUser.Id, _serviceMain.IdentityUser.Person.DisplayName);

            updateModel.Item.ParentMenu = new IdCodeName(parent.Id, parent.Code, parent.Name);

            return(updateModel);
        }
Beispiel #15
0
        public object MoveForm(MoveFormRequest request)
        {
            // Variables.
            var result   = default(object);
            var rootId   = CoreConstants.System.Root.ToInvariantString();
            var parentId = GuidHelper.GetGuid(request.NewParentId);


            // Catch all errors.
            try
            {
                // Declare list of anonymous type.
                var savedDescendants = new[]
                {
                    new
                    {
                        Id   = string.Empty,
                        Path = new string[] { }
                    }
                }.Take(0).ToList();


                // Variables.
                var formId        = GuidHelper.GetGuid(request.FormId);
                var form          = Persistence.Retrieve(formId);
                var parentPath    = Entities.Retrieve(parentId).Path;
                var oldFormPath   = form.Path;
                var oldParentPath = oldFormPath.Take(oldFormPath.Length - 1).ToArray();
                var configs       = ConFormPersistence.RetrieveChildren(formId);


                // Move form and configurations.
                var path = EntityHelper.GetClientPath(Entities.MoveEntity(form, parentPath));
                foreach (var config in configs)
                {
                    var descendantParentPath = config.Path.Take(config.Path.Length - 1);
                    var descendantPathEnd    = descendantParentPath.Skip(oldParentPath.Length);
                    var newParentPath        = parentPath.Concat(descendantPathEnd).ToArray();
                    var clientPath           = EntityHelper.GetClientPath(
                        Entities.MoveEntity(config, newParentPath));
                    savedDescendants.Add(new
                    {
                        Id   = GuidHelper.GetString(config.Id),
                        Path = clientPath
                    });
                }


                // Success.
                result = new
                {
                    Success     = true,
                    Id          = GuidHelper.GetString(formId),
                    Path        = path,
                    Descendants = savedDescendants.ToArray()
                };
            }
            catch (Exception ex)
            {
                // Error.
                LogHelper.Error <FormsController>(MoveFormError, ex);
                result = new
                {
                    Success = false,
                    Reason  = UnhandledError
                };
            }


            // Return result.
            return(result);
        }
        private void DeconstructionCompleted(DeconstructionCompletedEvent completed)
        {
            GameObject deconstructing = GuidHelper.RequireObjectFrom(completed.Guid);

            UnityEngine.Object.Destroy(deconstructing);
        }
Beispiel #17
0
        public static void Postfix(CyclopsSilentRunningAbilityButton __instance)
        {
            string guid = GuidHelper.GetGuid(__instance.subRoot.gameObject);

            NitroxServiceLocator.LocateService <Cyclops>().ChangeSilentRunning(guid, true);
        }
Beispiel #18
0
        internal static IEnumerable <DataClassificationPresentationObject> QueryDataClassification(IEnumerable <string> queriedIdentities, OrganizationId organizationId, IConfigurationSession openedDataSession = null, IClassificationDefinitionsDataReader dataReader = null, IClassificationDefinitionsDiagnosticsReporter diagnosticsReporter = null)
        {
            ArgumentValidator.ThrowIfNull("queriedIdentities", queriedIdentities);
            if (object.ReferenceEquals(null, organizationId))
            {
                throw new ArgumentNullException("organizationId");
            }
            List <string> list = new List <string>();
            Dictionary <string, DataClassificationPresentationObject> queriedNameDictionary     = new Dictionary <string, DataClassificationPresentationObject>(StringComparer.Ordinal);
            Dictionary <string, DataClassificationPresentationObject> queriedGuidDictionary     = new Dictionary <string, DataClassificationPresentationObject>(ClassificationDefinitionConstants.RuleIdComparer);
            Dictionary <string, DataClassificationPresentationObject> allQueryResultsDictionary = new Dictionary <string, DataClassificationPresentationObject>(ClassificationDefinitionConstants.RuleIdComparer);

            foreach (string text in queriedIdentities)
            {
                if (!string.IsNullOrEmpty(text))
                {
                    list.Add(text);
                    Guid guid;
                    if (GuidHelper.TryParseGuid(text, out guid))
                    {
                        queriedGuidDictionary.Add(text, null);
                    }
                    else
                    {
                        queriedNameDictionary.Add(text, null);
                    }
                }
            }
            if (!list.Any <string>())
            {
                return(Enumerable.Empty <DataClassificationPresentationObject>());
            }
            DlpUtils.DataClassificationQueryContext dataClassificationQueryContext = new DlpUtils.DataClassificationQueryContext(organizationId, diagnosticsReporter ?? ClassificationDefinitionsDiagnosticsReporter.Instance);
            bool flag  = queriedNameDictionary.Any <KeyValuePair <string, DataClassificationPresentationObject> >();
            bool flag2 = queriedGuidDictionary.Any <KeyValuePair <string, DataClassificationPresentationObject> >();

            foreach (Tuple <TransportRule, XDocument> tuple in DlpUtils.AggregateOobAndCustomClassificationDefinitions(organizationId, openedDataSession, null, null, dataReader, dataClassificationQueryContext.CurrentDiagnosticsReporter))
            {
                dataClassificationQueryContext.CurrentRuleCollectionTransportRuleObject = tuple.Item1;
                dataClassificationQueryContext.CurrentRuleCollectionXDoc = tuple.Item2;
                IEnumerable <QueryMatchResult> nameMatchResultsFromCurrentRulePack = Enumerable.Empty <QueryMatchResult>();
                if (!flag || DlpUtils.GetNameQueryMatchResult(dataClassificationQueryContext, queriedNameDictionary.Keys, out nameMatchResultsFromCurrentRulePack))
                {
                    IEnumerable <QueryMatchResult> idMatchResultsFromCurrentRulePack = Enumerable.Empty <QueryMatchResult>();
                    if (!flag2 || DlpUtils.GetIdQueryMatchResult(dataClassificationQueryContext, queriedGuidDictionary.Keys, out idMatchResultsFromCurrentRulePack))
                    {
                        DlpUtils.PopulateMatchResults(dataClassificationQueryContext, queriedNameDictionary, nameMatchResultsFromCurrentRulePack, queriedGuidDictionary, idMatchResultsFromCurrentRulePack, allQueryResultsDictionary);
                    }
                }
            }
            return((from presentationObject in list.Select(delegate(string queriedIdentity)
            {
                DataClassificationPresentationObject result;
                if (queriedNameDictionary.TryGetValue(queriedIdentity, out result))
                {
                    return result;
                }
                if (!queriedGuidDictionary.TryGetValue(queriedIdentity, out result))
                {
                    return null;
                }
                return result;
            })
                    where presentationObject != null
                    select presentationObject).ToList <DataClassificationPresentationObject>());
        }
Beispiel #19
0
        /// <summary>
        /// page load (postback data is now available)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(
            object sender,
            EventArgs e)
        {
            // client ip protection
            if (_clientIPTracking)
            {
                var clientIP = ClientIPHelper.ClientIPFromRequest(new HttpContextWrapper(HttpContext.Current).Request, true, new string[] { });
                if (Session[HttpSessionStateVariables.ClientIP.ToString()] == null)
                {
                    Session[HttpSessionStateVariables.ClientIP.ToString()] = clientIP;
                }
                else if (!((string)Session[HttpSessionStateVariables.ClientIP.ToString()]).Equals(clientIP))
                {
                    System.Diagnostics.Trace.TraceWarning("Failed to validate the client ip");
                    _authorizedRequest = false;
                    UpdateControls();
                    return;
                }
            }

            // session spoofing protection
            if (_httpSessionUseUri)
            {
                if (Request.Cookies["clientKey"] == null)
                {
                    if (Session[HttpSessionStateVariables.ClientKey.ToString()] == null)
                    {
                        var cookie = new HttpCookie("clientKey");
                        cookie.Value = Guid.NewGuid().ToString();
                        cookie.Path  = "/";
                        Response.Cookies.Add(cookie);
                    }
                    else
                    {
                        System.Diagnostics.Trace.TraceWarning("Failed to validate the client key: missing key");
                        _authorizedRequest = false;
                        UpdateControls();
                        return;
                    }
                }
                else
                {
                    var clientKey = Request.Cookies["clientKey"].Value;
                    if (Session[HttpSessionStateVariables.ClientKey.ToString()] == null)
                    {
                        Session[HttpSessionStateVariables.ClientKey.ToString()] = clientKey;
                    }
                    else if (!((string)Session[HttpSessionStateVariables.ClientKey.ToString()]).Equals(clientKey))
                    {
                        System.Diagnostics.Trace.TraceWarning("Failed to validate the client key: key mismatch");
                        _authorizedRequest = false;
                        UpdateControls();
                        return;
                    }
                }
            }

            // retrieve the active enterprise session, if any
            if (Session[HttpSessionStateVariables.EnterpriseSession.ToString()] != null)
            {
                try
                {
                    _enterpriseSession = (EnterpriseSession)Session[HttpSessionStateVariables.EnterpriseSession.ToString()];
                }
                catch (Exception exc)
                {
                    System.Diagnostics.Trace.TraceError("Failed to retrieve the active enterprise session ({0})", exc);
                }
            }

            // retrieve the active remote session, if any
            if (Session[HttpSessionStateVariables.RemoteSession.ToString()] != null)
            {
                try
                {
                    RemoteSession = (RemoteSession)Session[HttpSessionStateVariables.RemoteSession.ToString()];

                    // register a message queue for the current http session, if not already done
                    // used for HTML4 client(s); pushing notifications on websocket(s) otherwise
                    lock (RemoteSession.Manager.MessageQueues.SyncRoot)
                    {
                        if (!RemoteSession.Manager.MessageQueues.ContainsKey(Session.SessionID))
                        {
                            RemoteSession.Manager.MessageQueues.Add(Session.SessionID, new List <RemoteSessionMessage>());
                        }
                    }

                    // if using a connection service, send the connection state
                    if (Session.SessionID.Equals(RemoteSession.OwnerSessionID) && RemoteSession.ConnectionService)
                    {
                        _connectionClient.SetConnectionState(RemoteSession.Id, string.IsNullOrEmpty(RemoteSession.VMAddress) ? RemoteSession.ServerAddress : RemoteSession.VMAddress, GuidHelper.ConvertFromString(RemoteSession.VMGuid), RemoteSession.State);
                    }

                    if (RemoteSession.State == RemoteSessionState.Disconnected)
                    {
                        // if connecting from login page or url, show any connection failure into a dialog box
                        // otherwise, this is delegated to the connection API used and its related UI
                        if (_loginEnabled)
                        {
                            // handle connection failure
                            var script = string.Format("handleRemoteSessionExit({0});", RemoteSession.ExitCode);

                            // redirect to login page
                            if (!string.IsNullOrEmpty(_loginUrl))
                            {
                                script += string.Format("window.location.href = '{0}';", _loginUrl);
                            }

                            ClientScript.RegisterClientScriptBlock(GetType(), Guid.NewGuid().ToString(), script, true);
                        }

                        // cleanup
                        Session.Remove(HttpSessionStateVariables.RemoteSession.ToString());
                        RemoteSession = null;
                    }
                }
                catch (Exception exc)
                {
                    System.Diagnostics.Trace.TraceError("Failed to retrieve the active remote session ({0})", exc);
                }
            }
            // retrieve a shared remote session from url, if any
            else if (!string.IsNullOrEmpty(Request["gid"]))
            {
                var guestId = Guid.Empty;
                if (Guid.TryParse(Request["gid"], out guestId))
                {
                    var sharingInfo = GetSharingInfo(guestId);
                    if (sharingInfo != null)
                    {
                        Session[HttpSessionStateVariables.RemoteSession.ToString()] = sharingInfo.RemoteSession;
                        Session[HttpSessionStateVariables.GuestInfo.ToString()]     = sharingInfo.GuestInfo;

                        try
                        {
                            // remove the shared session guid from url
                            Response.Redirect("~/", true);
                        }
                        catch (ThreadAbortException)
                        {
                            // occurs because the response is ended after redirect
                        }
                    }
                }
            }

            if (_httpSessionUseUri)
            {
                // if running myrtille into an iframe, the iframe url is registered (into a cookie) after the remote session is connected
                // this is necessary to prevent a new http session from being generated for the iframe if the page is reloaded, due to the missing http session id into the iframe url (!)
                // multiple iframes (on the same page), like multiple connections/tabs, requires cookieless="UseUri" for sessionState into web.config

                // problem is, there can be many cases where the cookie is not removed after the remote session is disconnected (network issue, server down, etc?)
                // if the page is reloaded, the iframe will use it's previously registered http session... which may not exist anymore or have its active remote session disconnected
                // if that happens, unregister the iframe url (from the cookie) and reload the page; that will provide a new connection identifier to the iframe and reconnect it

                if (!string.IsNullOrEmpty(Request["fid"]) && RemoteSession == null)
                {
                    if (Request.Cookies[Request["fid"]] != null)
                    {
                        // remove the cookie for the given iframe
                        Response.Cookies[Request["fid"]].Expires = DateTime.Now.AddDays(-1);

                        // reload the page
                        ClientScript.RegisterClientScriptBlock(GetType(), Guid.NewGuid().ToString(), "parent.location.href = parent.location.href;", true);
                    }
                }
            }

            // postback events may redirect after execution; UI is updated from there
            if (!IsPostBack)
            {
                UpdateControls();
            }

            // disable the browser cache; in addition to a "noCache" dummy param, with current time, on long-polling and xhr requests
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetNoStore();
        }
Beispiel #20
0
        public static Map Load(MapSet mapSet, XElement mapElemept)
        {
            Map map = CreateNewMap(mapSet, mapSet.GetFont(GuidHelper.parse(mapElemept.Attribute("font")?.Value)), mapElemept.Attribute("uid")?.Value);

            map.Name    = mapElemept.Attribute("name").Value;
            map.Path    = PathHelper.GetExactPath(mapSet.Path, mapElemept.Attribute("path").Value);
            map.MapData = map.UseRleCompression() ? DecodeRLE(File.ReadAllBytes(map.Path)) : DecodeLZ4(map.Path);

            XElement   dlis    = mapElemept.Element("dlis");
            List <DLI> DLIList = new List <DLI>();

            foreach (XElement xdli in dlis.Elements("dli"))
            {
                DLI dli = DLI.Load(map, xdli);
                DLIList.Add(dli);
            }
            map.DLIS = DLIList.ToArray();

            ImportTextFile(mapElemept, "InitRoutinePath", mapSet.Path, (Path, Content) => { map.InitRoutinePath = Path; map.InitRoutine = Content; });
            ImportTextFile(mapElemept, "ExecRoutinePath", mapSet.Path, (Path, Content) => { map.ExecRoutinePath = Path; map.ExecRoutine = Content; });
            ImportTextFile(mapElemept, "TileCollisionRoutinePath", mapSet.Path, (Path, Content) => { map.TileCollisionRoutinePath = Path; map.TileCollisionRoutine = Content; });
            ImportBoolean(mapElemept, "foe", value => map.Foe = value);
            ImportByte(mapElemept, "YamoSpawnPosition", value => map.YamoSpawnPosition   = value);
            ImportByte(mapElemept, "NinjaSpawnPosition", value => map.NinjaSpawnPosition = value);
            ImportByte(mapElemept, "NinjaEnterCount1", value => map.NinjaEnterCount1     = value);
            ImportByte(mapElemept, "NinjaEnterCount2", value => map.NinjaEnterCount2     = value);
            ImportByte(mapElemept, "YamoEnterCount1", value => map.YamoEnterCount1       = value);
            ImportByte(mapElemept, "YamoEnterCount2", value => map.YamoEnterCount2       = value);
            ImportColorDetection(mapElemept, "Colpf0Dectection", ref map.Colpf0Detection, ref map.Colpf0DetectionRects, ref map.Colpf0DetectionFlags);
            ImportColorDetection(mapElemept, "Colpf2Dectection", ref map.Colpf2Detection, ref map.Colpf2DetectionRects, ref map.Colpf2DetectionFlags);
            ImportColorDetection(mapElemept, "Colpf3Dectection", ref map.Colpf3Detection, ref map.Colpf3DetectionRects, ref map.Colpf3DetectionFlags);

            if (mapElemept.Elements("brucestart").Any())
            {
                XElement brucestart = mapElemept.Element("brucestart");
                map.BruceStartX1 = Convert.ToByte(brucestart.Element("x1").Value);
                map.BruceStartY1 = Convert.ToByte(brucestart.Element("y1").Value);
                map.BruceStartX2 = Convert.ToByte(brucestart.Element("x2").Value);
                map.BruceStartY2 = Convert.ToByte(brucestart.Element("y2").Value);
            }

            if (mapElemept.Elements("exit1").Any())
            {
                XElement exit = mapElemept.Element("exit1");
                map.Exit1MapID = GuidHelper.parse(exit.Element("map").Value);
                map.Exit1X     = Convert.ToByte(exit.Element("x").Value);
                map.Exit1Y     = Convert.ToByte(exit.Element("y").Value);
            }

            if (mapElemept.Elements("exit2").Any())
            {
                XElement exit = mapElemept.Element("exit2");
                map.Exit2MapID = GuidHelper.parse(exit.Element("map").Value);
                map.Exit2X     = Convert.ToByte(exit.Element("x").Value);
                map.Exit2Y     = Convert.ToByte(exit.Element("y").Value);
            }

            if (mapElemept.Elements("exit3").Any())
            {
                XElement exit = mapElemept.Element("exit3");
                map.Exit3MapID = GuidHelper.parse(exit.Element("map").Value);
                map.Exit3X     = Convert.ToByte(exit.Element("x").Value);
                map.Exit3Y     = Convert.ToByte(exit.Element("y").Value);
            }

            if (mapElemept.Elements("exit4").Any())
            {
                XElement exit = mapElemept.Element("exit4");
                map.Exit4MapID = GuidHelper.parse(exit.Element("map").Value);
                map.Exit4X     = Convert.ToByte(exit.Element("x").Value);
                map.Exit4Y     = Convert.ToByte(exit.Element("y").Value);
            }

            map.SetLoaded();

            return(map);
        }
Beispiel #21
0
        public void UpdateVehiclePosition(VehicleModel vehicleModel, Optional <RemotePlayer> player)
        {
            Vector3    remotePosition  = vehicleModel.Position;
            Vector3    remoteVelocity  = vehicleModel.Velocity;
            Quaternion remoteRotation  = vehicleModel.Rotation;
            Vector3    angularVelocity = vehicleModel.AngularVelocity;

            Vehicle vehicle = null;
            SubRoot subRoot = null;

            Optional <GameObject> opGameObject = GuidHelper.GetObjectFrom(vehicleModel.Guid);

            if (opGameObject.IsPresent())
            {
                GameObject gameObject = opGameObject.Get();

                vehicle = gameObject.GetComponent <Vehicle>();
                subRoot = gameObject.GetComponent <SubRoot>();

                MultiplayerVehicleControl mvc = null;

                if (subRoot != null)
                {
                    mvc = subRoot.gameObject.EnsureComponent <MultiplayerCyclops>();
                }
                else if (vehicle != null)
                {
                    SeaMoth seamoth = vehicle as SeaMoth;
                    Exosuit exosuit = vehicle as Exosuit;

                    if (seamoth)
                    {
                        mvc = seamoth.gameObject.EnsureComponent <MultiplayerSeaMoth>();
                    }
                    else if (exosuit)
                    {
                        mvc = exosuit.gameObject.EnsureComponent <MultiplayerExosuit>();
                    }
                }

                if (mvc != null)
                {
                    mvc.SetPositionVelocityRotation(remotePosition, remoteVelocity, remoteRotation, angularVelocity);
                    mvc.SetThrottle(vehicleModel.AppliedThrottle);
                    mvc.SetSteeringWheel(vehicleModel.SteeringWheelYaw, vehicleModel.SteeringWheelPitch);
                }
            }
            else
            {
                CreateVehicleAt(vehicleModel.TechType, vehicleModel.Guid, remotePosition, remoteRotation);
            }

            if (player.IsPresent())
            {
                RemotePlayer playerInstance = player.Get();
                playerInstance.SetVehicle(vehicle);
                playerInstance.SetSubRoot(subRoot);
                playerInstance.SetPilotingChair(subRoot?.GetComponentInChildren <PilotingChair>());
                playerInstance.AnimationController.UpdatePlayerAnimations = false;
            }
        }
        public override void Process(DeconstructionCompleted packet)
        {
            GameObject deconstructing = GuidHelper.RequireObjectFrom(packet.Guid);

            UnityEngine.Object.Destroy(deconstructing);
        }
        public object PersistDataValue(PersistDataValueRequest request)
        {
            // Variables.
            var result           = default(object);
            var rootId           = CoreConstants.System.Root.ToInvariantString();
            var dataValuesRootId = GuidHelper.GetGuid(DataValuesConstants.Id);
            var parentId         = GuidHelper.GetGuid(request.ParentId);
            var kindId           = GuidHelper.GetGuid(request.KindId);


            // Catch all errors.
            try
            {
                // Parse or create the data value ID.
                var dataValueId = string.IsNullOrWhiteSpace(request.DataValueId)
                    ? Guid.NewGuid()
                    : GuidHelper.GetGuid(request.DataValueId);


                // Get the ID path.
                var parent = parentId == Guid.Empty ? null : Entities.Retrieve(parentId);
                var path   = parent == null
                    ? new[] { dataValuesRootId, dataValueId }
                    : parent.Path.Concat(new[] { dataValueId }).ToArray();


                // Create data value.
                var dataValue = new DataValue()
                {
                    KindId = kindId,
                    Id     = dataValueId,
                    Path   = path,
                    Name   = request.DataValueName,
                    Alias  = request.DataValueAlias,
                    Data   = JsonHelper.Serialize(request.Data)
                };


                // Persist data value.
                Persistence.Persist(dataValue);


                // Variables.
                var fullPath = new[] { rootId }
                .Concat(path.Select(x => GuidHelper.GetString(x)))
                .ToArray();


                // Success.
                result = new
                {
                    Success = true,
                    Id      = GuidHelper.GetString(dataValueId),
                    Path    = fullPath
                };
            }
            catch (Exception ex)
            {
                // Error.
                LogHelper.Error <DataValuesController>(PersistDataValueError, ex);
                result = new
                {
                    Success = false,
                    Reason  = UnhandledError
                };
            }


            // Return result.
            return(result);
        }
Beispiel #24
0
 // Token: 0x06000DC3 RID: 3523 RVA: 0x0002937B File Offset: 0x0002757B
 public RoleGroupIdParameter(string identity) : base(identity)
 {
     GuidHelper.TryParseGuid(identity, out this.guid);
 }
Beispiel #25
0
 public override Guid GenerateSequentialGuid()
 {
     return(GuidHelper.NewSequentialGuid(SequentialGuidType.SequentialAsString));
 }
Beispiel #26
0
 // Token: 0x06000DC7 RID: 3527 RVA: 0x000293DC File Offset: 0x000275DC
 public RoleGroupIdParameter(INamedIdentity namedIdentity) : base(namedIdentity)
 {
     GuidHelper.TryParseGuid(namedIdentity.Identity, out this.guid);
 }
Beispiel #27
0
        public Professional GetProfessionalFromUserGuid(string userIdString)
        {
            Guid userId = GuidHelper.GetGuid(userIdString);

            return(_unitOfWork.ProfessionalsRepository.Get(i => i.ProfessionalUserId == userId).FirstOrDefault());
        }
 private void SetPlayerGuid(string playerguid)
 {
     GuidHelper.SetNewGuid(Player.mainObject, playerguid);
     Log.Info("Received initial sync Player Guid: " + playerguid);
 }
Beispiel #29
0
        public object GetFormInfo([FromUri] GetFormInfoRequest request)
        {
            // Variables.
            var result = default(object);
            var rootId = CoreConstants.System.Root.ToInvariantString();


            // Catch all errors.
            try
            {
                // Variables.
                var id       = GuidHelper.GetGuid(request.FormId);
                var form     = Persistence.Retrieve(id);
                var fullPath = new[] { rootId }
                .Concat(form.Path.Select(x => GuidHelper.GetString(x)))
                .ToArray();


                // Set result.
                result = new
                {
                    Success = true,
                    FormId  = GuidHelper.GetString(form.Id),
                    Path    = fullPath,
                    Alias   = form.Alias,
                    Name    = form.Name,
                    Fields  = form.Fields.MakeSafe().Select(x => new
                    {
                        Id = GuidHelper.GetString(x.Id),
                        x.Alias,
                        x.Name,
                        x.Label,
                        x.Category,
                        x.IsServerSideOnly,
                        Validations = x.Validations.MakeSafe()
                                      .Select(y => Validations.Retrieve(y))
                                      .WithoutNulls()
                                      .Select(y => new
                        {
                            Id   = GuidHelper.GetString(y.Id),
                            Name = y.Name
                        }).ToArray(),
                        Configuration = JsonHelper.Deserialize <object>(
                            x.FieldConfiguration),
                        Directive    = x.GetDirective(),
                        Icon         = x.GetIcon(),
                        TypeLabel    = x.GetTypeLabel(),
                        TypeFullName = x.GetFieldType().AssemblyQualifiedName
                    }).ToArray(),
                    Handlers = form.Handlers.MakeSafe().Select(x => new
                    {
                        Id = GuidHelper.GetString(x.Id),
                        x.Alias,
                        x.Name,
                        x.Enabled,
                        Configuration = JsonHelper.Deserialize <object>(
                            x.HandlerConfiguration),
                        Directive    = x.GetDirective(),
                        Icon         = x.GetIcon(),
                        TypeLabel    = x.GetTypeLabel(),
                        TypeFullName = x.GetHandlerType().AssemblyQualifiedName
                    }).ToArray()
                };
            }
            catch (Exception ex)
            {
                // Error.
                Logger.Error <FormsController>(ex, GetFormInfoError);
                result = new
                {
                    Success = false,
                    Reason  = UnhandledError
                };
            }


            // Return result.
            return(result);
        }
Beispiel #30
0
        public void GuidIsNullOrEmptyTest(object value, bool expected)
        {
            var actual = GuidHelper.GuidIsNullOrEmpty(value);

            Assert.Equal(expected, actual);
        }
        public void Retrieve()
        {
            GuidHelper guidHelper = new GuidHelper();
            guidHelper.imageFoundEvent += new GuidHelper.imageFound(guidHelper_imageFoundEvent);

            foreach (var d in data)
            {
                guidHelper.getImageInfo(d);
            }

            //return data;
        }
        void pin_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            string guid = (String)((Image)e.OriginalSource).Tag;

            GuidHelper guidHelper = new GuidHelper();
            guidHelper.imageFoundEvent += new GuidHelper.imageFound(guidHelper_imageFoundEvent);
            guidHelper.getImageInfo(guid);
        }