예제 #1
0
		public MachineStationsVM(MachineVM machine, AccessType access)
			: base(access)
		{
            UnitOfWork = new SoheilEdmContext();
			CurrentMachine = machine;
            MachineDataService = new MachineDataService(UnitOfWork);
			MachineDataService.StationAdded += OnStationAdded;
			MachineDataService.StationRemoved += OnStationRemoved;
            StationDataService = new StationDataService(UnitOfWork);

			var selectedVms = new ObservableCollection<StationMachineVM>();
			foreach (var stationMachine in MachineDataService.GetStations(machine.Id))
			{
				selectedVms.Add(new StationMachineVM(stationMachine, Access, StationMachineDataService, RelationDirection.Reverse));
			}
			SelectedItems = new ListCollectionView(selectedVms);

            var allVms = new ObservableCollection<StationVM>();
            foreach (var station in StationDataService.GetActives(SoheilEntityType.Machines, CurrentMachine.Id))
            {
                allVms.Add(new StationVM(station, Access, StationDataService));
            }
            AllItems = new ListCollectionView(allVms);

			IncludeCommand = new Command(Include, CanInclude);
			ExcludeCommand = new Command(Exclude, CanExclude);
		}
예제 #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ProductVM"/> class from the model.
        /// </summary>
        /// <param name="entity">The model.</param>
        /// <param name="access"></param>
        public PositionVM(Position entity, AccessType access, PositionDataService dataService)
            : base(access)
        {
            InitializeData(dataService);
            _model = entity;

        }
예제 #3
0
 internal LockTimeoutException(ObjectName tableName, AccessType accessType, int timeout)
     : base(SystemErrorCodes.LockTimeout, FormatMessage(tableName, accessType, timeout))
 {
     TableName = tableName;
     AccessType = accessType;
     Timeout = timeout;
 }
        public FishboneNodeActionPlansVM(FishboneNodeVM defection, AccessType access)
            : base(access)
        {
            UnitOfWork = new SoheilEdmContext();
            CurrentFishboneNode = defection;
            FishboneNodeDataService = new FishboneNodeDataService(UnitOfWork);
            FishboneNodeDataService.ActionPlanAdded += OnActionPlanAdded;
            FishboneNodeDataService.ActionPlanRemoved += OnActionPlanRemoved;
            ActionPlanDataService = new ActionPlanDataService(UnitOfWork);

            var selectedVms = new ObservableCollection<ActionPlanFishboneVM>();
            foreach (var productFishboneNode in FishboneNodeDataService.GetActionPlans(defection.Id))
            {
                selectedVms.Add(new ActionPlanFishboneVM(productFishboneNode, Access, RelationDirection.Reverse));
            }
            SelectedItems = new ListCollectionView(selectedVms);

            var allVms = new ObservableCollection<ActionPlanVM>();
            foreach (var actionPlan in ActionPlanDataService.GetActives())
            {
                allVms.Add(new ActionPlanVM(actionPlan, Access, ActionPlanDataService));
            }
            AllItems = new ListCollectionView(allVms);

            IncludeCommand = new Command(Include, CanInclude);
            ExcludeCommand = new Command(Exclude, CanExclude);
        }
예제 #5
0
 internal LockEvent(LockEventType eventType, IEnumerable<ObjectName> references, LockingMode mode, AccessType accessType)
 {
     EventType = eventType;
     References = references;
     Mode = mode;
     AccessType = accessType;
 }
예제 #6
0
        protected override sealed void DoAccess(uint pageid, byte[] resultOrData, AccessType type)
        {
            QueueNode<IFrame> node;
            IFrame frame;

            if (map.TryGetValue(pageid, out node))
            {
                node = OnHit(node, type);
                frame = node.ListNode.Value;
            }
            else
            {
                frame = CreateFrame(pageid, pool.AllocSlot());

                if (type == AccessType.Read)
                    dev.Read(pageid, pool[frame.DataSlotId]);

                node = OnMiss(frame, type);
            }

            map[pageid] = node;

            if (type == AccessType.Read)
            {
                pool[frame.DataSlotId].CopyTo(resultOrData, 0);
            }
            else
            {
                resultOrData.CopyTo(pool[frame.DataSlotId], 0);
                frame.Dirty = true;
            }
        }
예제 #7
0
        public ProductDefectionsVM(ProductVM product, AccessType access):base(access)
        {
            UnitOfWork = new SoheilEdmContext();
            CurrentProduct = product;
            ProductDataService = new ProductDataService(UnitOfWork);
            ProductDataService.DefectionAdded += OnDefectionAdded;
            ProductDataService.DefectionRemoved += OnDefectionRemoved;
            DefectionDataService = new DefectionDataService(UnitOfWork);
            ProductDefectionDataService = new ProductDefectionDataService(UnitOfWork);

            var selectedVms = new ObservableCollection<ProductDefectionVM>();
            foreach (var productDefection in ProductDataService.GetDefections(product.Id))
            {
                selectedVms.Add(new ProductDefectionVM(productDefection, Access, ProductDefectionDataService, RelationDirection.Straight));
            }
            SelectedItems = new ListCollectionView(selectedVms);

            var allVms = new ObservableCollection<DefectionVM>();
            foreach (var defection in DefectionDataService.GetActives(SoheilEntityType.Products, CurrentProduct.Id))
            {
                allVms.Add(new DefectionVM(defection, Access, DefectionDataService));
            }
            AllItems = new ListCollectionView(allVms);

            IncludeCommand = new Command(Include, CanInclude);
            ExcludeCommand = new Command(Exclude, CanExclude);
            IncludeRangeCommand = new Command(IncludeRange, CanIncludeRange);
            ExcludeRangeCommand = new Command(ExcludeRange, CanExcludeRange);
        }
예제 #8
0
        public OperatorActivitiesVM(OperatorVM opr, AccessType access) : base(access)
        {
            UnitOfWork = new SoheilEdmContext();
            CurrentOperator = opr;
            OperatorDataService = new OperatorDataService(UnitOfWork);
            OperatorDataService.ActivityAdded += OnActivityAdded;
            OperatorDataService.ActivityRemoved += OnActivityRemoved;
            ActivityDataService = new ActivityDataService(UnitOfWork);
            ActivityOperatorDataService = new ActivitySkillDataService(UnitOfWork);
            ActivityGroupDataService = new ActivityGroupDataService(UnitOfWork);

            var selectedVms = new ObservableCollection<ActivityOperatorVM>();
            foreach (var generalActivitySkill in OperatorDataService.GetActivities(opr.Id))
            {
                selectedVms.Add(new ActivityOperatorVM(generalActivitySkill, Access, ActivityOperatorDataService, RelationDirection.Reverse));
            }
            SelectedItems = new ListCollectionView(selectedVms);

            var allVms = new ObservableCollection<ActivityVM>();
            foreach (var activity in ActivityDataService.GetActives()
				.Where(activity => !selectedVms.Any(activityOperator => activityOperator.ActivityId == activity.Id)))
            {
                allVms.Add(new ActivityVM(activity, Access, ActivityDataService, ActivityGroupDataService));
            }
            AllItems = new ListCollectionView(allVms);

            IncludeCommand = new Command(Include, CanInclude);
            ExcludeCommand = new Command(Exclude, CanExclude);
            
        }
예제 #9
0
        public ActivityOperatorsVM(ActivityVM activity, AccessType access)
            : base(access)
        {
            UnitOfWork = new SoheilEdmContext();
            CurrentActivity = activity;
            ActivityDataService = new ActivityDataService(UnitOfWork);
            ActivityDataService.OperatorAdded += OnOperatorAdded;
            ActivityDataService.OperatorRemoved += OnOperatorRemoved;
            OperatorDataService = new OperatorDataService(UnitOfWork);
            ActivityOperatorDataService = new ActivitySkillDataService(UnitOfWork);

            var selectedVms = new ObservableCollection<ActivityOperatorVM>();
            foreach (var activityOperator in ActivityDataService.GetOperators(activity.Id))
            {
                selectedVms.Add(new ActivityOperatorVM(activityOperator, Access, ActivityOperatorDataService, RelationDirection.Straight));
            }
            SelectedItems = new ListCollectionView(selectedVms);

            var allVms = new ObservableCollection<OperatorVM>();
            foreach (var opr in OperatorDataService.GetActives(SoheilEntityType.Activities, CurrentActivity.Id))
            {
                allVms.Add(new OperatorVM(opr, Access, OperatorDataService));
            }
            AllItems = new ListCollectionView(allVms);

            IncludeCommand = new Command(Include, CanInclude);
            ExcludeCommand = new Command(Exclude, CanExclude);
        }
예제 #10
0
        public ActionPlanFishbonesVM(ActionPlanVM actionPlan, AccessType access)
            : base(access)
        {
            UnitOfWork = new SoheilEdmContext();
            CurrentActionPlan = actionPlan;
            ActionPlanDataService = new ActionPlanDataService(UnitOfWork);
            ActionPlanDataService.FishboneNodeAdded += OnFishboneNodeAdded;
            ActionPlanDataService.FishboneNodeRemoved += OnFishboneNodeRemoved;
            FishboneActionPlanDataService = new FishboneActionPlanDataService(UnitOfWork);
            FishboneNodeDataService = new FishboneNodeDataService(UnitOfWork);

            var selectedVms = new ObservableCollection<ActionPlanFishboneVM>();
            foreach (var fishboneNodeActionPlan in ActionPlanDataService.GetFishboneNodes(actionPlan.Id))
            {
                selectedVms.Add(new ActionPlanFishboneVM(fishboneNodeActionPlan,access,RelationDirection.Straight));
            }
            SelectedItems = new ListCollectionView(selectedVms);

            var allVms = new ObservableCollection<FishboneNodeVM>();
            foreach (var fishboneNode in FishboneNodeDataService.GetActives())
            {
                allVms.Add(new FishboneNodeVM(fishboneNode, Access, FishboneNodeDataService));
            }
            AllItems = new ListCollectionView(allVms);

            IncludeCommand = new Command(Include, CanInclude);
            ExcludeCommand = new Command(Exclude, CanExclude);
        }
예제 #11
0
 public User(string name, string password, AccessType accessType, List<Directory> directories)
 {
     Name = name;
     Password = password;
     AccessType = accessType;
     Directories = directories;
 }
예제 #12
0
        public AccessRulePositionsVM(AccessRuleVM accessRule, AccessType access)
            : base(access)
        {
            UnitOfWork = new SoheilEdmContext();
            CurrentAccessRule = accessRule;
            AccessRuleDataService = new AccessRuleDataService(UnitOfWork);
            AccessRuleDataService.PositionAdded += OnPositionAdded;
            AccessRuleDataService.PositionRemoved += OnPositionRemoved;
            PositionDataService = new PositionDataService(UnitOfWork);

            var selectedVms = new ObservableCollection<PositionAccessRuleVM>();
            foreach (var accessRulePosition in AccessRuleDataService.GetPositions(accessRule.Id))
            {
                selectedVms.Add(new PositionAccessRuleVM(accessRulePosition, Access, RelationDirection.Reverse));
            }
            SelectedItems = new ListCollectionView(selectedVms);

            var allVms = new ObservableCollection<PositionVM>();
            foreach (var position in PositionDataService.GetActives())
            {
                allVms.Add(new PositionVM(position, Access,PositionDataService));
            }
            AllItems = new ListCollectionView(allVms);

            IncludeCommand = new Command(Include,CanInclude);
            ExcludeCommand = new Command(Exclude,CanExclude);
        }
예제 #13
0
 public EntityGroupPermission(string name, AccessType accessType, params Type[] entityTypes)
     : base(name)
 {
     AccessType = accessType;
       var resource = new EntityGroupResource(name + "_resource", entityTypes);
       GroupResources.Add(resource);
 }
예제 #14
0
파일: Tile.cs 프로젝트: eimink/KoboldAI
 public float GetAccessCost(AccessType accessMethod)
 {
     AccessCost ac = AccessCosts.Find(p => FlagsHelper.IsSet(p.Type,accessMethod));
     if (ac != null)
         return ac.Cost;
     else return Mathf.Infinity;
 }
예제 #15
0
 public static Token CreateAndSign(string username,string profileImg, AccessType accessLevel, DateTimeOffset? expiredTime)
 {
     var expiration = expiredTime.HasValue ? expiredTime.Value : DateTimeOffset.Now + TimeSpan.FromDays(2);
     var token = new Token(username, profileImg, accessLevel, expiration);
     SignToken(token);
     return token;
 }
예제 #16
0
 private Token(string username, string profileImg, AccessType accessType, DateTimeOffset expiration)
 {
     UserName = username;
     ProfilePath = profileImg;
     AccessLevel = accessType;
     ExpireTime = expiration;
 }
예제 #17
0
 public void Merge(UserRecordPermission other)
 {
     Peek.Merge(other.Peek);
       ReadStrict.Merge(other.ReadStrict);
       UpdateStrict.Merge(other.UpdateStrict);
       AccessTypes |= other.AccessTypes;
 }
예제 #18
0
        bool _initialized; //to avoid multiple initializations

        #endregion Fields

        #region Constructors

        public EntityGroupPermission(string name, AccessType accessType, params EntityGroupResource[] groupResources)
            : base(name)
        {
            AccessType = accessType;
              if (groupResources != null)
            Add(groupResources);
        }
예제 #19
0
        public UserPositionsVM(UserVM user, AccessType access)
            : base(access)
        {
            UnitOfWork = new SoheilEdmContext();
            CurrentUser = user;
            UserDataService = new UserDataService(UnitOfWork);
            PositionDataService = new PositionDataService(UnitOfWork);
            AccessRuleDataService = new AccessRuleDataService(UnitOfWork);
            UserDataService.PositionAdded += OnPositionAdded;
            UserDataService.PositionRemoved += OnPositionRemoved;


            var selectedVms = new ObservableCollection<UserPositionVM>();
            foreach (var userPosition in UserDataService.GetPositions(user.Id))
            {
                selectedVms.Add(new UserPositionVM(userPosition, Access, RelationDirection.Straight));
            }
            SelectedItems = new ListCollectionView(selectedVms);

            var allVms = new ObservableCollection<PositionVM>();
            foreach (var position in PositionDataService.GetActives(SoheilEntityType.Users, CurrentUser.Id))
            {
                allVms.Add(new PositionVM(position, Access, PositionDataService));
            }
            AllItems = new ListCollectionView(allVms);

            //AllItems = new ListCollectionView(PositionDataService.GetActives());
            IncludeCommand = new Command(Include, CanInclude);
            ExcludeCommand = new Command(Exclude, CanExclude);
        }
예제 #20
0
 internal Lock(LockingQueue queue, LockingMode mode, AccessType accessType)
 {
     Queue = queue;
     AccessType = accessType;
     Mode = mode;
     Queue.Acquire(this);
 }
예제 #21
0
        public PositionUsersVM(PositionVM position, AccessType access)
            : base(access)
        {
            UnitOfWork = new SoheilEdmContext();
            CurrentPosition = position;
            PositionDataService = new PositionDataService(UnitOfWork);
            PositionDataService.UserAdded += OnUserAdded;
            PositionDataService.UserRemoved += OnUserRemoved;
            UserDataService = new UserDataService(UnitOfWork);

            var selectedVms = new ObservableCollection<UserPositionVM>();
            foreach (var positionUser in PositionDataService.GetUsers(position.Id))
            {
                selectedVms.Add(new UserPositionVM(positionUser, Access, RelationDirection.Reverse));
            }
            SelectedItems = new ListCollectionView(selectedVms);

            var allVms = new ObservableCollection<UserVM>();
            foreach (var user in UserDataService.GetActives(SoheilEntityType.Positions, CurrentPosition.Id))
            {
                allVms.Add(new UserVM(user, Access, UserDataService));
            }
            AllItems = new ListCollectionView(allVms);

            IncludeCommand = new Command(Include, CanInclude);
            ExcludeCommand = new Command(Exclude, CanExclude);
            
        }
예제 #22
0
 public UserRecordPermission(AccessType accessTypes, EntityMemberMask memberMask = null)
 {
     Peek = new OperationPermission(AccessType.Peek, accessTypes.IsSet(AccessType.Peek), memberMask);
       ReadStrict = new OperationPermission(AccessType.ReadStrict, accessTypes.IsSet(AccessType.ReadStrict), memberMask);
       UpdateStrict = new OperationPermission(AccessType.UpdateStrict, accessTypes.IsSet(AccessType.UpdateStrict), memberMask);
       AccessTypes = accessTypes;
 }
예제 #23
0
 public UserRecordPermission()
 {
     AccessTypes = AccessType.None;
       Peek = new OperationPermission(AccessType.Peek, false);
       ReadStrict = new OperationPermission(AccessType.ReadStrict, false);
       UpdateStrict = new OperationPermission(AccessType.UpdateStrict, false);
 }
예제 #24
0
        public DefectionProductsVM(DefectionVM defection, AccessType access)
            : base(access)
        {
            UnitOfWork = new SoheilEdmContext();
            CurrentDefection = defection;
            DefectionDataService = new DefectionDataService(UnitOfWork);
            DefectionDataService.ProductAdded += OnProductAdded;
            DefectionDataService.ProductRemoved += OnProductRemoved;
            ProductDataService = new ProductDataService(UnitOfWork);
            ProductGroupDataService = new ProductGroupDataService(UnitOfWork);
            ProductDefectionDataService = new ProductDefectionDataService(UnitOfWork);

            var selectedVms = new ObservableCollection<ProductDefectionVM>();
            foreach (var productDefection in DefectionDataService.GetProducts(defection.Id))
            {
                selectedVms.Add(new ProductDefectionVM(productDefection, Access, ProductDefectionDataService, RelationDirection.Reverse));
            }
            SelectedItems = new ListCollectionView(selectedVms);

            var allVms = new ObservableCollection<ProductVM>();
            foreach (var product in ProductDataService.GetActives(SoheilEntityType.Defections, CurrentDefection.Id))
            {
                allVms.Add(new ProductVM(product, Access, ProductDataService, ProductGroupDataService));
            }
            AllItems = new ListCollectionView(allVms);

            IncludeCommand = new Command(Include, CanInclude);
            ExcludeCommand = new Command(Exclude, CanExclude);
        }
예제 #25
0
 public Access(Organization organization, Geography geography, AccessAspect aspect, AccessType type)
 {
     this.Organization = organization;
     this.Geography = geography;
     this.Aspect = aspect;
     this.Type = type;
 }
예제 #26
0
		/// <summary>
		/// Initializes a new instance of the <see cref="WorkProfileVm"/> class from the model.
		/// </summary>
		/// <param name="entity">The model.</param>
		/// <param name="access"></param>
		/// <param name="dataService"></param>
		public WorkProfileVm(WorkProfile entity, AccessType access)
			: base(access)
		{
			IsReadonly = (access < AccessType.Update);
			_model = entity;
			InitializeData();
		}
예제 #27
0
 public AuthorizationException(string message, Type entityType, AccessType accessType, bool isRecordLevel, 
     UserRecordPermission grantedPermissions, SecureSession session = null)
     : base(message)
 {
     EntityType = entityType;
       AccessType = accessType;
       IsRecordLevel = isRecordLevel;
       GrantedPermissions = grantedPermissions;
       if (session != null) {
     RequireReadMode = session.DemandReadAccessLevel;
     CurrentDenyReadMode = session.DenyReadAction;
     var ctx = session.Context;
     UserName = ctx.User.UserName;
     UserContextValues = string.Join(string.Empty, ctx.Values.Select(kv => StringHelper.SafeFormat("      [{0}]={1}\r\n", kv.Key, kv.Value)));
     var user = ctx.User;
     if (user.Authority == null) {
       UserRoles = "(UserContext.Authority is not set)";
     } else {
       UserRoles = user.Authority.GetRoleNames();
       PermissionSummary = user.Authority.GetPermissionsSummary(EntityType);
       var enDynGrants = user.Authority.DynamicGrants.Where(g => g.IsEnabled(session.Context));
       EnabledDynamicGrants = string.Join(",", enDynGrants.Select(g => g.Activity.Name));
     }
       }
 }
        public PositionOrganizationChartsVM(PositionVM position, AccessType access)
            : base(access)
        {
            UnitOfWork = new SoheilEdmContext();
            CurrentPosition = position;
            PositionDataService = new PositionDataService(UnitOfWork);
            PositionDataService.OrganizationChartAdded += OnOrganizationChartAdded;
            PositionDataService.OrganizationChartRemoved += OnOrganizationChartRemoved;
            OrganizationChartDataService = new OrganizationChartDataService(UnitOfWork);
            OrganizationChartPositionDataService = new OrganizationChartPositionDataService(UnitOfWork);

            var selectedVms = new ObservableCollection<OrganizationChartPositionVM>();
            foreach (var positionOrganizationChart in PositionDataService.GetOrganizationCharts(position.Id))
            {
                selectedVms.Add(new OrganizationChartPositionVM(positionOrganizationChart, Access, OrganizationChartPositionDataService));
            }
            SelectedItems = new ListCollectionView(selectedVms);

            var allVms = new ObservableCollection<OrganizationChartVM>();
            foreach (var organizationChart in OrganizationChartDataService.GetActives())
            {
                allVms.Add(new OrganizationChartVM(organizationChart, Access, OrganizationChartDataService));
            }
            AllItems = new ListCollectionView(allVms);

            IncludeCommand = new Command(Include, CanInclude);
            ExcludeCommand = new Command(Exclude, CanExclude);
            
        }
예제 #29
0
        public AccessRuleUsersVM(AccessRuleVM accessRule, AccessType access)
            : base(access)
        {
            UnitOfWork = new SoheilEdmContext();
            CurrentAccessRule = accessRule;
            AccessRuleDataService = new AccessRuleDataService(UnitOfWork);
            AccessRuleDataService.UserAdded += OnUserAdded;
            AccessRuleDataService.UserRemoved += OnUserRemoved;
            UserDataService = new UserDataService(UnitOfWork);

            var selectedVms = new ObservableCollection<UserAccessRuleVM>();
            foreach (var accessRuleUser in AccessRuleDataService.GetUsers(accessRule.Id))
            {
                selectedVms.Add(new UserAccessRuleVM(accessRuleUser, Access, RelationDirection.Reverse));
            }
            SelectedItems = new ListCollectionView(selectedVms);

            var allVms = new ObservableCollection<UserVM>();
            foreach (var user in UserDataService.GetActives())
            {
                allVms.Add(new UserVM(user, Access, UserDataService));
            }
            AllItems = new ListCollectionView(allVms);

            IncludeCommand = new Command(Include,CanInclude);
            ExcludeCommand = new Command(Exclude, CanExclude);
        }
        public IHttpActionResult PutAccessType(int id, AccessType accessType)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != accessType.AccessTypeId)
            {
                return BadRequest();
            }

            db.Entry(accessType).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AccessTypeExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
예제 #31
0
 /// <summary>
 /// Grant method declaration.
 /// This method is used to grant a user rights to database objects.
 /// </summary>
 /// <param name="name">name of the user</param>
 /// <param name="dbobject">object in the database</param>
 /// <param name="right">right to grant to the user</param>
 public void Grant(string name, string dbobject, AccessType right)
 {
     Get(name).Grant(dbobject, right);
 }
예제 #32
0
    /// <summary>
    /// This function get the access token based on the type parameter type values.
    /// If type value is 1, access token is fetch for client credential flow
    /// If type value is 2, access token is fetch for client credential flow based on the exisiting refresh token
    /// </summary>
    /// <param name="type">Type as integer</param>
    /// <param name="panelParam">Panel details</param>
    /// <returns>Return boolean</returns>
    private bool GetAccessToken(AccessType type, Panel panelParam)
    {
        FileStream   fileStream   = null;
        Stream       postStream   = null;
        StreamWriter streamWriter = null;

        // This is client credential flow
        if (type == AccessType.ClientCredential)
        {
            try
            {
                DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();

                WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create(string.Empty + this.endPoint + "/oauth/token");
                accessTokenRequest.Method = "POST";
                string oauthParameters = string.Empty;
                if (type == AccessType.ClientCredential)
                {
                    oauthParameters = "client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&grant_type=client_credentials&scope=" + this.scope;
                }
                else
                {
                    oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken;
                }

                accessTokenRequest.ContentType = "application/x-www-form-urlencoded";

                UTF8Encoding encoding  = new UTF8Encoding();
                byte[]       postBytes = encoding.GetBytes(oauthParameters);
                accessTokenRequest.ContentLength = postBytes.Length;

                postStream = accessTokenRequest.GetRequestStream();
                postStream.Write(postBytes, 0, postBytes.Length);

                WebResponse accessTokenResponse = accessTokenRequest.GetResponse();
                using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream()))
                {
                    string jsonAccessToken = accessTokenResponseStream.ReadToEnd().ToString();
                    JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();

                    AccessTokenResponse deserializedJsonObj = (AccessTokenResponse)deserializeJsonObject.Deserialize(jsonAccessToken, typeof(AccessTokenResponse));

                    this.accessToken           = deserializedJsonObj.access_token;
                    this.accessTokenExpiryTime = currentServerTime.AddSeconds(Convert.ToDouble(deserializedJsonObj.expires_in)).ToString();
                    this.refreshToken          = deserializedJsonObj.refresh_token;

                    DateTime refreshExpiry = currentServerTime.AddHours(this.refreshTokenExpiresIn);

                    if (deserializedJsonObj.expires_in.Equals("0"))
                    {
                        int defaultAccessTokenExpiresIn = 100; // In Yearsint yearsToAdd = 100;
                        this.accessTokenExpiryTime = currentServerTime.AddYears(defaultAccessTokenExpiresIn).ToLongDateString() + " " + currentServerTime.AddYears(defaultAccessTokenExpiresIn).ToLongTimeString();
                    }

                    this.refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString();

                    fileStream   = new FileStream(Request.MapPath(this.accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Write);
                    streamWriter = new StreamWriter(fileStream);
                    streamWriter.WriteLine(this.accessToken);
                    streamWriter.WriteLine(this.accessTokenExpiryTime);
                    streamWriter.WriteLine(this.refreshToken);
                    streamWriter.WriteLine(this.refreshTokenExpiryTime);

                    // Close and clean up the StreamReader
                    accessTokenResponseStream.Close();
                    return(true);
                }
            }
            catch (WebException we)
            {
                string errorResponse = string.Empty;

                try
                {
                    using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
                    {
                        errorResponse = sr2.ReadToEnd();
                        sr2.Close();
                    }
                }
                catch
                {
                    errorResponse = "Unable to get response";
                }

                this.DrawPanelForFailure(panelParam, errorResponse + Environment.NewLine + we.ToString());
            }
            catch (Exception ex)
            {
                this.DrawPanelForFailure(panelParam, ex.Message);
                return(false);
            }
            finally
            {
                if (null != postStream)
                {
                    postStream.Close();
                }

                if (null != streamWriter)
                {
                    streamWriter.Close();
                }

                if (null != fileStream)
                {
                    fileStream.Close();
                }
            }
        }
        else if (type == AccessType.RefreshToken)
        {
            try
            {
                DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();

                WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create(string.Empty + this.endPoint + "/oauth/token");
                accessTokenRequest.Method = "POST";

                string oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken;
                accessTokenRequest.ContentType = "application/x-www-form-urlencoded";

                UTF8Encoding encoding  = new UTF8Encoding();
                byte[]       postBytes = encoding.GetBytes(oauthParameters);
                accessTokenRequest.ContentLength = postBytes.Length;

                postStream = accessTokenRequest.GetRequestStream();
                postStream.Write(postBytes, 0, postBytes.Length);

                WebResponse accessTokenResponse = accessTokenRequest.GetResponse();
                using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream()))
                {
                    string accessTokenJSon = accessTokenResponseStream.ReadToEnd().ToString();
                    JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();

                    AccessTokenResponse deserializedJsonObj = (AccessTokenResponse)deserializeJsonObject.Deserialize(accessTokenJSon, typeof(AccessTokenResponse));
                    this.accessToken = deserializedJsonObj.access_token.ToString();
                    DateTime accessTokenExpiryTime = currentServerTime.AddMilliseconds(Convert.ToDouble(deserializedJsonObj.expires_in.ToString()));
                    this.refreshToken = deserializedJsonObj.refresh_token.ToString();

                    fileStream   = new FileStream(Request.MapPath(this.accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Write);
                    streamWriter = new StreamWriter(fileStream);
                    streamWriter.WriteLine(this.accessToken);
                    streamWriter.WriteLine(this.accessTokenExpiryTime);
                    streamWriter.WriteLine(this.refreshToken);

                    // Refresh token valids for 24 hours
                    DateTime refreshExpiry = currentServerTime.AddHours(24);
                    this.refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString();
                    streamWriter.WriteLine(refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString());

                    accessTokenResponseStream.Close();
                    return(true);
                }
            }
            catch (WebException we)
            {
                string errorResponse = string.Empty;

                try
                {
                    using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
                    {
                        errorResponse = sr2.ReadToEnd();
                        sr2.Close();
                    }
                }
                catch
                {
                    errorResponse = "Unable to get response";
                }

                this.DrawPanelForFailure(panelParam, errorResponse + Environment.NewLine + we.ToString());
            }
            catch (Exception ex)
            {
                this.DrawPanelForFailure(panelParam, ex.Message);
                return(false);
            }
            finally
            {
                if (null != postStream)
                {
                    postStream.Close();
                }

                if (null != streamWriter)
                {
                    streamWriter.Close();
                }

                if (null != fileStream)
                {
                    fileStream.Close();
                }
            }
        }

        return(false);
    }
예제 #33
0
 private static void EmitLdp(ILEmitterCtx context, AccessType accType)
 {
     EmitLoad(context, accType, pair: true);
 }
예제 #34
0
 private static extern IntPtr WinHttpOpen(
     string userAgent,
     AccessType accessType,
     string proxyName,
     string proxyBypass,
     int flags);
예제 #35
0
    //验证数据
    bool ValidateData()
    {
        //foreach (CBaseObject objCIVD in m_ViewDetail.ColumnInViewDetailMgr.GetList())
        foreach (CBaseObject objCol in m_Table.ColumnMgr.GetList())
        {
            //CColumnInViewDetail civd = (CColumnInViewDetail)objCIVD;

            //CColumn col = (CColumn)m_Table.ColumnMgr.Find(civd.FW_Column_id);
            CColumn col = (CColumn)objCol;
            if (col == null)
            {
                continue;
            }
            //判断禁止和只读权限字段
            if (m_sortRestrictColumnAccessType.ContainsKey(col.Id))
            {
                AccessType accessType = m_sortRestrictColumnAccessType[col.Id];
                if (accessType == AccessType.forbide)
                {
                    continue;
                }
                //只读只在界面控制,有些默认值需要只读也需要保存数据
                //else if (accessType == AccessType.read)
                //    continue;
            }
            //

            if (col.Code.Equals("id", StringComparison.OrdinalIgnoreCase))
            {
                continue;
            }
            else if (col.Code.Equals("Created", StringComparison.OrdinalIgnoreCase))
            {
                continue;
            }
            else if (col.Code.Equals("Creator", StringComparison.OrdinalIgnoreCase))
            {
                continue;
            }
            else if (col.Code.Equals("Updated", StringComparison.OrdinalIgnoreCase))
            {
                continue;
            }
            else if (col.Code.Equals("Updator", StringComparison.OrdinalIgnoreCase))
            {
                continue;
            }

            string val = Request.Params["_" + col.Code];
            if (!col.AllowNull && string.IsNullOrEmpty(val))
            {
                Response.Write(string.Format("<script>alert('{0}不允许空!');</script>", col.Name));
                return(false);
            }
            if (col.ColType == ColumnType.string_type)
            {
                if (val.Length > col.ColLen)
                {
                    Response.Write(string.Format("<script>alert('{0}长度不能超过{1}!');</script>", col.Name, col.ColLen));
                    return(false);
                }
            }
            else if (col.ColType == ColumnType.datetime_type)
            {
                if (!string.IsNullOrEmpty(val))
                {
                    try { Convert.ToDateTime(val); }
                    catch
                    {
                        Response.Write(string.Format("<script>alert('{0}日期格式错误!');</script>", col.Name));
                        return(false);
                    }
                }
            }
            else if (col.ColType == ColumnType.int_type ||
                     col.ColType == ColumnType.long_type)
            {
                if (!Util.IsInt(val))
                {
                    Response.Write(string.Format("<script>alert('{0}为整型数字!');</script>", col.Name));
                    return(false);
                }
            }
            else if (col.ColType == ColumnType.numeric_type)
            {
                if (!Util.IsNum(val))
                {
                    Response.Write(string.Format("<script>alert('{0}为数字!');</script>", col.Name));
                    return(false);
                }
            }
            else if (col.ColType == ColumnType.guid_type ||
                     col.ColType == ColumnType.ref_type)
            {
                if (!string.IsNullOrEmpty(val))
                {
                    try { Guid guid = new Guid(val); }
                    catch
                    {
                        Response.Write(string.Format("<script>alert('{0}为GUID格式!');</script>", col.Name));
                        return(false);
                    }
                }
            }

            //唯一性字段判断
            if (col.IsUnique)
            {
                if (!IsUniqueValue(col, val))
                {
                    return(false);
                }
            }
        }
        return(true);
    }
예제 #36
0
    void PostData()
    {
        if (!ValidateData())
        {
            return;
        }

        bool bHasVisible = false;

        //foreach (CBaseObject objCIVD in m_ViewDetail.ColumnInViewDetailMgr.GetList())
        foreach (CBaseObject objCol in m_Table.ColumnMgr.GetList())
        {
            //CColumnInViewDetail civd = (CColumnInViewDetail)objCIVD;

            //CColumn col = (CColumn)m_Table.ColumnMgr.Find(civd.FW_Column_id);
            CColumn col = (CColumn)objCol;
            if (col == null)
            {
                continue;
            }
            //判断禁止和只读权限字段
            if (m_sortRestrictColumnAccessType.ContainsKey(col.Id))
            {
                AccessType accessType = m_sortRestrictColumnAccessType[col.Id];
                if (accessType == AccessType.forbide)
                {
                    continue;
                }
                //只读只在界面控制,有些默认值需要只读也需要保存数据
                //else if (accessType == AccessType.read)
                //    continue;
            }
            //

            if (col.Code.Equals("id", StringComparison.OrdinalIgnoreCase))
            {
                continue;
            }
            else if (col.Code.Equals("Created", StringComparison.OrdinalIgnoreCase))
            {
                continue;
            }
            else if (col.Code.Equals("Creator", StringComparison.OrdinalIgnoreCase))
            {
                //BaseObject.SetColValue(col, Program.User.Id);
                continue;
            }
            else if (col.Code.Equals("Updated", StringComparison.OrdinalIgnoreCase))
            {
                m_BaseObject.SetColValue(col, DateTime.Now);
                continue;
            }
            else if (col.Code.Equals("Updator", StringComparison.OrdinalIgnoreCase))
            {
                CUser u = (CUser)Session["User"];
                m_BaseObject.SetColValue(col, u.Id);
                continue;
            }

            if (col.ColType == ColumnType.object_type)
            {
                string ckVal = Request.Params["ckClear_" + col.Code];
                if (!string.IsNullOrEmpty(ckVal) && ckVal.ToLower() == "on")
                {
                    //清空附件
                    m_BaseObject.SetColValue(col, null);
                }
                else
                {
                    HttpPostedFile postfile = Request.Files.Get("_" + col.Code);
                    if (postfile != null && postfile.ContentLength > 0)
                    {
                        string sFileName = postfile.FileName;
                        if (sFileName.LastIndexOf('\\') > -1)//有些浏览器不带路径
                        {
                            sFileName = sFileName.Substring(sFileName.LastIndexOf('\\'));
                        }

                        byte[] byteFileName = System.Text.Encoding.Default.GetBytes(sFileName);
                        byte[] byteValue    = new byte[254 + postfile.ContentLength];
                        byte[] byteData     = new byte[postfile.ContentLength];
                        postfile.InputStream.Read(byteData, 0, postfile.ContentLength);

                        Array.Copy(byteFileName, byteValue, byteFileName.Length);
                        Array.Copy(byteData, 0, byteValue, 254, byteData.Length);

                        m_BaseObject.SetColValue(col, byteValue);
                    }
                }
            }
            else if (col.ColType == ColumnType.path_type)
            {
                string sUploadPath = col.UploadPath;
                if (sUploadPath[sUploadPath.Length - 1] != '\\')
                {
                    sUploadPath += "\\";
                }
                if (!Directory.Exists(sUploadPath))
                {
                    Directory.CreateDirectory(sUploadPath);
                }

                string ckVal = Request.Params["ckClear_" + col.Code];
                if (!string.IsNullOrEmpty(ckVal) && ckVal.ToLower() == "on")
                {
                    //清空附件
                    m_BaseObject.SetColValue(col, "");
                }
                else
                {
                    HttpPostedFile postfile = Request.Files.Get("_" + col.Code);
                    if (postfile != null && postfile.ContentLength > 0)
                    {
                        string sFileName = postfile.FileName;
                        if (sFileName.LastIndexOf('\\') > -1)//有些浏览器不带路径
                        {
                            sFileName = sFileName.Substring(sFileName.LastIndexOf('\\'));
                        }

                        FileInfo fi        = new FileInfo(sUploadPath + sFileName);
                        Guid     guid      = Guid.NewGuid();
                        string   sDestFile = string.Format("{0}{1}", guid.ToString().Replace("-", ""), fi.Extension);
                        postfile.SaveAs(sUploadPath + sDestFile);

                        string sVal = string.Format("{0}|{1}", sDestFile, sFileName);
                        m_BaseObject.SetColValue(col, sVal);
                    }
                }
            }
            else if (col.ColType == ColumnType.bool_type)
            {
                string val = Request.Params["_" + col.Code];
                if (!string.IsNullOrEmpty(val) && val.ToLower() == "on")
                {
                    m_BaseObject.SetColValue(col, true);
                }
                else
                {
                    m_BaseObject.SetColValue(col, false);
                }
            }
            else if (col.ColType == ColumnType.datetime_type)
            {
                string val = Request.Params["_" + col.Code];
                if (!string.IsNullOrEmpty(val))
                {
                    m_BaseObject.SetColValue(col, Convert.ToDateTime(val));
                }
            }
            else
            {
                m_BaseObject.SetColValue(col, Request.Params["_" + col.Code]);
            }
            bHasVisible = true;
        }
        if (!bHasVisible)
        {
            //Response.Write("没有可修改字段!");
            Response.Write("<script>alert('没有可修改字段!');</script>");
            return;
        }

        SortedList <Guid, CBaseObject> arrP = (SortedList <Guid, CBaseObject>)Session["EditMultMasterDetailViewRecord"];
        CBaseObject objP = (CBaseObject)arrP.Values[0];
        CColumn     colP = (CColumn)objP.Table.ColumnMgr.Find(m_ViewDetail.PrimaryKey);
        CColumn     colF = (CColumn)m_Table.ColumnMgr.Find(m_ViewDetail.ForeignKey);

        m_BaseObject.SetColValue(colF, objP.GetColValue(colP));

        CUser user = (CUser)Session["User"];

        m_BaseObject.Updator = user.Id;
        m_BaseObjectMgr.Update(m_BaseObject);
        if (!m_BaseObjectMgr.Save(true))
        {
            //Response.Write("修改失败!");
            Response.Write("<script>alert('修改失败!');</script>");
            return;
        }
        //在iframe里访问外面,需要parent.parent.
        //Response.Write("<script>parent.parent.grid.loadData(true);parent.parent.$.ligerDialog.close();</script>");
        Response.Write("<script>parent.parent.onOkEditMultDetailRecord2();</script>");
    }
예제 #37
0
        public void Wait(ILockable lockable, AccessType accessType)
        {
            var timeout = locker.context.LockTimeout();

            Wait(lockable, accessType, timeout);
        }
예제 #38
0
 private static void EmitStr(ILEmitterCtx context, AccessType accType)
 {
     EmitStore(context, accType, pair: false);
 }
예제 #39
0
        private static void EmitStore(ILEmitterCtx context, AccessType accType, bool pair)
        {
            OpCodeMemEx64 op = (OpCodeMemEx64)context.CurrOp;

            bool ordered   = (accType & AccessType.Ordered) != 0;
            bool exclusive = (accType & AccessType.Exclusive) != 0;

            if (ordered)
            {
                EmitBarrier(context);
            }

            if (exclusive)
            {
                ILLabel lblEx  = new ILLabel();
                ILLabel lblEnd = new ILLabel();

                context.EmitLdarg(TranslatedSub.StateArgIdx);
                context.EmitLdint(op.Rn);

                context.EmitPrivateCall(typeof(CpuThreadState), nameof(CpuThreadState.CheckExclusiveAddress));

                context.Emit(OpCodes.Brtrue_S, lblEx);

                //Address check failed, set error right away and do not store anything.
                context.EmitLdc_I4(1);
                context.EmitStintzr(op.Rs);

                context.Emit(OpCodes.Br, lblEnd);

                //Address check passsed.
                context.MarkLabel(lblEx);

                context.EmitLdarg(TranslatedSub.MemoryArgIdx);
                context.EmitLdint(op.Rn);

                context.EmitLdarg(TranslatedSub.StateArgIdx);

                context.EmitCallPrivatePropGet(typeof(CpuThreadState), nameof(CpuThreadState.ExclusiveValueLow));

                void EmitCast()
                {
                    //The input should be always int64.
                    switch (op.Size)
                    {
                    case 0: context.Emit(OpCodes.Conv_U1); break;

                    case 1: context.Emit(OpCodes.Conv_U2); break;

                    case 2: context.Emit(OpCodes.Conv_U4); break;
                    }
                }

                EmitCast();

                if (pair)
                {
                    context.EmitLdarg(TranslatedSub.StateArgIdx);

                    context.EmitCallPrivatePropGet(typeof(CpuThreadState), nameof(CpuThreadState.ExclusiveValueHigh));

                    EmitCast();

                    context.EmitLdintzr(op.Rt);

                    EmitCast();

                    context.EmitLdintzr(op.Rt2);

                    EmitCast();

                    switch (op.Size)
                    {
                    case 2: context.EmitPrivateCall(typeof(MemoryManager), nameof(MemoryManager.AtomicCompareExchange2xInt32)); break;

                    case 3: context.EmitPrivateCall(typeof(MemoryManager), nameof(MemoryManager.AtomicCompareExchangeInt128));  break;

                    default: throw new InvalidOperationException($"Invalid store size of {1 << op.Size} bytes.");
                    }
                }
                else
                {
                    context.EmitLdintzr(op.Rt);

                    EmitCast();

                    switch (op.Size)
                    {
                    case 0: context.EmitCall(typeof(MemoryManager), nameof(MemoryManager.AtomicCompareExchangeByte));  break;

                    case 1: context.EmitCall(typeof(MemoryManager), nameof(MemoryManager.AtomicCompareExchangeInt16)); break;

                    case 2: context.EmitCall(typeof(MemoryManager), nameof(MemoryManager.AtomicCompareExchangeInt32)); break;

                    case 3: context.EmitCall(typeof(MemoryManager), nameof(MemoryManager.AtomicCompareExchangeInt64)); break;

                    default: throw new InvalidOperationException($"Invalid store size of {1 << op.Size} bytes.");
                    }
                }

                //The value returned is a bool, true if the values compared
                //were equal and the new value was written, false otherwise.
                //We need to invert this result, as on ARM 1 indicates failure,
                //and 0 success on those instructions.
                context.EmitLdc_I4(1);

                context.Emit(OpCodes.Xor);
                context.Emit(OpCodes.Dup);
                context.Emit(OpCodes.Conv_U8);

                context.EmitStintzr(op.Rs);

                //Only clear the exclusive monitor if the store was successful (Rs = false).
                context.Emit(OpCodes.Brtrue_S, lblEnd);

                Clrex(context);

                context.MarkLabel(lblEnd);
            }
            else
            {
                void EmitWriteCall(int rt, long offset)
                {
                    context.EmitLdint(op.Rn);

                    if (offset != 0)
                    {
                        context.EmitLdc_I8(offset);

                        context.Emit(OpCodes.Add);
                    }

                    context.EmitLdintzr(rt);

                    InstEmitMemoryHelper.EmitWriteCall(context, op.Size);
                }

                EmitWriteCall(op.Rt, 0);

                if (pair)
                {
                    EmitWriteCall(op.Rt2, 1 << op.Size);
                }
            }
        }
예제 #40
0
        private static void EmitLoad(ILEmitterCtx context, AccessType accType, bool pair)
        {
            OpCodeMemEx64 op = (OpCodeMemEx64)context.CurrOp;

            bool ordered   = (accType & AccessType.Ordered) != 0;
            bool exclusive = (accType & AccessType.Exclusive) != 0;

            if (ordered)
            {
                EmitBarrier(context);
            }

            context.EmitLdint(op.Rn);
            context.EmitSttmp();

            if (exclusive)
            {
                context.EmitLdarg(TranslatedSub.StateArgIdx);
                context.EmitLdtmp();

                context.EmitPrivateCall(typeof(CpuThreadState), nameof(CpuThreadState.SetExclusiveAddress));
            }

            void WriteExclusiveValue(string propName)
            {
                context.Emit(OpCodes.Dup);

                if (op.Size < 3)
                {
                    context.Emit(OpCodes.Conv_U8);
                }

                context.EmitSttmp2();
                context.EmitLdarg(TranslatedSub.StateArgIdx);
                context.EmitLdtmp2();

                context.EmitCallPrivatePropSet(typeof(CpuThreadState), propName);
            }

            if (pair)
            {
                //Exclusive loads should be atomic. For pairwise loads, we need to
                //read all the data at once. For a 32-bits pairwise load, we do a
                //simple 64-bits load, for a 128-bits load, we need to call a special
                //method to read 128-bits atomically.
                if (op.Size == 2)
                {
                    context.EmitLdtmp();

                    EmitReadZxCall(context, 3);

                    context.Emit(OpCodes.Dup);

                    //Mask low half.
                    context.Emit(OpCodes.Conv_U4);

                    if (exclusive)
                    {
                        WriteExclusiveValue(nameof(CpuThreadState.ExclusiveValueLow));
                    }

                    context.EmitStintzr(op.Rt);

                    //Shift high half.
                    context.EmitLsr(32);
                    context.Emit(OpCodes.Conv_U4);

                    if (exclusive)
                    {
                        WriteExclusiveValue(nameof(CpuThreadState.ExclusiveValueHigh));
                    }

                    context.EmitStintzr(op.Rt2);
                }
                else if (op.Size == 3)
                {
                    context.EmitLdarg(TranslatedSub.MemoryArgIdx);
                    context.EmitLdtmp();

                    context.EmitPrivateCall(typeof(MemoryManager), nameof(MemoryManager.AtomicReadInt128));

                    context.Emit(OpCodes.Dup);

                    //Load low part of the vector.
                    context.EmitLdc_I4(0);
                    context.EmitLdc_I4(3);

                    VectorHelper.EmitCall(context, nameof(VectorHelper.VectorExtractIntZx));

                    if (exclusive)
                    {
                        WriteExclusiveValue(nameof(CpuThreadState.ExclusiveValueLow));
                    }

                    context.EmitStintzr(op.Rt);

                    //Load high part of the vector.
                    context.EmitLdc_I4(1);
                    context.EmitLdc_I4(3);

                    VectorHelper.EmitCall(context, nameof(VectorHelper.VectorExtractIntZx));

                    if (exclusive)
                    {
                        WriteExclusiveValue(nameof(CpuThreadState.ExclusiveValueHigh));
                    }

                    context.EmitStintzr(op.Rt2);
                }
                else
                {
                    throw new InvalidOperationException($"Invalid load size of {1 << op.Size} bytes.");
                }
            }
            else
            {
                //8, 16, 32 or 64-bits (non-pairwise) load.
                context.EmitLdtmp();

                EmitReadZxCall(context, op.Size);

                if (exclusive)
                {
                    WriteExclusiveValue(nameof(CpuThreadState.ExclusiveValueLow));
                }

                context.EmitStintzr(op.Rt);
            }
        }
예제 #41
0
 private static void EmitLdp(ArmEmitterContext context, AccessType accType)
 {
     EmitLoadEx(context, accType, pair: true);
 }
예제 #42
0
        /// <include file='Doc/Nodes.xml' path='doc/method[@name="Emit"]/*'/>
        internal override PhpTypeCode Emit(CodeGenerator codeGenerator)
        {
            Statistics.AST.AddNode("IncDecEx");
            Debug.Assert(access == AccessType.Read || access == AccessType.None);

            AccessType old_selector = codeGenerator.AccessSelector;

            PhpTypeCode returned_typecode = PhpTypeCode.Void;

            codeGenerator.AccessSelector = AccessType.Write;
            codeGenerator.ChainBuilder.Create();
            variable.Emit(codeGenerator);
            codeGenerator.AccessSelector = AccessType.Read;
            codeGenerator.ChainBuilder.Create();
            variable.Emit(codeGenerator);
            codeGenerator.ChainBuilder.End();

            LocalBuilder old_value = null;

            if (access == AccessType.Read && post)
            {
                old_value = codeGenerator.IL.DeclareLocal(Types.Object[0]);
                // Save variable's value for later use
                codeGenerator.IL.Emit(OpCodes.Dup);
                codeGenerator.IL.Stloc(old_value);
            }

            if (this.inc)
            {
                // Increment
                codeGenerator.IL.Emit(OpCodes.Call, Methods.Operators.Increment);
            }
            else
            {
                // Decrement
                codeGenerator.IL.Emit(OpCodes.Call, Methods.Operators.Decrement);
            }

            codeGenerator.AccessSelector = AccessType.Write;
            if (access == AccessType.Read)
            {
                if (post)
                {
                    variable.EmitAssign(codeGenerator);
                    // Load original value (as was before operation)
                    codeGenerator.IL.Ldloc(old_value);
                }
                else
                {
                    old_value = codeGenerator.IL.DeclareLocal(Types.Object[0]);
                    // pre-incrementation
                    // Load variable's value after operation
                    codeGenerator.IL.Emit(OpCodes.Dup);
                    codeGenerator.IL.Stloc(old_value);
                    variable.EmitAssign(codeGenerator);
                    codeGenerator.IL.Ldloc(old_value);
                }

                returned_typecode = PhpTypeCode.Object;
            }
            else
            {
                variable.EmitAssign(codeGenerator);
            }
            codeGenerator.AccessSelector = old_selector;

            codeGenerator.ChainBuilder.End();

            return(returned_typecode);
        }
예제 #43
0
 private static void EmitStr(ArmEmitterContext context, AccessType accType)
 {
     EmitStoreEx(context, accType, pair: false);
 }
예제 #44
0
 /// <summary>
 /// Returns true if the user has access to the resource for the specified type of access requested.
 /// </summary>
 /// <param name="path">Path to resource access is requested for.</param>
 /// <param name="username">Username of user trying to access resource.</param>
 /// <param name="roles">Roles user belongs to.</param>
 /// <param name="type">Type of access requested.</param>
 /// <returns>True if user has access to perform action, otherwise false.</returns>
 public bool Authorize(string path, string username, string[] roles, AccessType type)
 {
     return(_functor(path, username, roles, type));
 }
 public MethodDescripter SetAccess(AccessType access)
 {
     Access = access;
     return(this);
 }
예제 #46
0
        public bool AccessIsAllowed(string login, string password, AccessType requiredAccessType)
        {
            var foundUser = modelDatabase.Users.First(user => user.Login == login && user.Password == password);

            return(-(foundUser.AccessType | (-(int)requiredAccessType - 1)) - 1 == 0);
        }
예제 #47
0
        private static void EmitExLoadOrStore(ArmEmitterContext context, int size, AccessType accType)
        {
            IOpCode32MemEx op = (IOpCode32MemEx)context.CurrOp;

            Operand address = context.Copy(GetIntA32(context, op.Rn));

            var exclusive = (accType & AccessType.Exclusive) != 0;
            var ordered   = (accType & AccessType.Ordered) != 0;

            if (ordered)
            {
                EmitBarrier(context);
            }

            if ((accType & AccessType.Load) != 0)
            {
                if (size == DWordSizeLog2)
                {
                    // Keep loads atomic - make the call to get the whole region and then decompose it into parts
                    // for the registers.

                    Operand value = EmitLoadExclusive(context, address, exclusive, size);

                    Operand valueLow = context.ConvertI64ToI32(value);

                    valueLow = context.ZeroExtend32(OperandType.I64, valueLow);

                    Operand valueHigh = context.ShiftRightUI(value, Const(32));

                    Operand lblBigEndian = Label();
                    Operand lblEnd       = Label();

                    context.BranchIfTrue(lblBigEndian, GetFlag(PState.EFlag));

                    SetIntA32(context, op.Rt, valueLow);
                    SetIntA32(context, op.Rt | 1, valueHigh);

                    context.Branch(lblEnd);

                    context.MarkLabel(lblBigEndian);

                    SetIntA32(context, op.Rt | 1, valueLow);
                    SetIntA32(context, op.Rt, valueHigh);

                    context.MarkLabel(lblEnd);
                }
                else
                {
                    SetIntA32(context, op.Rt, EmitLoadExclusive(context, address, exclusive, size));
                }
            }
            else
            {
                if (size == DWordSizeLog2)
                {
                    // Split the result into 2 words (based on endianness)

                    Operand lo = context.ZeroExtend32(OperandType.I64, GetIntA32(context, op.Rt));
                    Operand hi = context.ZeroExtend32(OperandType.I64, GetIntA32(context, op.Rt | 1));

                    Operand lblBigEndian = Label();
                    Operand lblEnd       = Label();

                    context.BranchIfTrue(lblBigEndian, GetFlag(PState.EFlag));

                    Operand leResult = context.BitwiseOr(lo, context.ShiftLeft(hi, Const(32)));
                    Operand leS      = EmitStoreExclusive(context, address, leResult, exclusive, size);
                    if (exclusive)
                    {
                        SetIntA32(context, op.Rd, leS);
                    }

                    context.Branch(lblEnd);

                    context.MarkLabel(lblBigEndian);

                    Operand beResult = context.BitwiseOr(hi, context.ShiftLeft(lo, Const(32)));
                    Operand beS      = EmitStoreExclusive(context, address, beResult, exclusive, size);
                    if (exclusive)
                    {
                        SetIntA32(context, op.Rd, beS);
                    }

                    context.MarkLabel(lblEnd);
                }
                else
                {
                    Operand s = EmitStoreExclusive(context, address, context.ZeroExtend32(OperandType.I64, GetIntA32(context, op.Rt)), exclusive, size);
                    // This is only needed for exclusive stores. The function returns 0
                    // when the store is successful, and 1 otherwise.
                    if (exclusive)
                    {
                        SetIntA32(context, op.Rd, s);
                    }
                }
            }
        }
예제 #48
0
        public void InvokeTableItemSetAccessMember(Authentication authentication, ITableItem tableItem, AccessInfo accessInfo, string memberID, AccessType accessType)
        {
            this.CremaHost.DebugMethod(authentication, this, nameof(InvokeTableItemSetAccessMember), tableItem, memberID, accessType);
            var accessInfoPath = tableItem.GetAccessInfoPath();

            try
            {
                accessInfo.Set(authentication.SignatureDate, memberID, accessType);
                tableItem.WriteAccessInfo(accessInfoPath, accessInfo);
            }
            catch (Exception e)
            {
                this.CremaHost.Error(e);
                this.repository.Revert();
                throw e;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                #region Script Resource

                ScriptReference scriptReference = new ScriptReference();
                scriptReference.Path = ConfigurationManager.AppSettings["MaintJsPath"].ToString().TrimEnd('/') + "/ScriptResources/MeasurementDocumentScriptResource.js";
                string[] cultures = ConfigurationManager.AppSettings["SupportLanguages"].ToString().Split(',');
                scriptReference.ResourceUICultures = CommonBLL.GetCultures(cultures, scriptReference.Path);
                scriptManager.Scripts.Add(scriptReference);

                #endregion

                int siteID = CommonBLL.ValidateSiteID(Request);
                if (siteID == 0)
                {
                    Response.Redirect(ConfigurationManager.AppSettings["NoAccessPage"].ToString());
                }

                //if loading page in edit mode
                int maintScheduleID = 0;
                if (Request.QueryString["maintscheduleid"] != null && Request.QueryString["maintscheduleid"].Trim().Length > 0)
                {
                    maintScheduleID = Convert.ToInt32(Request.QueryString["maintscheduleid"].ToString().Trim());
                }

                if (maintScheduleID > 0)
                {
                    btnAdd.Text = "Update";
                }

                int  userID          = this.CurrentUser.UserID;
                int  accessLevelID   = CommonBLL.GetAccessLevelID(this.CurrentUser.AccessLevel);
                bool hasDeleteAccess = false;
                bool hasEditAccess   = false;

                AccessType accessType = ValidateUserPrivileges(siteID, accessLevelID);

                if (accessType == AccessType.FULL_ACCESS)
                {
                    hasDeleteAccess = true;
                }
                if (accessType == AccessType.FULL_ACCESS || accessType == AccessType.EDIT_ONLY)
                {
                    hasEditAccess = true;
                }

                if (accessType == AccessType.FULL_ACCESS || (maintScheduleID > 0 && accessType == AccessType.EDIT_ONLY))
                {
                    btnAdd.Attributes.Add("onclick", "javascript:AddUpdateMeasurementDocument();return false;");
                }
                else
                {
                    btnAdd.Attributes.Add("disabled", "disabled");
                }

                if (accessType == AccessType.FULL_ACCESS)
                {
                    btnActivateSchedule.Attributes.Add("onclick", "javascript:ActivateScheduleInfoCinfirm();return false;");
                }
                else
                {
                    btnActivateSchedule.Attributes.Add("disabled", "disabled");
                }

                string basePath       = ConfigurationManager.AppSettings["MaintBasePath"].ToString().TrimEnd('/');
                string webServicePath = ConfigurationManager.AppSettings["MaintWebServicePath"].Trim();

                //using pager for displaying maintenance types in configure maintenance types modal popup
                UserControls.PagerData measPointPagerData = new UserControls.PagerData();
                measPointPagerData.PageIndex        = 0;
                measPointPagerData.PageSize         = int.Parse(hdnPageSize.Value.ToString());
                measPointPagerData.SelectMethod     = "LoadAvailableMeasuringPoints";
                measPointPagerData.ServicePath      = webServicePath;
                measPointPagerData.SiteID           = siteID;
                measPointPagerData.UserID           = userID;
                measPointPagerData.AccessLevelID    = accessLevelID;
                measPointPagerData.LoadControlID    = btnAdd.ClientID;
                measPointPagerData.PageAccessRights = accessType.ToString();


                thAMFLocName.Attributes.Add("onclick", "javascript:SortMeasuringPointsTabs('" + thAMFLocName.ClientID + "','FLocationName'," + (new JavaScriptSerializer()).Serialize(true) + ");");
                thAMEquipment.Attributes.Add("onclick", "javascript:SortMeasuringPointsTabs('" + thAMEquipment.ClientID + "','Equipment'," + (new JavaScriptSerializer()).Serialize(true) + ");");
                thAMMeasPoint.Attributes.Add("onclick", "javascript:SortMeasuringPointsTabs('" + thAMMeasPoint.ClientID + "','MeasuringPoint'," + (new JavaScriptSerializer()).Serialize(true) + ");");
                thAMCategory.Attributes.Add("onclick", "javascript:SortMeasuringPointsTabs('" + thAMCategory.ClientID + "','Category'," + (new JavaScriptSerializer()).Serialize(true) + ");");

                thSMFLocName.Attributes.Add("onclick", "javascript:SortMeasuringPointsTabs('" + thSMFLocName.ClientID + "','FLocationName'," + (new JavaScriptSerializer()).Serialize(false) + ");");
                thSMEquipment.Attributes.Add("onclick", "javascript:SortMeasuringPointsTabs('" + thSMEquipment.ClientID + "','Equipment'," + (new JavaScriptSerializer()).Serialize(false) + ");");
                thSMMeasPoint.Attributes.Add("onclick", "javascript:SortMeasuringPointsTabs('" + thSMMeasPoint.ClientID + "','MeasuringPoint'," + (new JavaScriptSerializer()).Serialize(false) + ");");
                thSMCategory.Attributes.Add("onclick", "javascript:SortMeasuringPointsTabs('" + thSMCategory.ClientID + "','Category'," + (new JavaScriptSerializer()).Serialize(false) + ");");

                ScriptManager.RegisterStartupScript(this, this.GetType(), "InitMeasurementDocumentInfo", "javascript:InitMeasurementDocumentInfo(" + (new JavaScriptSerializer()).Serialize(measPointPagerData) + ",'" + basePath + "','" + maintScheduleID + "','" + hasDeleteAccess + "','" + hasEditAccess + "');", true);
            }
        }
예제 #50
0
 public RoleRequired(AccessType access)
 {
     AccessType = access;
 }
예제 #51
0
파일: Group.cs 프로젝트: cmqd/coflows-quant
 public static List <Group> Groups(IPermissible permissible, AccessType type)
 {
     return(Factory.Groups(User.CurrentUser, permissible, type));
 }
예제 #52
0
파일: TableBase.cs 프로젝트: MutesK/Crema
        public override void OnValidateSetAccessMember(IAuthentication authentication, object target, string memberID, AccessType accessType)
        {
            base.OnValidateSetAccessMember(authentication, target, memberID, accessType);

            foreach (var item in this.Childs)
            {
                item.OnValidateSetAccessMember(authentication, target, memberID, accessType);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                #region Script_Resource_Refernce
                ScriptReference scriptReference = new ScriptReference();
                scriptReference.Path = ConfigurationManager.AppSettings["MaintJsPath"].ToString().TrimEnd('/') + "/ScriptResources/DynamicGridScriptResource.js";
                string[] cultures = ConfigurationManager.AppSettings["SupportLanguages"].ToString().Split(',');
                scriptReference.ResourceUICultures = CommonBLL.GetCultures(cultures, scriptReference.Path);
                ScriptManager1.Scripts.Add(scriptReference);

                scriptReference      = new ScriptReference();
                scriptReference.Path = ConfigurationManager.AppSettings["MaintJsPath"].ToString().TrimEnd('/') + "/ScriptResources/NotificationScriptResource.js";
                scriptReference.ResourceUICultures = CommonBLL.GetCultures(cultures, scriptReference.Path);
                ScriptManager1.Scripts.Add(scriptReference);
                #endregion

                userID        = this.CurrentUser.UserID;
                siteID        = this.CurrentUser.SiteID;
                accessLevelID = CommonBLL.GetAccessLevelID(this.CurrentUser.AccessLevel);

                AccessType accessType = ValidateUserPrivileges(siteID, accessLevelID);

                Vegam_MaintenanceService.BasicParam basicParam = new Vegam_MaintenanceService.BasicParam();
                basicParam.SiteID = siteID;
                basicParam.UserID = userID;

                string usercontrolPath = ConfigurationManager.AppSettings["MaintUserControls"].ToString().TrimEnd('/');
                string webServicePath  = ConfigurationManager.AppSettings["MaintWebServicePath"].ToString().TrimEnd('/');
                string basePath        = ConfigurationManager.AppSettings["MaintBasePath"].ToString().TrimEnd('/');


                SiteDateTimeFormatInfo dateTimeForamt = BLL.MaintenanceBLL.GetSiteDateTimeFormatInfo(siteID);

                UserControls.DynamicGridControl dynamicGridControl = (UserControls.DynamicGridControl)Page.LoadControl(usercontrolPath + "/DynamicGridControl.ascx");
                divDynamicGridContent.Controls.Add(dynamicGridControl);

                #region Feature Equipment Model

                List <string> featureName = new List <string>();
                featureName.Add(Language_Resources.MaintenanceFeatures.manageNotification);

                int featureID = 0;
                List <ipas_UserService.SiteFeatureInfo> featurePageToLoad = BLL.UserBLL.GetCompanyFeatureConfiguredURL(siteID, 0, featureName);
                if (featurePageToLoad.Count > 0)
                {
                    ipas_UserService.SiteFeatureInfo result = featurePageToLoad.SingleOrDefault(x => x.FeatureName == Language_Resources.MaintenanceFeatures.manageNotification);
                    if (result != null)
                    {
                        featureID = result.FeatureID;
                    }
                }
                #endregion

                UserControls.PagerData pagerData = new UserControls.PagerData();
                pagerData.PageIndex        = 0;
                pagerData.PageSize         = int.Parse(hdnPageSize.Value.ToString());
                pagerData.CurrentPage      = currentPage;
                pagerData.ServicePath      = webServicePath;
                pagerData.SelectMethod     = "LoadDynamicGridContent";
                pagerData.LoadControlID    = divDynamicGridContent.ClientID;
                pagerData.SiteID           = siteID;
                pagerData.UserID           = userID;
                pagerData.AccessLevelID    = accessLevelID;
                pagerData.PlantDateFormat  = dateTimeForamt.DateFormat;
                pagerData.PlantTimeFormat  = dateTimeForamt.TimeFormat;
                pagerData.PageAccessRights = accessType.ToString();

                UserControls.DynamicGridProperties dynamicGridProperties = new UserControls.DynamicGridProperties();
                dynamicGridProperties.GridType         = UserControls.DynamicGridType.Table;
                dynamicGridProperties.FeatureID        = featureID;
                dynamicGridProperties.DatePickerFormat = CommonBLL.GetDatePickerDateFormat(dateTimeForamt.DateFormat);
                dynamicGridProperties.TableHeaderText  = Language_Resources.ManageNotification_Resource.listOfNotification;
                dynamicGridProperties.ImagePath        = ConfigurationManager.AppSettings["MaintImagePath"].TrimEnd('/') + "/Styles/Images";
                dynamicGridProperties.PagerData        = pagerData;
                dynamicGridProperties.WebServiceName   = "Vegam_MaintenanceService.asmx";
                dynamicGridProperties.ExcelSheetName   = "NotificationlList";

                string addNotificationHtml = string.Empty;
                if (accessType == AccessType.FULL_ACCESS)
                {
                    addNotificationHtml = "<input id='btnAddNewNotification' type='button' class='btn btn-sm btn-success pull-xs-right pover' data-placement='top' data-content='" + Language_Resources.ManageNotification_Resource.addEditNotificationInfo + "' value='" + Language_Resources.ManageNotification_Resource.addEditNotificationInfo + "' onclick='javascript:AddNewNotification();return false;'/>";
                }
                else
                {
                    addNotificationHtml = "<input id='btnAddNewNotification' type='button' class='btn btn-sm btn-success pull-xs-right' value='" + Language_Resources.ManageNotification_Resource.addEditNotificationInfo + "' disabled/>";
                }

                Page.ClientScript.RegisterStartupScript(GetType(), "LoadNotificationInfo", "LoadNotificationInfo(" + (new JavaScriptSerializer()).Serialize(dynamicGridProperties) + ",'" + basePath + "',\"" + addNotificationHtml + "\")", true);
            }
        }
예제 #54
0
        /// <summary>
        /// Encode the sector tailer access type for a specific block
        /// </summary>
        /// <param name="blockNumber">The block sector to encode</param>
        /// <param name="accessType">The access type to encode</param>
        /// <returns>The encoded sector tailer for the specific block</returns>
        public (byte B6, byte B7, byte B8) EncodeSectorTailer(byte blockNumber, AccessType accessType)
        {
            blockNumber = (byte)(blockNumber % 4);

            byte c1 = 0;
            byte c2 = 0;
            byte c3 = 0;

            if (accessType == (AccessType.ReadKeyA | AccessType.ReadKeyB | AccessType.WriteKeyA | AccessType.WriteKeyB |
                               AccessType.IncrementKeyA | AccessType.IncrementKeyB |
                               AccessType.DecrementTransferRestoreKeyA | AccessType.DecrementTransferRestoreKeyB))
            {
                c1 = 0;
                c2 = 0;
                c3 = 0;
            }

            if (accessType == (AccessType.ReadKeyA | AccessType.ReadKeyB))
            {
                c1 = 0;
                c2 = 1;
                c3 = 0;
            }

            if (accessType == (AccessType.ReadKeyA | AccessType.ReadKeyB | AccessType.WriteKeyB))
            {
                c1 = 1;
                c2 = 0;
                c3 = 0;
            }

            if (accessType == (AccessType.ReadKeyA | AccessType.ReadKeyB | AccessType.WriteKeyB |
                               AccessType.IncrementKeyB |
                               AccessType.DecrementTransferRestoreKeyA | AccessType.DecrementTransferRestoreKeyB))
            {
                c1 = 1;
                c2 = 1;
                c3 = 0;
            }

            if (accessType == (AccessType.ReadKeyA | AccessType.ReadKeyB |
                               AccessType.DecrementTransferRestoreKeyA | AccessType.DecrementTransferRestoreKeyB))
            {
                c1 = 0;
                c2 = 0;
                c3 = 1;
            }

            if (accessType == (AccessType.ReadKeyB | AccessType.WriteKeyB))
            {
                c1 = 0;
                c2 = 1;
                c3 = 1;
            }

            if (accessType == AccessType.ReadKeyB)
            {
                c1 = 1;
                c2 = 0;
                c3 = 1;
            }

            if (accessType == AccessType.None)
            {
                c1 = 1;
                c2 = 1;
                c3 = 1;
            }

            // Encore the access bits
            byte b6 = (byte)((((~c2) & 0x01) << (4 + blockNumber)) | (((~c1) & 0x01) << blockNumber));
            byte b7 = (byte)(((c1) << (4 + blockNumber)) | (((~c3) & 0x01) << blockNumber));
            byte b8 = (byte)(((c3) << (4 + blockNumber)) | ((c2) << blockNumber));

            return(b6, b7, b8);
        }
예제 #55
0
        void GetProtocolData(object DataObject)
        {
            //Data container from protocol
            ProtocolDataContainer dataContainer = (ProtocolDataContainer)DataObject;
            //Some data from protocol
            object data = dataContainer.Data;

            //Check Protocol name
            if (dataContainer.ProtocolName != "PulsePLCv2" || data == null)
            {
                return;
            }
            PulsePLCv2Protocol.Commands cmd = (PulsePLCv2Protocol.Commands)dataContainer.CommandCode;

            if (cmd == PulsePLCv2Protocol.Commands.Search_Devices)
            {
                Main_VM.SerialNumList.Clear();
                ((List <string>)data).ForEach(str => Main_VM.SerialNumList.Add(str));
                if (Main_VM.SerialNumList.Count > 0)
                {
                    //Проверим есть ли выбранный серийник в списке
                    bool exsistInList = false;
                    foreach (var item in Main_VM.SerialNumList)
                    {
                        if (item.Substring(0, 8) == Main_VM.Device.Serial_View)
                        {
                            exsistInList = true;
                        }
                    }
                    //Если нет в списке, то делаем текущим первый номер из списка
                    if (!exsistInList)
                    {
                        Main_VM.Device.Serial_View = Main_VM.SerialNumList[0];
                    }
                }
            }
            if (cmd == PulsePLCv2Protocol.Commands.Check_Pass)
            {
                AccessType access = (AccessType)data;
                //Отобразить во View
                //
            }
            if (cmd == PulsePLCv2Protocol.Commands.Read_Main_Params)
            {
                DeviceMainParams device = (DeviceMainParams)data;
                //Версии
                Main_VM.Device.VersionFirmware = device.VersionFirmware;
                Main_VM.Device.VersionEEPROM   = device.VersionEEPROM;
                //Режимы работы
                Main_VM.Device.WorkMode           = device.WorkMode;
                Main_VM.Device.BatteryMode        = device.BatteryMode;
                Main_VM.Device.RS485_WorkMode     = device.RS485_WorkMode;
                Main_VM.Device.Bluetooth_WorkMode = device.Bluetooth_WorkMode;
                //Ошибки
                Main_VM.Device.ErrorsByte = device.ErrorsByte;
                //Покрасим пункт меню в зеленый
                //
            }
            if (cmd == PulsePLCv2Protocol.Commands.Read_IMP)
            {
                if (((ImpParams)data).Num == ImpNum.IMP1)
                {
                    Main_VM.Imp1 = (ImpParams)data;
                }
                else
                {
                    Main_VM.Imp2 = (ImpParams)data;
                }
            }
            if (cmd == PulsePLCv2Protocol.Commands.Read_IMP_extra)
            {
                if (((ImpExParams)data).Num == ImpNum.IMP1)
                {
                    Main_VM.Imp1Ex = (ImpExParams)data;
                }
                else
                {
                    Main_VM.Imp2Ex = (ImpExParams)data;
                }
            }
            if (cmd == PulsePLCv2Protocol.Commands.Read_DateTime)
            {
                Main_VM.Device.DeviceDateTime = (DateTime)data;
            }
            if (cmd == PulsePLCv2Protocol.Commands.Read_PLC_Table_En)
            {
                List <DataGridRow_PLC> rows = (List <DataGridRow_PLC>)data;
                PLCTable_VM.TablePLC.ToList().ForEach(item => item.IsEnable = false);
                foreach (var item in rows)
                {
                    PLCTable_VM.TablePLC[item.Adrs_PLC - 1].IsEnable = true;
                }
                var rowsToRead = rows.Split(10); //Divide into groups of 10 item
                //Send requests for data
                rowsToRead.ForEach(r => {
                    if (r.Count > 0)
                    {
                        CommandManager.Add_CMD(LinkManager.Link, Protocol, PulsePLCv2Protocol.Commands.Read_PLC_Table, r, 0);
                    }
                });
                CommandManager.Add_CMD(LinkManager.Link, Protocol, PulsePLCv2Protocol.Commands.Close_Session, null, 0);
            }
            if (cmd == PulsePLCv2Protocol.Commands.Read_PLC_Table)
            {
                var rows = (List <DataGridRow_PLC>)data;
                foreach (var item in rows)
                {
                    PLCTable_VM.TablePLC[item.Adrs_PLC - 1] = item;
                }
            }
            if (cmd == PulsePLCv2Protocol.Commands.Read_E_Current)
            {
                var row = (DataGridRow_PLC)data;
                PLCTable_VM.TablePLC[row.Adrs_PLC - 1].E_Current = row.E_Current;
            }
            if (cmd == PulsePLCv2Protocol.Commands.Read_E_Start_Day)
            {
                var row = (DataGridRow_PLC)data;
                PLCTable_VM.TablePLC[row.Adrs_PLC - 1].E_StartDay = row.E_StartDay;
            }
            if (cmd == PulsePLCv2Protocol.Commands.Read_Journal)
            {
                var journal = (JournalForProtocol)data;
                switch (journal.Type)
                {
                case Journal_type.POWER:
                    Main_VM.JournalPower.Clear();
                    journal.Events.ForEach(row => Main_VM.JournalPower.Add(row));
                    break;

                case Journal_type.CONFIG:
                    Main_VM.JournalConfig.Clear();
                    journal.Events.ForEach(row => Main_VM.JournalConfig.Add(row));
                    break;

                case Journal_type.INTERFACES:
                    Main_VM.JournalInterfaces.Clear();
                    journal.Events.ForEach(row => Main_VM.JournalInterfaces.Add(row));
                    break;

                case Journal_type.REQUESTS:
                    Main_VM.JournalRequestsPLC.Clear();
                    journal.Events.ForEach(row => Main_VM.JournalRequestsPLC.Add(row));
                    break;

                default:
                    break;
                }
            }
        }
예제 #56
0
 public RoleRequired()
 {
     AccessType = AccessType.Upper;
 }
예제 #57
0
        public void LoadData()
        {
            if (BaseObjectMgr == null)
            {
                return;
            }
            if (dataGridView.Columns.Count == 0)
            {
                return;
            }
            dataGridView.Rows.Clear();

            //检查权限
            if (!CheckAccess())
            {
                return;
            }

            m_TempViewFilterMgr.IsLoad = true;//避免临时数据从数据库装载
            List <CBaseObject> lstObj = BaseObjectMgr.FilterByView(View, m_TempViewFilterMgr);

            if (lstObj.Count == 0)
            {
                return;
            }
            dataGridView.Rows.Add(lstObj.Count);
            int nRowIdx = 0;

            foreach (CBaseObject obj in lstObj)
            {
                DataGridViewRow row = dataGridView.Rows[nRowIdx];
                row.Tag = obj;
                foreach (DataGridViewColumn column in dataGridView.Columns)
                {
                    //工作流
                    if (column.Name.Equals("workflow"))
                    {
                        continue;
                    }
                    //

                    CColumn col = (CColumn)column.Tag;
                    //判断禁止权限字段
                    if (m_sortRestrictColumnAccessType.ContainsKey(col.Id))
                    {
                        AccessType accessType = m_sortRestrictColumnAccessType[col.Id];
                        if (accessType == AccessType.forbide)
                        {
                            continue;
                        }
                    }
                    //
                    if (col.ColType == ColumnType.object_type)
                    {
                        if (obj.GetColValue(col) != null)
                        {
                            row.Cells[column.Name].Value = "long byte";
                        }
                    }
                    else if (col.ColType == ColumnType.ref_type)
                    {
                        CTable table = (CTable)Program.Ctx.TableMgr.Find(col.RefTable);
                        if (table == null)
                        {
                            continue;
                        }
                        CColumn RefCol     = (CColumn)table.ColumnMgr.Find(col.RefCol);
                        CColumn RefShowCol = (CColumn)table.ColumnMgr.Find(col.RefShowCol);
                        object  objVal     = obj.GetColValue(col);


                        Guid guidParentId = Guid.Empty;
                        if (BaseObjectMgr.m_Parent != null && BaseObjectMgr.m_Parent.Id == (Guid)objVal)
                        {
                            row.Cells[column.Name].Value = BaseObjectMgr.m_Parent.GetColValue(RefShowCol);
                        }
                        else
                        {
                            CBaseObjectMgr objMgr = Program.Ctx.FindBaseObjectMgrCache(table.Code, Guid.Empty);
                            if (objMgr != null)
                            {
                                CBaseObject objCache = objMgr.FindByValue(RefCol, objVal);
                                if (objCache != null)
                                {
                                    row.Cells[column.Name].Value = objCache.GetColValue(RefShowCol);
                                }
                            }
                            else
                            {
                                objMgr        = new CBaseObjectMgr();
                                objMgr.TbCode = table.Code;
                                objMgr.Ctx    = Program.Ctx;

                                string             sWhere   = string.Format(" {0}=?", RefCol.Code);
                                List <DbParameter> cmdParas = new List <DbParameter>();
                                cmdParas.Add(new DbParameter(RefCol.Code, obj.GetColValue(col)));
                                List <CBaseObject> lstObj2 = objMgr.GetList(sWhere, cmdParas);
                                if (lstObj2.Count > 0)
                                {
                                    CBaseObject obj2 = lstObj2[0];
                                    row.Cells[column.Name].Value = obj2.GetColValue(RefShowCol);
                                }
                            }
                        }
                    }
                    else
                    {
                        row.Cells[column.Name].Value = obj.GetColValue(col);
                    }
                }
                UpdateRowWorkflow(row);

                nRowIdx++;
            }
        }
예제 #58
0
 public void InvokeTableItemSetAccessMember(Authentication authentication, ITableItem tableItem, AccessInfo accessInfo, string memberID, AccessType accessType)
 {
     this.CremaHost.DebugMethod(authentication, this, nameof(InvokeTableItemSetAccessMember), tableItem, memberID, accessType);
 }
    void GetData()
    {
        int page     = Convert.ToInt32(Request.Params["page"]);
        int pageSize = Convert.ToInt32(Request.Params["pagesize"]);

        CBaseObjectMgr BaseObjectMgr = Global.GetCtx(Session["TopCompany"].ToString()).FindBaseObjectMgrCache(m_Table.Code, m_guidParentId);

        if (BaseObjectMgr == null)
        {
            BaseObjectMgr        = new CBaseObjectMgr();
            BaseObjectMgr.TbCode = m_Table.Code;
            BaseObjectMgr.Ctx    = Global.GetCtx(Session["TopCompany"].ToString());
        }

        string             sData = "";
        List <CBaseObject> lstObj;

        if (Request["Filter"] == null || Session["ViewFilterMgr"] == null)
        {
            lstObj = BaseObjectMgr.FilterByView(m_View);
            //清空过滤条件
            Session["ViewFilterMgr"] = null;
        }
        else
        {
            //过滤查询
            SortedList <Guid, CViewFilterMgr> sortObj = (SortedList <Guid, CViewFilterMgr>)Session["ViewFilterMgr"];
            if (sortObj.ContainsKey(m_View.Id))
            {
                CViewFilterMgr ViewFilterMgr = sortObj[m_View.Id];
                lstObj = BaseObjectMgr.FilterByView(m_View, ViewFilterMgr);
            }
            else
            {
                lstObj = BaseObjectMgr.FilterByView(m_View);
            }
        }

        int totalPage = lstObj.Count % pageSize == 0 ? lstObj.Count / pageSize : lstObj.Count / pageSize + 1; // 计算总页数

        int index = (page - 1) * pageSize;                                                                    // 开始记录数

        for (int i = index; i < pageSize + index && i < lstObj.Count; i++)
        {
            CBaseObject obj = (CBaseObject)lstObj[i];

            string sRow = "";
            foreach (CBaseObject objC in m_Table.ColumnMgr.GetList())
            {
                CColumn col = (CColumn)objC;
                //判断禁止权限字段
                if (m_sortRestrictColumnAccessType.ContainsKey(col.Id))
                {
                    AccessType accessType = m_sortRestrictColumnAccessType[col.Id];
                    if (accessType == AccessType.forbide)
                    {
                        string sVal = "";
                        sRow += string.Format("\"{0}\":\"{1}\",", col.Code, sVal);
                        continue;
                    }
                }
                //

                if (col.ColType == ColumnType.object_type)
                {
                    string sVal = "";
                    if (obj.GetColValue(col) != null)
                    {
                        sVal = "long byte";
                    }
                    sRow += string.Format("\"{0}\":\"{1}\",", col.Code, sVal);
                }
                else if (col.ColType == ColumnType.ref_type)
                {
                    CTable RefTable = (CTable)Global.GetCtx(Session["TopCompany"].ToString()).TableMgr.Find(col.RefTable);
                    if (RefTable == null)
                    {
                        continue;
                    }
                    CColumn RefCol     = (CColumn)RefTable.ColumnMgr.Find(col.RefCol);
                    CColumn RefShowCol = (CColumn)RefTable.ColumnMgr.Find(col.RefShowCol);
                    object  objVal     = obj.GetColValue(col);


                    string sVal         = "";
                    Guid   guidParentId = Guid.Empty;
                    if (BaseObjectMgr.m_Parent != null && BaseObjectMgr.m_Parent.Id == (Guid)objVal)
                    {
                        object objVal2 = BaseObjectMgr.m_Parent.GetColValue(RefShowCol);
                        if (objVal2 != null)
                        {
                            sVal = objVal2.ToString();
                        }
                    }
                    else
                    {
                        CBaseObjectMgr objRefMgr = Global.GetCtx(Session["TopCompany"].ToString()).FindBaseObjectMgrCache(RefTable.Code, guidParentId);
                        if (objRefMgr != null)
                        {
                            CBaseObject objCache = objRefMgr.FindByValue(RefCol, objVal);
                            if (objCache != null)
                            {
                                object objVal2 = objCache.GetColValue(RefShowCol);
                                if (objVal2 != null)
                                {
                                    sVal = objVal2.ToString();
                                }
                            }
                        }
                        else
                        {
                            objRefMgr        = new CBaseObjectMgr();
                            objRefMgr.TbCode = RefTable.Code;
                            objRefMgr.Ctx    = Global.GetCtx(Session["TopCompany"].ToString());

                            string             sWhere   = string.Format(" {0}=?", RefCol.Code);
                            List <DbParameter> cmdParas = new List <DbParameter>();
                            cmdParas.Add(new DbParameter(RefCol.Code, obj.GetColValue(col)));
                            List <CBaseObject> lstObj2 = objRefMgr.GetList(sWhere, cmdParas);
                            if (lstObj2.Count > 0)
                            {
                                CBaseObject obj2    = lstObj2[0];
                                object      objVal2 = obj2.GetColValue(RefShowCol);
                                if (objVal2 != null)
                                {
                                    sVal = objVal2.ToString();
                                }
                            }
                        }
                    }
                    sRow += string.Format("\"{0}\":\"{1}\",", col.Code, sVal);
                }
                else
                {
                    string sVal   = "";
                    object objVal = obj.GetColValue(col);
                    if (objVal != null)
                    {
                        sVal = objVal.ToString();
                    }
                    //转义特殊字符
                    Util.ConvertJsonSymbol(ref sVal);
                    sRow += string.Format("\"{0}\":\"{1}\",", col.Code, sVal);
                }
            }
            sRow   = sRow.TrimEnd(",".ToCharArray());
            sRow   = "{" + sRow + "},";
            sData += sRow;
        }
        sData = sData.TrimEnd(",".ToCharArray());
        sData = "[" + sData + "]";
        string sJson = string.Format("{{\"Rows\":{0},\"Total\":\"{1}\"}}"
                                     , sData, lstObj.Count);

        Response.Write(sJson);
    }
예제 #60
0
파일: OpUser.cs 프로젝트: nandub/DeOps
        public static void CreateNew(string path, string opName, string userName, string password, AccessType access, byte[] opKey, bool globalIM)
        {
            OpUser user = new OpUser(path, password);

            user.Settings.Operation = opName;
            user.Settings.UserName  = userName;
            user.Settings.KeyPair   = new RSACryptoServiceProvider(1024);
            user.Settings.FileKey   = Utilities.GenerateKey(new RNGCryptoServiceProvider(), 256);
            user.Settings.OpAccess  = access;
            user.Settings.Security  = SecurityLevel.Medium;
            user.Settings.GlobalIM  = globalIM;

            // joining/creating public
            if (access == AccessType.Public)
            {
                // 256 bit rijn

                SHA256Managed sha256 = new SHA256Managed();
                user.Settings.OpKey    = sha256.ComputeHash(UTF8Encoding.UTF8.GetBytes(opName.ToLowerInvariant()));
                user.Settings.Security = SecurityLevel.Low;
            }

            // invite to private/secret
            else if (opKey != null)
            {
                user.Settings.OpKey = opKey;
            }

            // creating private/secret
            else if (globalIM)
            {
                user.Settings.OpKey = DhtNetwork.GlobalIMKey;
            }

            else
            {
                user.Settings.OpKey = Utilities.GenerateKey(new RNGCryptoServiceProvider(), 256);
            }

            user.Save();

            // throws exception on failure
        }