public BaseRole(string sName, string sID, string sPath, AccessRights AccessRights) { _sName = sName; _sID = sID; _sPath = sPath; _AccessRight = AccessRights; }
public IotHubConnection(IotHubConnectionString connectionString, AccessRights accessRights) { this.connectionString = connectionString; this.accessRights = accessRights; this.faultTolerantSession = new FaultTolerantAmqpObject<AmqpSession>(this.CreateSessionAsync, this.CloseConnection); this.refreshTokenTimer = new IOThreadTimer(s => ((IotHubConnection)s).OnRefreshToken(), this, false); }
/// <summary> /// Initializes a new instance of the <see cref="MailKit.AccessControl"/> class. /// </summary> /// <remarks> /// Creates a new <see cref="MailKit.AccessControl"/> with the given name and /// access rights. /// </remarks> /// <param name="name">The identifier name.</param> /// <param name="rights">The access rights.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="name"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="rights"/> is <c>null</c>.</para> /// </exception> public AccessControl (string name, string rights) { if (name == null) throw new ArgumentNullException (nameof (name)); Rights = new AccessRights (rights); Name = name; }
public ServiceBusQueueListenerFactory(ServiceBusAccount account, string queueName, ITriggeredFunctionExecutor executor, AccessRights accessRights) { _namespaceManager = account.NamespaceManager; _messagingFactory = account.MessagingFactory; _queueName = queueName; _executor = executor; _accessRights = accessRights; }
public VKApiManager(int appId, AccessRights rights, bool xmlNeeded = true) { AuthorizationDetails details = new AuthorizationDetails(); details.appId = appId; details.rights = rights; IsXmlResponseNeeded = xmlNeeded; status = Init(details); }
/// <summary> /// Initializes a new instance of the <see cref="MailKit.AccessControl"/> class. /// </summary> /// <remarks> /// Creates a new <see cref="MailKit.AccessControl"/> with the given name and /// access rights. /// </remarks> /// <param name="name">The identifier name.</param> /// <param name="rights">The access rights.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="name"/> is <c>null</c>. /// </exception> public AccessControl (string name, IEnumerable<AccessRight> rights) { if (name == null) throw new ArgumentNullException ("name"); Rights = new AccessRights (rights); Name = name; }
public async Task CreateAsync_AccessRightsNotManage_DoesNotCreateTopicOrSubscription(AccessRights accessRights) { ServiceBusAccount account = new ServiceBusAccount(); Mock<ITriggeredFunctionExecutor> mockExecutor = new Mock<ITriggeredFunctionExecutor>(MockBehavior.Strict); ServiceBusSubscriptionListenerFactory factory = new ServiceBusSubscriptionListenerFactory(account, "testtopic", "testsubscription", mockExecutor.Object, accessRights, new ServiceBusConfiguration()); IListener listener = await factory.CreateAsync(CancellationToken.None); Assert.NotNull(listener); }
//Deserialization constructor. public BaseRole(SerializationInfo info, StreamingContext ctxt) { //Get the values from info and assign them to the appropriate properties _sName = (string)info.GetValue("Name", typeof(string)); _sID = (string)info.GetValue("ID", typeof(string)); _sPath = (string)info.GetValue("Path", typeof(string)); _AccessRight = (AccessRights)info.GetValue("AccessRight", typeof(AccessRights)); }
public async Task CreateAsync_AccessRightsNotManage_DoesNotCreateQueue(AccessRights accessRights) { ServiceBusAccount account = new ServiceBusAccount(); Mock<ITriggeredFunctionExecutor> mockExecutor = new Mock<ITriggeredFunctionExecutor>(MockBehavior.Strict); ServiceBusQueueListenerFactory factory = new ServiceBusQueueListenerFactory(account, "testqueue", mockExecutor.Object, accessRights); IListener listener = await factory.CreateAsync(CancellationToken.None); Assert.NotNull(listener); }
public ServiceBusSubscriptionListenerFactory(ServiceBusAccount account, string topicName, string subscriptionName, ITriggeredFunctionExecutor executor, AccessRights accessRights) { _namespaceManager = account.NamespaceManager; _messagingFactory = account.MessagingFactory; _topicName = topicName; _subscriptionName = subscriptionName; _executor = executor; _accessRights = accessRights; }
public ServiceBusBinding(string parameterName, IArgumentBinding<ServiceBusEntity> argumentBinding, ServiceBusAccount account, IBindableServiceBusPath path, AccessRights accessRights) { _parameterName = parameterName; _argumentBinding = argumentBinding; _account = account; _namespaceName = ServiceBusClient.GetNamespaceName(account); _path = path; _accessRights = accessRights; _converter = CreateConverter(account, path, accessRights); }
/// <summary> /// Констуктор по умолчанию. /// </summary> public AuthorizationDetails() { appId = -1; secureKey = String.Empty; rights = AccessRights.NO_RIGHTS; userId = -1; accessToken = String.Empty; expiresIn = -1; issuedTime = DateTime.MinValue; }
public ServiceBusTriggerBinding(string parameterName, ITriggerDataArgumentBinding<BrokeredMessage> argumentBinding, ServiceBusAccount account, string topicName, string subscriptionName, AccessRights accessRights) { _parameterName = parameterName; _argumentBinding = argumentBinding; _account = account; _namespaceName = ServiceBusClient.GetNamespaceName(account); _topicName = topicName; _subscriptionName = subscriptionName; _entityPath = SubscriptionClient.FormatSubscriptionPath(topicName, subscriptionName); _accessRights = accessRights; }
public ServiceBusTriggerBinding(string parameterName, Type parameterType, ITriggerDataArgumentBinding<BrokeredMessage> argumentBinding, ServiceBusAccount account, string queueName, AccessRights accessRights) { _parameterName = parameterName; _converter = CreateConverter(parameterType); _argumentBinding = argumentBinding; _account = account; _namespaceName = ServiceBusClient.GetNamespaceName(account); _queueName = queueName; _entityPath = queueName; _accessRights = accessRights; }
public VKApiManager(string appId, AccessRights rights, bool xmlNeeded = true) { AuthorizationDetails details = new AuthorizationDetails(); if (Int32.TryParse(appId, out details.appId)) { details.rights = rights; IsXmlResponseNeeded = xmlNeeded; status = Init(details); } else { status = false; } }
internal MemberWithAccess(IClrDeclaredElement declaredElement, AccessRights typeAccessRights, MemberType memberType, AccessRights memberAccessRights) { Contract.Requires(declaredElement != null); _declaredElement = declaredElement; MemberName = declaredElement.ShortName; TypeAccessRights = typeAccessRights; MemberType = memberType; _memberAccessRights = memberAccessRights; }
private void FixReferencedMemberAccess(AccessRights memberAccessRights) { var declaration = _highlighting.LessVisibleReferencedMember.DeclaredElement .GetDeclarations().FirstOrDefault(); Contract.Assert(declaration != null); ModifiersUtil.SetAccessRights( declaration, memberAccessRights); }
private void FixReferencedTypeAccess(AccessRights newTypeAccess) { var declaration = _highlighting.LessVisibleReferencedMember.DeclaredElement .With(x => x.GetContainingType()) .With(x => x.GetDeclarations().FirstOrDefault()); Contract.Assert(declaration != null); ModifiersUtil.SetAccessRights( declaration, newTypeAccess); }
public static string[] AccessRightsToStringArray(AccessRights accessRights) { var values = new List<string>(2); foreach (AccessRights right in Enum.GetValues(typeof(AccessRights))) { if (accessRights.HasFlag(right)) { values.Add(right.ToString()); } } return values.ToArray(); }
public static async Task SendAndCreateQueueIfNotExistsAsync(this MessageSender sender, BrokeredMessage message, Guid functionInstanceId, NamespaceManager namespaceManager, AccessRights accessRights, CancellationToken cancellationToken) { if (sender == null) { throw new ArgumentNullException("sender"); } else if (namespaceManager == null) { throw new ArgumentNullException("namespaceManager"); } ServiceBusCausalityHelper.EncodePayload(functionInstanceId, message); bool threwMessgingEntityNotFoundException = false; cancellationToken.ThrowIfCancellationRequested(); try { await sender.SendAsync(message); return; } catch (MessagingEntityNotFoundException) { if (accessRights != AccessRights.Manage) { // if we don't have the required rights to create the queue, // rethrow the exception throw; } threwMessgingEntityNotFoundException = true; } Debug.Assert(threwMessgingEntityNotFoundException); cancellationToken.ThrowIfCancellationRequested(); try { await namespaceManager.CreateQueueAsync(sender.Path); } catch (MessagingEntityAlreadyExistsException) { } // Clone the message because it was already consumed before (when trying to send) // otherwise, you get an exception message = message.Clone(); cancellationToken.ThrowIfCancellationRequested(); await sender.SendAsync(message); }
public byte[] ChannelCreatedMessage(int clientId, int serverId, EpicsType dataType, int dataCount, AccessRights access) { MemoryStream mem = new MemoryStream(); BinaryWriter writer = new BinaryWriter(mem); mem.Capacity = 32; writer.Write(((UInt16)CommandID.CA_PROTO_ACCESS_RIGHTS).ToByteArray()); writer.Write(new byte[6]); writer.Write(((UInt32)clientId).ToByteArray()); writer.Write(((UInt32)access).ToByteArray()); writer.Write(((UInt16)CommandID.CA_PROTO_CREATE_CHAN).ToByteArray()); if (dataCount > 30000) writer.Write(new byte[] { 0xFF, 0xFF }); else writer.Write(new byte[2]); writer.Write(((UInt16)dataType).ToByteArray()); if (dataCount > 30000) writer.Write(new byte[] { 0x00, 0x00 }); else writer.Write(((UInt16)dataCount).ToByteArray()); writer.Write(((UInt32)clientId).ToByteArray()); writer.Write(((UInt32)serverId).ToByteArray()); if (dataCount > 30000) { // Size writer.Write(((UInt32)0).ToByteArray()); // Data count writer.Write(((UInt32)dataCount).ToByteArray()); } byte[] buffer = mem.ToArray(); writer.Close(); mem.Dispose(); return buffer; }
public CAServerChannel(CAServer cAServer, int serverId, int clientId, string channelName, CATcpConnection tcpConnection) { // TODO: Complete member initialization this.Server = cAServer; this.ServerId = serverId; this.ClientId = clientId; this.ChannelName = channelName; this.TcpConnection = tcpConnection; tcpConnection.Closing += new EventHandler(tcpConnection_Closing); Property = "VAL"; if (channelName.Contains(".")) { string[] splitted = channelName.Split('.'); Record = Server.records[splitted[0]]; Property = splitted[1].ToUpper(); } else Record = Server.records[ChannelName]; if (!Record.CanBeRemotlySet) Access = AccessRights.ReadOnly; TcpConnection.Send(Server.Filter.ChannelCreatedMessage(ClientId, ServerId, FindType(Record), Record.dataCount, Access)); //TcpConnection.Send(Server.Filter.ChannelCreatedMessage(ClientId, ServerId, FindType(Record[Property].GetType()), Record.dataCount, Access)); }
private static extern IntPtr OpenProcess(AccessRights dwDesiredAccess, bool bInheritHandle, long dwProcessId);
internal static extern IntPtr CreateConsoleScreenBuffer(AccessRights desiredAccess, FileShare shareMode, IntPtr securityAttributes, ConsoleBufferMode bufferMode, IntPtr reserved);
/// <summary> /// Set the access rights for the specified identity. /// </summary> /// <remarks> /// Sets the access rights for the specified identity. /// </remarks> /// <param name="name">The identity name.</param> /// <param name="rights">The access rights.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="name"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="rights"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The <see cref="IMailStore"/> has been disposed. /// </exception> /// <exception cref="ServiceNotConnectedException"> /// The <see cref="IMailStore"/> is not connected. /// </exception> /// <exception cref="ServiceNotAuthenticatedException"> /// The <see cref="IMailStore"/> is not authenticated. /// </exception> /// <exception cref="System.NotSupportedException"> /// The mail store does not support the ACL extension. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="ProtocolException"> /// The server's response contained unexpected tokens. /// </exception> /// <exception cref="CommandException"> /// The command failed. /// </exception> public abstract void SetAccessRights (string name, AccessRights rights, CancellationToken cancellationToken = default (CancellationToken));
internal bool HasPermission(Entity entity, AccessRights access, EntityReference caller) { if (!SecurityRoles.Any(s => s.Value.Privileges.Any(p => p.Key == entity.LogicalName))) { // system has no security roles for this entity. Is a case with linkentities which have no security roles return(true); } if (caller.Id == Core.AdminUserRef.Id) { return(true); } var userRoles = GetSecurityRoles(caller)?.Where(r => r.Privileges.ContainsKey(entity.LogicalName) && r.Privileges[entity.LogicalName].ContainsKey(access)); if (userRoles == null || userRoles.Count() == 0) { return(false); } var maxRole = userRoles.Max(r => r.Privileges[entity.LogicalName][access].PrivilegeDepth); if (maxRole == PrivilegeDepth.Global) { return(true); } if (access == AccessRights.CreateAccess) { if (!entity.Attributes.ContainsKey("ownerid")) { entity["ownerid"] = caller; } } if (entity.Attributes.ContainsKey("ownerid")) { var owner = entity.GetAttributeValue <EntityReference>("ownerid"); if (owner.Id == caller.Id) { return(true); } var callerRow = Core.GetDbRow(caller); if (maxRole == PrivilegeDepth.Local) { return(IsInBusinessUnit(owner.Id, callerRow.GetColumn <DbRow>("businessunitid").Id)); } if (maxRole == PrivilegeDepth.Deep) { if (callerRow.GetColumn <DbRow>("parentbusinessunitid") != null) { return(IsInBusinessUnitTree(owner.Id, callerRow.GetColumn <DbRow>("parentbusinessunitid").Id)); } return(IsInBusinessUnitTree(owner.Id, callerRow.GetColumn <DbRow>("businessunitid").Id)); } } var entityRef = entity.ToEntityReference(); if (Shares.ContainsKey(entityRef) && Shares[entityRef].ContainsKey(caller) && Shares[entityRef][caller].HasFlag(access)) { return(true); } var parentChangeRelationships = Metadata.EntityMetadata.GetMetadata(entity.LogicalName).ManyToOneRelationships .Where(r => r.CascadeConfiguration.Reparent == CascadeType.Cascade || r.CascadeConfiguration.Reparent == CascadeType.Active) .Where(r => entity.Attributes.ContainsKey(r.ReferencingAttribute)); if (parentChangeRelationships.Any(r => Core.GetDbRowOrNull(new EntityReference(r.ReferencedEntity, Utility.GetGuidFromReference(entity[r.ReferencingAttribute]))) ?.GetColumn <DbRow>("ownerid").Id == caller.Id)) { return(true); } return(false); }
public static string ToSerialString(this AccessRights value) => value switch {
protected override void ApplyRightsFromStream(AccessRights rights) { base.ApplyRightsFromStream(rights); _currentAccessRights = rights; }
public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e) { if (SkippedNumbersReport.DocumentRegisterId.HasValue) { SkippedNumbersReport.DocumentRegister = DocumentRegisters.Get(SkippedNumbersReport.DocumentRegisterId.Value); } SkippedNumbersReport.CurrentDate = Calendar.Now; var documentRegister = SkippedNumbersReport.DocumentRegister; var documents = Enumerable.Empty <IOfficialDocument>().AsQueryable(); AccessRights.AllowRead(() => { documents = Docflow.OfficialDocuments.GetAll() .Where(d => d.DocumentRegister == SkippedNumbersReport.DocumentRegister) .Where(d => d.RegistrationState == RegistrationState.Registered || d.RegistrationState == RegistrationState.Reserved); }); #region Период формирования отчета и разрезы var baseDate = Calendar.UserNow; var periodOffset = SkippedNumbersReport.PeriodOffset.HasValue ? SkippedNumbersReport.PeriodOffset.Value : 0; // Признак того, что отчет запущен из диалога регистрации. var launchedFromDialog = SkippedNumbersReport.RegistrationDate.HasValue; if (launchedFromDialog) { baseDate = SkippedNumbersReport.RegistrationDate.Value; // По умолчанию для отчета из диалога регистрации берем данные за последний месяц. SkippedNumbersReport.Period = Constants.SkippedNumbersReport.Month; SkippedNumbersReport.PeriodOffset = 0; } if (SkippedNumbersReport.Period.Equals(Constants.SkippedNumbersReport.Year)) { SkippedNumbersReport.PeriodBegin = Calendar.BeginningOfYear(baseDate.AddYears(periodOffset)); SkippedNumbersReport.PeriodEnd = periodOffset == 0 ? Calendar.EndOfYear(baseDate) : Calendar.EndOfYear(baseDate.AddYears(periodOffset)); } if (SkippedNumbersReport.Period.Equals(Constants.SkippedNumbersReport.Quarter)) { SkippedNumbersReport.PeriodBegin = Docflow.PublicFunctions.AccountingDocumentBase.BeginningOfQuarter(baseDate.AddMonths(3 * periodOffset)); SkippedNumbersReport.PeriodEnd = periodOffset == 0 ? Docflow.PublicFunctions.AccountingDocumentBase.EndOfQuarter(baseDate) : Docflow.PublicFunctions.AccountingDocumentBase.EndOfQuarter(baseDate.AddMonths(3 * periodOffset)); } if (SkippedNumbersReport.Period.Equals(Constants.SkippedNumbersReport.Month)) { SkippedNumbersReport.PeriodBegin = Calendar.BeginningOfMonth(baseDate.AddMonths(periodOffset)); SkippedNumbersReport.PeriodEnd = periodOffset == 0 ? Calendar.EndOfMonth(baseDate) : Calendar.EndOfMonth(baseDate.AddMonths(periodOffset)); } if (SkippedNumbersReport.Period.Equals(Constants.SkippedNumbersReport.Week)) { SkippedNumbersReport.PeriodBegin = Calendar.BeginningOfWeek(baseDate.AddDays(7 * periodOffset)); SkippedNumbersReport.PeriodEnd = periodOffset == 0 ? Calendar.EndOfWeek(baseDate) : Calendar.EndOfWeek(baseDate.AddDays(7 * periodOffset)); } // Получить границы периода журнала регистрации. var registrationDate = launchedFromDialog ? SkippedNumbersReport.RegistrationDate.Value : SkippedNumbersReport.PeriodEnd.Value; DateTime?documentRegisterPeriodBegin = Functions.DocumentRegister.GetBeginPeriod(documentRegister, registrationDate); DateTime?documentRegisterPeriodEnd = Functions.DocumentRegister.GetEndPeriod(documentRegister, registrationDate) ?? SkippedNumbersReport.PeriodEnd.Value; // Начало расчетного периода. var periodBegin = SkippedNumbersReport.PeriodBegin; // Если отчет вызван из диалога регистрации взять "месяц назад" от даты регистрации. if (launchedFromDialog) { periodBegin = registrationDate.AddMonths(-1); } // Если начало указанного периода раньше начала периода журнала, то считать от последнего. if (documentRegisterPeriodBegin.HasValue && documentRegisterPeriodBegin > periodBegin) { periodBegin = documentRegisterPeriodBegin; } else if (!documentRegisterPeriodBegin.HasValue) { documentRegisterPeriodBegin = Calendar.SqlMinValue; } SkippedNumbersReport.PeriodBegin = periodBegin; // Конец расчетного периода. var periodEnd = launchedFromDialog ? SkippedNumbersReport.RegistrationDate.Value.EndOfDay() : SkippedNumbersReport.PeriodEnd; SkippedNumbersReport.PeriodEnd = periodEnd; var hasLeadingDocument = SkippedNumbersReport.LeadingDocument != null; var hasDepartment = SkippedNumbersReport.Department != null; var hasBusinessUnit = SkippedNumbersReport.BusinessUnit != null; // Отфильтровать документы по разрезам. if (hasLeadingDocument) { documents = documents.Where(d => Equals(d.LeadingDocument, SkippedNumbersReport.LeadingDocument)); } if (hasDepartment) { documents = documents.Where(d => Equals(d.Department, SkippedNumbersReport.Department)); } if (hasBusinessUnit) { documents = documents.Where(d => Equals(d.BusinessUnit, SkippedNumbersReport.BusinessUnit)); } #endregion #region Генерация формата номера var numberFormat = string.Empty; foreach (var item in documentRegister.NumberFormatItems.OrderBy(x => x.Number)) { var elementName = string.Empty; if (item.Element == DocumentRegisterNumberFormatItems.Element.Number) { elementName = DocumentRegisters.Resources.NumberFormatNumber; } else if (item.Element == DocumentRegisterNumberFormatItems.Element.Year2Place || item.Element == DocumentRegisterNumberFormatItems.Element.Year4Place) { elementName = DocumentRegisters.Resources.NumberFormatYear; } else if (item.Element == DocumentRegisterNumberFormatItems.Element.Quarter) { elementName = DocumentRegisters.Resources.NumberFormatQuarter; } else if (item.Element == DocumentRegisterNumberFormatItems.Element.Month) { elementName = DocumentRegisters.Resources.NumberFormatMonth; } else if (item.Element == DocumentRegisterNumberFormatItems.Element.LeadingNumber) { elementName = DocumentRegisters.Resources.NumberFormatLeadingNumber; } else if (item.Element == DocumentRegisterNumberFormatItems.Element.Log) { elementName = DocumentRegisters.Resources.NumberFormatLog; } else if (item.Element == DocumentRegisterNumberFormatItems.Element.RegistrPlace) { elementName = DocumentRegisters.Resources.NumberFormatRegistrPlace; } else if (item.Element == DocumentRegisterNumberFormatItems.Element.CaseFile) { elementName = DocumentRegisters.Resources.NumberFormatCaseFile; } else if (item.Element == DocumentRegisterNumberFormatItems.Element.DepartmentCode) { elementName = DocumentRegisters.Resources.NumberFormatDepartmentCode; } else if (item.Element == DocumentRegisterNumberFormatItems.Element.BUCode) { elementName = DocumentRegisters.Resources.NumberFormatBUCode; } else if (item.Element == DocumentRegisterNumberFormatItems.Element.DocKindCode) { elementName = DocumentRegisters.Resources.NumberFormatDocKindCode; } else if (item.Element == DocumentRegisterNumberFormatItems.Element.CPartyCode) { elementName = DocumentRegisters.Resources.NumberFormatCounterpartyCode; } numberFormat += elementName + item.Separator; } SkippedNumbersReport.NumberFormat = numberFormat; #endregion #region Границы индексов в выбранном периоде // Получить минимальный индекс по документам в периоде (при ручной регистрации мб нарушение следования индексов). var firstDocumentIndex = Functions.DocumentRegister.GetIndex(documents, periodBegin, periodEnd, false); // Получить индекс документа из предыдущего периода. var previousIndex = 0; if (periodBegin != documentRegisterPeriodBegin) { previousIndex = Functions.DocumentRegister.FilterDocumentsByPeriod(documents, documentRegisterPeriodBegin, periodBegin.Value.AddDays(-1).EndOfDay()) .Where(d => !firstDocumentIndex.HasValue || d.Index < firstDocumentIndex).Select(d => d.Index).OrderByDescending(a => a).FirstOrDefault() ?? 0; } if (firstDocumentIndex == null) { firstDocumentIndex = previousIndex + 1; } var firstIndex = firstDocumentIndex < previousIndex ? firstDocumentIndex : previousIndex + 1; // Получить первый индекс документа следующего периода. var nextIndex = periodEnd != documentRegisterPeriodEnd? Functions.DocumentRegister.GetIndex(documents, periodEnd.Value.AddDays(1).BeginningOfDay(), documentRegisterPeriodEnd, false) : null; // Если в следующем периоде ещё нет документов, то взять текущий индекс журнала. var leadingDocumentId = hasLeadingDocument ? SkippedNumbersReport.LeadingDocument.Id : 0; var departmentId = hasDepartment ? SkippedNumbersReport.Department.Id : 0; var businessUnitId = hasBusinessUnit ? SkippedNumbersReport.BusinessUnit.Id : 0; if (nextIndex == null) { nextIndex = Functions.DocumentRegister.GetCurrentNumber(documentRegister, registrationDate, leadingDocumentId, departmentId, businessUnitId) + 1; } // Получить индекс по зарегистрированным документам (при ручной регистрации мб нарушение следования индексов). var lastDocumentIndex = Functions.DocumentRegister.GetIndex(documents, periodBegin, periodEnd, true) ?? nextIndex - 1; var lastIndex = lastDocumentIndex >= nextIndex ? lastDocumentIndex : nextIndex - 1; // Для случая когда нет документов в периоде. if (lastIndex < firstIndex) { lastIndex = firstIndex - 1; } #endregion // Отфильтровать документы по найденным границам индексов и по периоду журнала регистрации. // Допускать документы с номером не соответствующим формату (Index = 0). documents = documents .Where(d => !documentRegisterPeriodBegin.HasValue || d.RegistrationDate >= documentRegisterPeriodBegin) .Where(d => !documentRegisterPeriodEnd.HasValue || d.RegistrationDate <= documentRegisterPeriodEnd) .Where(l => l.Index >= firstIndex && l.Index <= lastIndex || (l.Index == 0 && l.RegistrationDate <= SkippedNumbersReport.PeriodEnd && l.RegistrationDate >= SkippedNumbersReport.PeriodBegin)); // Заполнить маску для гиперссылки. if (documents.Count() > 0) { var link = Hyperlinks.Get(documents.First()); var index = link.IndexOf("?type="); SkippedNumbersReport.hyperlinkMask = link.Substring(0, index) + "?type=DocGUID&id=DocId"; } else { SkippedNumbersReport.hyperlinkMask = string.Empty; } #region Вычислить пропущенные индексы // Создать временную таблицу для списка номеров "подряд". var skipsTableName = Constants.SkippedNumbersReport.SkipsTableName; SkippedNumbersReport.SkipsTableName = skipsTableName; var skipedNumberList = new List <string>(); var skipedNumbers = new List <Structures.SkippedNumbersReport.SkippedNumber>(); var reportSessionId = Guid.NewGuid().ToString(); SkippedNumbersReport.ReportSessionId = reportSessionId; // Заполнить таблицу номеров. var month = documentRegisterPeriodBegin.Value.Month < 10 ? string.Format("0{0}", documentRegisterPeriodBegin.Value.Month) : documentRegisterPeriodBegin.Value.Month.ToString(); var day = documentRegisterPeriodBegin.Value.Day < 10 ? string.Format("0{0}", documentRegisterPeriodBegin.Value.Day) : documentRegisterPeriodBegin.Value.Day.ToString(); var startDate = string.Format("{0}{1}{2}", documentRegisterPeriodBegin.Value.Year, month, day); month = documentRegisterPeriodEnd.Value.Month < 10 ? string.Format("0{0}", documentRegisterPeriodEnd.Value.Month) : documentRegisterPeriodEnd.Value.Month.ToString(); day = documentRegisterPeriodEnd.Value.Day < 10 ? string.Format("0{0}", documentRegisterPeriodEnd.Value.Day) : documentRegisterPeriodEnd.Value.Day.ToString(); var endDate = string.Format("{0}{1}{2}", documentRegisterPeriodEnd.Value.Year, month, day); var queryText = string.Format(Queries.SkippedNumbersReport.GetSkippedIndexes, SkippedNumbersReport.DocumentRegister.Id.ToString(), (firstIndex - 1).ToString(), (lastIndex + 1).ToString(), hasBusinessUnit.ToString(), businessUnitId.ToString(), hasDepartment.ToString(), departmentId.ToString(), hasLeadingDocument.ToString(), leadingDocumentId.ToString(), documentRegisterPeriodBegin.HasValue.ToString(), startDate, endDate); // Получить интервалы пропущеных индексов журнала в периоде. // Key - начало интервала, Value - окончиние интервала. var skippedIndexIntervals = new Dictionary <int, int>(); using (var command = SQL.GetCurrentConnection().CreateCommand()) { command.CommandText = queryText; var result = command.ExecuteReader(); while (result.Read()) { skippedIndexIntervals.Add((int)result[1], (int)result[0]); } result.Close(); } // Заполнить отчет данными для пропущенных индексов. foreach (var interval in skippedIndexIntervals) { var intervalStart = interval.Key; var intervalEnd = interval.Value; // Три и более подряд идущих пропущеных индексов должны быть собраны в одну строку. var intervalLength = intervalEnd - intervalStart + 1; if (intervalLength >= 3) { skipedNumbers.Add(Structures.SkippedNumbersReport.SkippedNumber.Create(Docflow.Reports.Resources.SkippedNumbersReport.NumbersAreSkipped, string.Format("{0}-{1}", intervalStart.ToString(), intervalEnd.ToString()), intervalStart, reportSessionId)); skipedNumberList.Add(string.Format("{0}-{1}", intervalStart.ToString(), intervalEnd.ToString())); continue; } for (var i = intervalStart; i <= intervalEnd; i++) { skipedNumbers.Add(Structures.SkippedNumbersReport.SkippedNumber.Create(Docflow.Reports.Resources.SkippedNumbersReport.NumberIsSkipped, i.ToString(), i, reportSessionId)); skipedNumberList.Add(i.ToString()); } } #endregion Functions.Module.WriteStructuresToTable(skipsTableName, skipedNumbers); // Получить 8-10 первых пропущенных номеров строкой. Для остальных указать общее количество. var skipedNumberCount = skipedNumberList.Count; var maxDisplayedNumberCount = 10; var minHiddenNumberCount = 3; var displayedValuesCount = skipedNumberCount; if (skipedNumberCount >= (maxDisplayedNumberCount + minHiddenNumberCount)) { displayedValuesCount = maxDisplayedNumberCount; } else if (skipedNumberCount > maxDisplayedNumberCount) { displayedValuesCount = skipedNumberCount - minHiddenNumberCount; } SkippedNumbersReport.SkipedNumberList = string.Join(", ", skipedNumberList.ToArray(), 0, displayedValuesCount); var hiddenSkipedNumberCount = skipedNumberCount - displayedValuesCount; if (hiddenSkipedNumberCount > 0) { var numberLabel = Functions.Module.GetNumberDeclination(hiddenSkipedNumberCount, Resources.SkippedNumbersReportNumber, Resources.SkippedNumbersReportNumberGenetive, Resources.SkippedNumbersReportNumberPlural); SkippedNumbersReport.SkipedNumberList += string.Format(Sungero.Docflow.Reports.Resources.SkippedNumbersReport.And, hiddenSkipedNumberCount, numberLabel); } // Создать таблицу для доступных пользователю документов. var availableDocuments = new List <Structures.SkippedNumbersReport.AvailableDocument>(); var previousDocDate = Calendar.SqlMinValue; foreach (var document in documents.ToList().OrderBy(x => x.Index)) { var numberOnFormat = document.Index != null && document.Index != 0; var canRead = document.AccessRights.CanRead(); var inCorrectOrder = (previousDocDate <= document.RegistrationDate || !numberOnFormat) && (document.RegistrationDate >= SkippedNumbersReport.PeriodBegin && document.RegistrationDate <= SkippedNumbersReport.PeriodEnd); availableDocuments.Add(Structures.SkippedNumbersReport.AvailableDocument.Create(document.Id, numberOnFormat, canRead, inCorrectOrder, reportSessionId)); if (numberOnFormat && inCorrectOrder) { previousDocDate = document.RegistrationDate.Value; } } SkippedNumbersReport.AvailableDocumentsTableName = Constants.SkippedNumbersReport.AvailableDocumentsTableName; Functions.Module.WriteStructuresToTable(SkippedNumbersReport.AvailableDocumentsTableName, availableDocuments); }
public ServiceBusTriggerBinding(string parameterName, Type parameterType, ITriggerDataArgumentBinding <BrokeredMessage> argumentBinding, ServiceBusAccount account, string queueName, AccessRights accessRights) { _parameterName = parameterName; _converter = CreateConverter(parameterType); _argumentBinding = argumentBinding; _account = account; _namespaceName = ServiceBusClient.GetNamespaceName(account); _queueName = queueName; _entityPath = queueName; _accessRights = accessRights; }
protected UnionPartBase(IReader reader) : base(reader) { HasNestedTypes = reader.ReadBool(); IsSingleCase = reader.ReadBool(); RepresentationAccessRights = (AccessRights)reader.ReadByte(); }
/// <summary> /// Replace the access rights on the target record for the specified security principal (user or team). /// <para> /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.modifyaccessrequest(v=crm.7).aspx /// </para> /// </summary> /// <param name="shareToPrincipal"><see cref="PrincipalType"/></param> /// <param name="shareToId"></param> /// <param name="targetEntityLogicalName"></param> /// <param name="targetId"></param> /// <param name="targetAccessRights"></param> /// <returns> /// <see cref="ModifyAccessResponse"/> /// </returns> public ModifyAccessResponse ModifyShare(PrincipalType shareToPrincipal, Guid shareToId, string targetEntityLogicalName, Guid targetId, AccessRights targetAccessRights) { ExceptionThrow.IfGuidEmpty(shareToId, "shareToId"); ExceptionThrow.IfGuidEmpty(targetId, "targetId"); ExceptionThrow.IfNullOrEmpty(targetEntityLogicalName, "targetEntityLogicalName"); ModifyAccessRequest request = new ModifyAccessRequest() { PrincipalAccess = new PrincipalAccess() { Principal = new EntityReference(shareToPrincipal.Description(), shareToId), AccessMask = targetAccessRights }, Target = new EntityReference(targetEntityLogicalName, targetId) }; return((ModifyAccessResponse)this.OrganizationService.Execute(request)); }
public void TestAccessRights() { var expected = new [] { AccessRight.OpenFolder, AccessRight.CreateFolder, AccessRight.DeleteFolder, AccessRight.ExpungeFolder, AccessRight.AppendMessages, AccessRight.SetMessageDeleted }; var rights = new AccessRights(); int i; Assert.IsFalse(rights.IsReadOnly, "IsReadOnly"); Assert.IsTrue(rights.Add(AccessRight.OpenFolder), "Add OpenFolder"); Assert.AreEqual(1, rights.Count, "Count after adding OpenFolder"); Assert.IsFalse(rights.Add(AccessRight.OpenFolder), "Add OpenFolder again"); Assert.AreEqual(1, rights.Count, "Count after adding OpenFolder again"); Assert.IsTrue(rights.Add(AccessRight.CreateFolder.Right), "Add CreateFolder"); Assert.AreEqual(2, rights.Count, "Count after adding CreateFolder"); Assert.IsFalse(rights.Add(AccessRight.CreateFolder), "Add CreateFolder again"); Assert.AreEqual(2, rights.Count, "Count after adding OpenFolder again"); rights.AddRange(new [] { AccessRight.DeleteFolder, AccessRight.ExpungeFolder }); Assert.AreEqual(4, rights.Count, "Count after adding DeleteFolder and ExpungeFolder"); Assert.IsTrue(rights.Contains(AccessRight.DeleteFolder), "Contains DeleteFolder"); Assert.IsTrue(rights.Contains(AccessRight.ExpungeFolder), "Contains ExpungeFolder"); Assert.IsFalse(rights.Contains(AccessRight.Administer), "Contains Administer"); rights.AddRange("it"); Assert.AreEqual(6, rights.Count, "Count after adding AppendMessages and SetMessageDeleted"); Assert.IsTrue(rights.Contains(AccessRight.AppendMessages), "Contains AppendMessages"); Assert.IsTrue(rights.Contains(AccessRight.SetMessageDeleted), "Contains SetMessageDeleted"); Assert.IsFalse(rights.Contains(AccessRight.Administer), "Contains Administer"); for (i = 0; i < 6; i++) { Assert.AreEqual(expected[i], rights[i], "rights[{0}]", i); } ((ICollection <AccessRight>)rights).Add(AccessRight.Administer); Assert.IsTrue(rights.Remove(AccessRight.Administer), "Remove Administer"); Assert.IsFalse(rights.Remove(AccessRight.Administer), "Remove Administer again"); i = 0; foreach (var right in rights) { Assert.AreEqual(expected[i], right, "foreach rights[{0}]", i++); } i = 0; foreach (AccessRight right in ((IEnumerable)rights)) { Assert.AreEqual(expected[i], right, "generic foreach rights[{0}]", i++); } var array = new AccessRight[rights.Count]; rights.CopyTo(array, 0); for (i = 0; i < 6; i++) { Assert.AreEqual(expected[i], array[i], "CopyTo[{0}]", i); } Assert.AreEqual("rkxeit", rights.ToString(), "ToString"); }
/// <summary> /// Checks if a principle has the given access right to an entity /// </summary> /// <param name="entityRef">Entity to check against</param> /// <param name="access">Access to check with</param> /// <param name="principleRef">User or team</param> /// <returns>If the given principle has permission to 'access' the entity</returns> public bool HasPermission(EntityReference entityRef, AccessRights access, EntityReference principleRef) { return(Core.HasPermission(entityRef, access, principleRef)); }
public static extern IntPtr OpenProcess(AccessRights dwDesiredAccess, bool bInheritHandle, int dwProcessId);
/// <summary> /// Назначает указанные права доступа файлу или каталогу. /// </summary> /// <param name="path">Путь к файлу или каталогу.</param> /// <param name="accessRights">Права доступа, которые будут назначены.</param> public void SetAccessRights(string path, AccessRights accessRights) { FileSystem.SetAccessRights(path, accessRights); }
void ModifyAccessRights (string name, AccessRights rights, string action, CancellationToken cancellationToken) { if ((Engine.Capabilities & ImapCapabilities.Acl) == 0) throw new NotSupportedException ("The IMAP server does not support the ACL extension."); CheckState (false, false); var ic = Engine.QueueCommand (cancellationToken, null, "SETACL %F %S %S\r\n", this, name, action + rights); Engine.Wait (ic); ProcessResponseCodes (ic, null); if (ic.Response != ImapCommandResponse.Ok) throw ImapCommandException.Create ("SETACL", ic); }
/// <summary> /// Override for GrantAccess plugin message /// </summary> /// <param name="context">Crm Context</param> /// <param name="entityName">Entity name</param> /// <param name="primaryEntityId">Id of the entity</param> /// <param name="principalEntityName">Principal entity name</param> /// <param name="principalId">Principal Id</param> /// <param name="mask">Principal access mask</param> public virtual void OnModifyAccess(IPluginExecutionContext context, string entityName, Guid primaryEntityId, string principalEntityName, Guid principalId, AccessRights mask) { }
/// <summary> /// Set the access rights for the specified identity. /// </summary> /// <remarks> /// Sets the access rights for the specified identity. /// </remarks> /// <param name="name">The identity name.</param> /// <param name="rights">The access rights.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="name"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="rights"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The <see cref="ImapClient"/> has been disposed. /// </exception> /// <exception cref="ServiceNotConnectedException"> /// The <see cref="ImapClient"/> is not connected. /// </exception> /// <exception cref="ServiceNotAuthenticatedException"> /// The <see cref="ImapClient"/> is not authenticated. /// </exception> /// <exception cref="System.NotSupportedException"> /// The IMAP server does not support the ACL extension. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="ImapProtocolException"> /// The server's response contained unexpected tokens. /// </exception> /// <exception cref="ImapCommandException"> /// The command failed. /// </exception> public override void SetAccessRights (string name, AccessRights rights, CancellationToken cancellationToken = default (CancellationToken)) { if (name == null) throw new ArgumentNullException ("name"); if (rights == null) throw new ArgumentNullException ("rights"); ModifyAccessRights (name, rights, string.Empty, cancellationToken); }
/// <summary> /// Initializes a new instance of the <see cref="ServiceBusTriggerAttribute"/> class. /// </summary> /// <param name="queueName">The name of the queue to which to bind.</param> /// <param name="access">The <see cref="AccessRights"/> the client has to the queue.</param> public ServiceBusTriggerAttribute(string queueName, AccessRights access) { _queueName = queueName; Access = access; }
public ServiceBusQueueListenerFactory(ServiceBusAccount account, string queueName, ITriggeredFunctionExecutor executor, AccessRights accessRights, ServiceBusConfiguration config) { _namespaceManager = account.NamespaceManager; _messagingFactory = account.MessagingFactory; _queueName = queueName; _executor = executor; _accessRights = accessRights; _config = config; }
/// <summary> /// Initializes a new instance of the <see cref="ServiceBusTriggerAttribute"/> class. /// </summary> /// <param name="topicName">The name of the topic to bind to.</param> /// <param name="subscriptionName">The name of the subscription in <paramref name="topicName"/> to bind to.</param> /// <param name="access">The <see cref="AccessRights"/> the client has to the subscription in the topic.</param> public ServiceBusTriggerAttribute(string topicName, string subscriptionName, AccessRights access) { _topicName = topicName; _subscriptionName = subscriptionName; Access = access; }
public static Metadata GetMetadata(MetadataLevel level, AccessRights rights, RootAccess rootAccess, ResourceCollection resourceCollection, TypeCache typeCache) { var domain = rights?.Keys ?? resourceCollection.AllResources; var entityResources = domain .OfType <IEntityResource>() .Where(r => r.IsGlobal) .OrderBy(r => r.Name) .ToList(); var terminalResources = domain .OfType <ITerminalResource>() .ToList(); if (level == MetadataLevel.OnlyResources) { return new Metadata { CurrentAccessScope = new Dictionary <IResource, Method[]>(rights ?? rootAccess), EntityResources = entityResources.ToArray(), TerminalResources = terminalResources.ToArray() } } ; var checkedTypes = new HashSet <Type>(); void parseType(Type type) { switch (type) { case var _ when type.IsEnum: checkedTypes.Add(type); break; case var _ when type.IsNullable(out var baseType): parseType(baseType); break; case var _ when type.ImplementsGenericInterface(typeof(IEnumerable <>), out var param) && param.Any(): if (param[0].ImplementsGenericInterface(typeof(IEnumerable <>))) { break; } parseType(param[0]); break; case var _ when type.IsGenericType && type.GetGenericTypeDefinition() == typeof(KeyValuePair <,>): case var _ when IsPrimitive(type): case var _ when type == typeof(object): break; case var _ when checkedTypes.Add(type): { var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance) .Where(p => !p.RESTableIgnored()) .Select(p => p.FieldType); foreach (var field in fields) { parseType(field); } var properties = typeCache.GetDeclaredProperties(type).Values .Where(p => !p.Hidden) .Select(p => p.Type); foreach (var property in properties) { parseType(property); } break; } } } var entityTypes = entityResources.Select(r => r.Type).ToHashSet(); var terminalTypes = terminalResources.Select(r => r.Type).ToHashSet(); foreach (var type in entityTypes) { parseType(type); } checkedTypes.ExceptWith(entityTypes); foreach (var type in terminalTypes) { parseType(type); } checkedTypes.ExceptWith(terminalTypes); return(new Metadata { CurrentAccessScope = new Dictionary <IResource, Method[]>(rights ?? rootAccess), EntityResources = entityResources.ToArray(), TerminalResources = terminalResources.ToArray(), EntityResourceTypes = new ReadOnlyDictionary <Type, Member[]>(entityTypes.ToDictionary(t => t, type => typeCache.GetDeclaredProperties(type).Values.Cast <Member>().ToArray())), PeripheralTypes = new ReadOnlyDictionary <Type, Member[]>(checkedTypes.ToDictionary(t => t, type => { var props = typeCache.GetDeclaredProperties(type).Values; var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance) .Where(p => !p.RESTableIgnored()) .Select(f => new Field(f)); return props.Union <Member>(fields).ToArray(); })) }); }
/// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() { var hashCode = Constants.HashInitializer; unchecked { hashCode = Constants.HashMultiplier * hashCode + IsFolder.GetHashCode(); hashCode = Constants.HashMultiplier * hashCode + (AccessRights != null ? AccessRights.GetHashCode() : 0); hashCode = Constants.HashMultiplier * hashCode + Number.GetHashCode(); hashCode = Constants.HashMultiplier * hashCode + (Owner != null ? Owner.GetHashCode() : 0); hashCode = Constants.HashMultiplier * hashCode + (Group != null ? Group.GetHashCode() : 0); hashCode = Constants.HashMultiplier * hashCode + FileSize.GetHashCode(); hashCode = Constants.HashMultiplier * hashCode + Created.GetHashCode(); hashCode = Constants.HashMultiplier * hashCode + (Name != null ? Name.GetHashCode() : 0); } return(hashCode); }
public StringToServiceBusEntityConverter(ServiceBusAccount account, IBindableServiceBusPath defaultPath, AccessRights accessRights) { _account = account; _defaultPath = defaultPath; _accessRights = accessRights; }
public AuthorizeLevelAttribute(AccessRights rights) { this.Rights = rights; }
private static TypeAndNamespace GetAccessableTypeElementAndNamespace(ICSharpTypeMemberDeclaration declaration, ISolution solution, ICSharpFile file, IClrDeclaredElement element, IdentifierLookupScopes scope) { //IPsiModule module = element.Module; IXmlDocIdOwner idOwner = element as IXmlDocIdOwner; string docId = idOwner == null ? element.ShortName : idOwner.XMLDocId; // Get the defining type. ITypeElement typeElement = element as ITypeElement ?? element.GetContainingType(); if (typeElement == null) { return(null); } // Create the result TypeAndNamespace result = new TypeAndNamespace { XmlDocId = docId, TypeElement = element }; // Get the namespace it belongs to. INamespace namespaceElement = typeElement.GetContainingNamespace(); string namespaceName = namespaceElement.QualifiedName; // Check if we're ignoring this namespace foreach (string namespacePrefix in NamespacePrefixesToIgnore) { if (namespaceName.StartsWith(namespacePrefix)) { return(null); } } // Check if it would be possible to access the type AccessRights elementAccessRights = GetAccessRights(element); if (elementAccessRights == AccessRights.PRIVATE) { return(null); } // Check if the type is defined in this solution IList <IDeclaration> declarations = element.GetDeclarations(); if (declarations.Count == 0) { // Assembly is an import so no internal things allowed if (elementAccessRights == AccessRights.INTERNAL) { return(null); } } // Check if the given namespace is already imported in this file. if (UsingUtil.CheckAlreadyImported(file, namespaceElement) || declaration.GetContainingNamespaceDeclaration().QualifiedName.StartsWith(namespaceName)) { string newDocId = docId[1] == ':' ? docId.Substring(2) : docId; if (newDocId.StartsWith(namespaceName + ".")) { newDocId = newDocId.Substring(namespaceName.Length + 1); } result.XmlDocId = newDocId; return(result); } // If we require it to be in project or using scope then this is not a match if (scope == IdentifierLookupScopes.ProjectAndUsings || scope == IdentifierLookupScopes.ProjectOnly) { return(null); } // No - so add in the namespace. result.RequiredNamespaceImport = namespaceElement; return(result); }
public static extern IntPtr Create([MarshalAs(UnmanagedType.LPWStr)] string fileName, AccessRights desiredAccess, ShareMode shareMode, IntPtr securityAttributes, CreationDisposition creationDisposition, Attribute flagsAndAttributes, IntPtr hTemplateFile);
public IotHubConnectionCache(AccessRights accessRights) { this.IdleTimeout = DefaultIdleTimeout; this.connections = new ConcurrentDictionary <IotHubConnectionString, CachedConnection>(new IotHubConnectionCacheStringComparer()); this.accessRights = accessRights; }
/// <summary> /// Returns true if the Principal has write access to the specified record. /// </summary> /// <param name="Record"></param> /// <param name="Principal"></param> /// <returns></returns> public bool HasWriteAccess(EntityReference Record, EntityReference Principal) { AccessRights rights = this.GetAccessRights(Record, Principal); return((rights & AccessRights.WriteAccess) != AccessRights.None); }
/// <summary> /// Asynchronously set the access rights for the specified identity. /// </summary> /// <remarks> /// Asynchronously sets the access rights for the specified identity. /// </remarks> /// <returns>An asynchronous task context.</returns> /// <param name="name">The identity name.</param> /// <param name="rights">The access rights.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="name"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="rights"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The <see cref="IMailStore"/> has been disposed. /// </exception> /// <exception cref="ServiceNotConnectedException"> /// The <see cref="IMailStore"/> is not connected. /// </exception> /// <exception cref="ServiceNotAuthenticatedException"> /// The <see cref="IMailStore"/> is not authenticated. /// </exception> /// <exception cref="System.NotSupportedException"> /// The mail store does not support the ACL extension. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="ProtocolException"> /// The server's response contained unexpected tokens. /// </exception> /// <exception cref="CommandException"> /// The command failed. /// </exception> public virtual Task SetAccessRightsAsync (string name, AccessRights rights, CancellationToken cancellationToken = default (CancellationToken)) { if (name == null) throw new ArgumentNullException ("name"); if (rights == null) throw new ArgumentNullException ("rights"); return Task.Factory.StartNew (() => { lock (SyncRoot) { SetAccessRights (name, rights, cancellationToken); } }, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); }
public static extern IntPtr CreateFile(string lpFileName, AccessRights dwDesiredAccess, ShareMode dwShareMode, ref SECURITY_ATTRIBUTES lpSecurityAttributes, CreationDisposition dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);
public AccessRights GetAccessRights(ValueType objectType, ObjectInfoFlags flags) { AccessRights rights = new AccessRights(); Access[] access = rights.Access = new Access[17]; // these aliases should make the code more readable // for the magazine edition (we don't get much width!) AccessFlags G = AccessFlags.General; AccessFlags S = AccessFlags.Specific; // summary page permissions access[0] = new Access(SERVICE_ALL, "Full Control", G | S); access[1] = new Access(SERVICE_READ, "Read", G); access[2] = new Access(SERVICE_WRITE, "Write", G); access[3] = new Access(SERVICE_EXECUTE, "Execute", G); // advanced page permissions access[4] = new Access(0x0001, "Query Configuration", S); access[5] = new Access(0x0002, "Change Configuration", S); access[6] = new Access(0x0004, "Query Status", S); access[7] = new Access(0x0008, "Enumerate Dependents", S); access[8] = new Access(0x0010, "Start", S); access[9] = new Access(0x0020, "Stop", S); access[10] = new Access(0x0040, "Pause or Continue", S); access[11] = new Access(0x0080, "Interrogate", S); access[12] = new Access(0x0100, "Send User Defined Control", S); access[13] = new Access(0x00010000, "Delete", S); access[14] = new Access(0x00020000, "Read Permissions", S); access[15] = new Access(0x00040000, "Change Permissions", S); access[16] = new Access(0x00080000, "Take Ownership", S); // note how I refer to access[1] as the default ("Read") rights.DefaultIndex = 1; return rights; }
public IMethodDeclaration CreateDeclaration([NotNull] CSharpElementFactory factory, [NotNull] IClassLikeDeclaration classDeclaration, AccessRights accessRights, bool makeVirtual = false, bool makeCoroutine = false) { var builder = new StringBuilder(128); if (accessRights != AccessRights.NONE) { builder.Append(CSharpDeclaredElementPresenter.Instance.Format(accessRights)); builder.Append(" "); } if (IsStatic) { builder.Append("static "); } // Consider this declaration a template, and the final generated code implements (or overrides) this API if (makeVirtual) { builder.Append("virtual "); } builder.Append("global::"); if (makeCoroutine && CanBeCoroutine) { builder.Append(PredefinedType.IENUMERATOR_FQN.FullName); } else { builder.Append(ReturnType.FullName); if (ReturnTypeIsArray) { builder.Append("[]"); } } builder.Append(" "); builder.Append(Name); builder.Append("("); for (var i = 0; i < Parameters.Length; i++) { if (i > 0) { builder.Append(","); } var parameter = Parameters[i]; // TODO: `out` or `ref`? // From reflection point of view, it's a "ByRef" Type, and that's all we know... // The only place it's currently being used is an out parameter if (parameter.IsByRef) { builder.Append("out "); } builder.Append("global::"); builder.Append(parameter.ClrTypeName.FullName); if (parameter.IsArray) { builder.Append("[]"); } builder.Append(' '); builder.Append(parameter.Name); } builder.Append(");"); var declaration = (IMethodDeclaration)factory.CreateTypeMemberDeclaration(builder.ToString()); declaration.SetResolveContextForSandBox(classDeclaration, SandBoxContextType.Child); return(declaration); }
/// <summary> /// Remove access rights for the specified identity. /// </summary> /// <remarks> /// Removes the given access rights for the specified identity. /// </remarks> /// <param name="name">The identity name.</param> /// <param name="rights">The access rights.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="name"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="rights"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// No rights were specified. /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The <see cref="ImapClient"/> has been disposed. /// </exception> /// <exception cref="ServiceNotConnectedException"> /// The <see cref="ImapClient"/> is not connected. /// </exception> /// <exception cref="ServiceNotAuthenticatedException"> /// The <see cref="ImapClient"/> is not authenticated. /// </exception> /// <exception cref="System.NotSupportedException"> /// The IMAP server does not support the ACL extension. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="ImapProtocolException"> /// The server's response contained unexpected tokens. /// </exception> /// <exception cref="ImapCommandException"> /// The command failed. /// </exception> public override void RemoveAccessRights (string name, AccessRights rights, CancellationToken cancellationToken = default (CancellationToken)) { if (name == null) throw new ArgumentNullException ("name"); if (rights == null) throw new ArgumentNullException ("rights"); if (rights.Count == 0) throw new ArgumentException ("No rights were specified.", "rights"); ModifyAccessRights (name, rights, "-", cancellationToken); }
/// <summary> /// Deserialise FileZilla binary data into object /// </summary> /// <param name="reader">Binary reader to read data from</param> public void Deserialize(BinaryReader reader) { Directory = reader.ReadText(); Aliases = reader.ReadTextList(); AccessRights = (AccessRights)reader.ReadBigEndianInt16(); }
/// <summary> /// Load user data from serialization stream.</summary> public User(SerializationInfo info, StreamingContext ctxt) { username = (string)info.GetValue("username", typeof(string)); password = (string)info.GetValue("password", typeof(string)); accessRights = (AccessRights)info.GetValue("accessRights", typeof(AccessRights)); }
/// <summary> /// Default constructor (sets defaults as in FileZilla server interface) /// </summary> public Permission() { Aliases = new List <string>(); AccessRights = AccessRights.FileRead | AccessRights.DirList | AccessRights.DirSubdirs; }
public ServiceBusTriggerBinding(string parameterName, ITriggerDataArgumentBinding <BrokeredMessage> argumentBinding, ServiceBusAccount account, string topicName, string subscriptionName, AccessRights accessRights) { _parameterName = parameterName; _argumentBinding = argumentBinding; _account = account; _namespaceName = ServiceBusClient.GetNamespaceName(account); _topicName = topicName; _subscriptionName = subscriptionName; _entityPath = SubscriptionClient.FormatSubscriptionPath(topicName, subscriptionName); _accessRights = accessRights; }
public void Share(Microsoft.Xrm.Sdk.EntityReference objectRef, Microsoft.Xrm.Sdk.EntityReference assigneeRef, AccessRights accessRights) { #region Parameters check if (objectRef == null) { throw new ArgumentNullException(nameof(objectRef)); } if (assigneeRef == null) { throw new ArgumentNullException(nameof(assigneeRef)); } #endregion AdminOrganizationService.Execute(new GrantAccessRequest { Target = objectRef, PrincipalAccess = new PrincipalAccess { AccessMask = accessRights, Principal = assigneeRef } }); }