コード例 #1
0
ファイル: CmisProfile.cs プロジェクト: aegif/CmisSync
 /// <summary>
 /// Prepare the given OperationContext for use with this CMIS profile.
 /// </summary>
 /// <param name="operationContext"></param>
 public void ConfigureOperationContext(IOperationContext operationContext)
 {
     /*
     Disabled because repository may generate error if the type is not Orderable for cmis:contentStreamFileName
     Documentum generates such an error: https://github.com/aegif/CmisSync/issues/724
     Alfresco also is not Orderable even though it does not generate an error:
     http://stackoverflow.com/questions/39290294/check-whether-cmiscontentstreamfilename-is-orderable
     
     if (IgnoreIfSameLowercaseNames)
     {
         // Depending on the CMIS profile, order by stream name or document name.
         if (UseCmisStreamName && contentStreamFileNameOrderable)
         {
             operationContext.OrderBy = "cmis:contentStreamFileName";
         }
         else
         {
             operationContext.OrderBy = "cmis:name";
         }
     }
     else
     {
         // Do not specify an order criteria, as we don't need it,
         // and it might have a performance impact on the CMIS server.
     }
     */
 }
コード例 #2
0
        async Task<OperationResult> Process(TestStatelessUnreliable msg, IOperationContext arg2)
        {
            if (msg.SleepDurationMs > 0)
                await Task.Delay(msg.SleepDurationMs);

            return OperationResult.Success;
        }
コード例 #3
0
 public void Process(SayS2S msg, IOperationContext context)
 {
     foreach (var roomMember in _roomMembers)
     {
         roomMember.CallbackChannel.Send(new RoomEvent() { Text = msg.Text, UserName = msg.UserName });
     }
 }
        public Task<Message> Process(Func<IOperationContext, Task<Message>> next, IOperationContext operation)
        {
            var lockType = LockType.Write;
            if (_lockConfig != null)
                lockType = _lockConfig.GetLockType(operation.Message.GetType());

            return _fiber.Call(() => next(operation), lockType);
        }
 void OnSay(Say msg, IOperationContext context)
 {
     if (_room != null)
     {
         _room.SendOneWay(new SayS2S(){UserName = _userName, Text = msg.Text}, context);    
     }
     else throw new ProcessingException(SayErrors.NotConnectedToRoom);
 }
コード例 #6
0
        public OperationContextOrgUnitContextStorage(IOperationContext operationContext)
        {
            _operationContext = operationContext;

            // WCF operation context is null during app initialization.
            // We don't need to store OU context during that stage anyway.
            operationContextAvailable = _operationContext != null;
        }
 async Task<OperationResult> Process(PingGateway msg, IOperationContext context)
 {
     using (BackendCallsTimer.NewContext())
     {
         await Task.Delay(msg.SleepDurationMs);
         return OperationResult.Success;
     }
 }
 async Task OnSay(Say msg, IOperationContext context)
 {
     if (_room != null)
     {
         await _room.Say(new SayS2S() { UserName = _userName, Text = msg.Text });
     }
     else throw new ProcessingException(SayErrors.NotConnectedToRoom);
 }
 private void UpdateClientIp(LocationContext location, IOperationContext operation)
 {
     if ( operation.HasIncomingMessageProperty(RemoteEndpointMessageProperty.Name) )
     {
         var property = (RemoteEndpointMessageProperty)
             operation.GetIncomingMessageProperty(RemoteEndpointMessageProperty.Name);
         location.Ip = property.Address;
         WcfEventSource.Log.LocationIdSet(location.Ip);
     }
 }
コード例 #10
0
 public static IEnumerable<int> FindAssociatedOrgUnitIds(int? organizationalUnitId, DescendantOption descentantOption, LinkedOption linkedOption, IOperationContext operationContext, ObjectContext objectContext)
 {
     return
         AssociatedOrgUnitFinder.FindAssociatedOrgUnits(objectContext, new AssociatedOrgUnitsDto
         {
             OrganizationalUnitId = organizationalUnitId,
             DescendantOption = descentantOption,
             LinkedOption = linkedOption
         });
 }
コード例 #11
0
 static void OnSay(Say msg, IOperationContext context)
 {
     RoomMember member;
     if (RoomMembers.TryGetValue(context.ReplyChannel, out member))
     {
         List<RoomMember> members;
         if (Rooms.TryGetValue(member.RoomName, out members))
         {
             members.ForEach((m) => m.UserChannel.Send(new RoomEvent() { UserName = member.UserName, Text = msg.Text }));
         }    
     }
 }
 /// <summary>
 /// Initialize the telemetry event with the client IP if available
 /// </summary>
 /// <param name="telemetry">The telemetry event</param>
 /// <param name="operation">The WCF operation context</param>
 protected override void OnInitialize(ITelemetry telemetry, IOperationContext operation)
 {
     if ( String.IsNullOrEmpty(telemetry.Context.Location.Ip) )
     {
         var location = operation.Request.Context.Location;
         if ( String.IsNullOrEmpty(location.Ip) )
         {
             UpdateClientIp(location, operation);
         }
         telemetry.Context.Location.Ip = location.Ip;
     }
 }
 /// <summary>
 /// Called when a telemetry item is available
 /// </summary>
 /// <param name="telemetry">The telemetry item to augment</param>
 /// <param name="operation">The operation context</param>
 protected override void OnInitialize(ITelemetry telemetry, IOperationContext operation)
 {
     var httpHeaders = operation.GetHttpRequestHeaders();
     if ( httpHeaders != null )
     {
         var userAgent = httpHeaders.Headers["User-Agent"];
         if ( !String.IsNullOrEmpty(userAgent) )
         {
             telemetry.Context.User.UserAgent = userAgent;
         }
     }
 }
コード例 #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RemoteObjectFetcher"/> class.
        /// Fetches remote CMIS Objects and adds them to the handled events.
        /// </summary>
        /// <param name="session">Session to be used.</param>
        /// <param name="storage">Storage to look for mapped objects.</param>
        public RemoteObjectFetcher(ISession session, IMetaDataStorage storage) {
            if (session == null) {
                throw new ArgumentNullException("session");
            }

            if (storage == null) {
                throw new ArgumentNullException("storage");
            }

            this.session = session;
            this.storage = storage;
            this.operationContext = OperationContextFactory.CreateNonCachingPathIncludingContext(this.session);
        }
コード例 #15
0
 public static IEnumerable<int> FindAssociatedOrgUnitIds(int? organizationalUnitId, DescendantOption descentantOption, LinkedOption linkedOption, IOperationContext operationContext, ObjectContext objectContext)
 {
     var key = string.Concat("AssociatedOrgUnitIds_", organizationalUnitId, "_", descentantOption, "_", linkedOption);
     //return operationContext.FindOrCreate<IEnumerable<int>>(key, () =>
     //{
         return
             AssociatedOrgUnitFinder.FindAssociatedOrgUnits(objectContext, new AssociatedOrgUnitsDto
             {
                 OrganizationalUnitId = organizationalUnitId,
                 DescendantOption = descentantOption,
                 LinkedOption = linkedOption
             });
     //});
 }
コード例 #16
0
        async public Task<JoinRoomResponse> Process(JoinRoomS2S request, IOperationContext context)
        {
            if (_roomMembers.Count >= MaxRoomSize)
                return new JoinRoomResponse { RetCode = JoinRoomRetCode.RoomIsFull };
            else
            {
                if (_roomMembers.Any(x => x.UserName == request.UserName))
                    return new JoinRoomResponse { RetCode = JoinRoomRetCode.NameIsTaken };

                _state = await _stateManager.GetOrAddAsync<IReliableDictionary<string, DateTime>>(ActorRef.Key.Id);

                try
                {
                    var callbackChannel = await _node.ConnectToCallbackChannel(request.CallbackChannelRef);

                    callbackChannel.DisconnectedEvent
                        .Subscribe(_ =>
                            Fiber.Process(() =>
                            {
                                _roomMembers.RemoveAll(x => x.UserName == request.UserName);

                                var leaveNotification = new RoomEvent { Text = "User left", UserName = request.UserName };
                                foreach (var roomMember in _roomMembers)
                                {
                                    roomMember.CallbackChannel.Send(leaveNotification);
                                }

                                if (_roomMembers.Count == 0)
                                    Dispose();

                            }));

                    var joinNotification = new RoomEvent { Text = "User joined", UserName = request.UserName };
                    foreach (var roomMember in _roomMembers)
                    {
                        roomMember.CallbackChannel.Send(joinNotification);
                    }

                    _roomMembers.Add(new RoomMember { UserName = request.UserName, CallbackChannel = callbackChannel });

                    return new JoinRoomResponse { RetCode = JoinRoomRetCode.Ok };
                }
                catch (Exception)
                {
                    return new JoinRoomResponse() { RetCode = JoinRoomRetCode.Retry };
                }
            }
        }
コード例 #17
0
        private Mock <ISession> CreateSessionMock(IOperationContext result)
        {
            Mock <ISession> sessionMock = new Mock <ISession>();

            sessionMock.Setup(s => s.CreateOperationContext(
                                  It.IsAny <HashSet <string> >(),
                                  It.IsAny <bool>(),
                                  It.IsAny <bool>(),
                                  It.IsAny <bool>(),
                                  It.IsAny <IncludeRelationshipsFlag>(),
                                  It.IsAny <HashSet <string> >(),
                                  It.IsAny <bool>(),
                                  It.IsAny <string>(),
                                  It.IsAny <bool>(),
                                  It.IsAny <int>())).Returns(result);
            return(sessionMock);
        }
コード例 #18
0
 public ResolverTaskDefinition(
     IOperationContext operationContext,
     IPreparedSelection selection,
     int responseIndex,
     ResultMap resultMap,
     object?parent,
     Path path,
     IImmutableDictionary <string, object?> scopedContextData)
 {
     OperationContext  = operationContext;
     Selection         = selection;
     ResponseIndex     = responseIndex;
     ResultMap         = resultMap;
     Parent            = parent;
     Path              = path;
     ScopedContextData = scopedContextData;
 }
コード例 #19
0
        /// <summary>
        /// Executes the operation's logic.
        /// </summary>
        /// <param name="context">A reference to the operation context.</param>
        protected override void Execute(IOperationContext context)
        {
            const byte FallbackIndex = 0xFF;

            var inThingContainer = this.FromLocation.DecodeContainer(context.Map, context.ContainerManager, out byte index, this.FromCreature);

            // Adjust index if this a map location.
            var existingThing = (this.FromLocation.Type == LocationType.Map && (inThingContainer is ITile fromTile)) ? fromTile.FindItemWithTypeId(this.FromTypeId) : inThingContainer?.FindThingAtIndex(index);

            if (existingThing == null || !(existingThing is IItem existingItem))
            {
                // Silent fail.
                return;
            }

            IThing thingCreated = context.ItemFactory.Create(ItemCreationArguments.WithTypeId(this.ToTypeId));

            if (thingCreated == null)
            {
                return;
            }

            // At this point, we have an item to change, and we were able to generate the new one, let's proceed.
            (bool replaceSuccessful, IThing replaceRemainder) = inThingContainer.ReplaceContent(context.ItemFactory, existingThing, thingCreated, index, existingItem.Amount);

            if (!replaceSuccessful || replaceRemainder != null)
            {
                context.GameApi.AddContentToContainerOrFallback(inThingContainer, ref replaceRemainder, FallbackIndex, includeTileAsFallback: true, this.GetRequestor(context.CreatureFinder));
            }

            if (replaceSuccessful)
            {
                if (inThingContainer is ITile atTile)
                {
                    this.SendNotification(
                        context,
                        new TileUpdatedNotification(
                            () => context.Map.FindPlayersThatCanSee(atTile.Location),
                            atTile.Location,
                            context.MapDescriptor.DescribeTile));

                    // Evaluate if the new item triggers a collision.
                    // context.EventRulesApi.EvaluateRules(this, EventRuleType.Collision, new CollisionEventRuleArguments(fromCylinder.Location, existingThing, this.GetRequestor(context.CreatureFinder)));
                }
            }
        }
コード例 #20
0
ファイル: CrawlStrategy.cs プロジェクト: buberuglu/CmisSync
            /// <summary>
            /// Crawl remote content, syncing down if needed.
            /// Meanwhile, cache remoteFiles and remoteFolders, they are output parameters that are used in CrawlLocalFiles/CrawlLocalFolders
            /// </summary>
            private bool CrawlRemote(IFolder remoteFolder, string localFolder, IList <string> remoteFiles, IList <string> remoteFolders)
            {
                bool success = true;

                SleepWhileSuspended();

                // Get all remote children.
                // TODO: use paging
                IOperationContext operationContext = session.CreateOperationContext();

                operationContext.MaxItemsPerPage = Int32.MaxValue;
                foreach (ICmisObject cmisObject in remoteFolder.GetChildren(operationContext))
                {
                    try
                    {
                        if (cmisObject is DotCMIS.Client.Impl.Folder)
                        {
                            // It is a CMIS folder.
                            IFolder remoteSubFolder = (IFolder)cmisObject;
                            CrawlRemoteFolder(remoteSubFolder, localFolder, remoteFolders);
                        }
                        else if (cmisObject is DotCMIS.Client.Impl.Document)
                        {
                            // It is a CMIS document.
                            IDocument remoteDocument = (IDocument)cmisObject;
                            CrawlRemoteDocument(remoteDocument, localFolder, remoteFiles);
                        }
                        else if (isLink(cmisObject))
                        {
                            Logger.Debug("Ignoring file '" + remoteFolder + "/" + cmisObject.Name + "' of type '" +
                                         cmisObject.ObjectType.Description + "'. Links are not currently handled.");
                        }
                        else
                        {
                            Logger.Warn("Unknown object type: '" + cmisObject.ObjectType.Description + "' (" + cmisObject.ObjectType.DisplayName
                                        + ") for object " + remoteFolder + "/" + cmisObject.Name);
                        }
                    }
                    catch (CmisBaseException e)
                    {
                        ProcessRecoverableException("Could not access remote object: " + cmisObject.Name, e);
                        success = false;
                    }
                }
                return(success);
            }
コード例 #21
0
        public override async Task DeleteAsync(IOperationDescription description, IOperationContext context)
        {
            Trace.WriteInfo(TraceType, "DeleteAsync called");
            description.ThrowIfNull(nameof(description));
            context.ThrowIfNull(nameof(context));

            string errorMessage;

            if (!this.ValidObjectType <ApplicationTypeVersionOperationDescription>(description, out errorMessage))
            {
                throw new InvalidCastException(errorMessage);
            }

            var appTypeDescription = (ApplicationTypeVersionOperationDescription)description;

            try
            {
                Trace.WriteInfo(
                    TraceType,
                    "DeleteAsync: Unprovisioning application type. Name: {0}. Version: {1}. Timeout: {2}",
                    appTypeDescription.TypeName,
                    appTypeDescription.TypeVersion,
                    context.OperationTimeout);
                await this.fabricClient.ApplicationManager.UnprovisionApplicationAsync(
                    appTypeDescription.TypeName,
                    appTypeDescription.TypeVersion,
                    context.OperationTimeout,
                    context.CancellationToken);

                Trace.WriteInfo(TraceType, "DeleteAsync: Unprovisioning call accepted");
            }
            catch (FabricElementNotFoundException nfe)
            {
                if (nfe.ErrorCode == FabricErrorCode.ApplicationTypeNotFound)
                {
                    Trace.WriteInfo(
                        TraceType,
                        "DeleteAsync: Application type not found. Name: {0}. Version: {1}",
                        appTypeDescription.TypeName,
                        appTypeDescription.TypeVersion);
                    return;
                }

                throw;
            }
        }
コード例 #22
0
        /// <summary>
        /// Called when a telemetry item is available
        /// </summary>
        /// <param name="telemetry">The telemetry item to augment</param>
        /// <param name="operation">The operation context</param>
        protected override void OnInitialize(ITelemetry telemetry, IOperationContext operation)
        {
            var ctxt = telemetry.Context.Operation;

            if (String.IsNullOrEmpty(ctxt.Name))
            {
                // TODO: consider including the HTTP verb
                // if service is using WebHttpBinding.
                ctxt.Name = operation.ContractName + '.' + operation.OperationName;
            }
            RequestTelemetry request = telemetry as RequestTelemetry;

            if (request != null)
            {
                request.Name = ctxt.Name;
            }
        }
コード例 #23
0
        /*--------------------------------------------------------------------------------------------*/
        public static void ClearOldTokens(IOperationContext pOpCtx, long pMemberId)
        {
            pOpCtx.Cache.Memory.RemoveOauthMembers(pMemberId);

            //OPTIMIZE: delete old OauthAccess vertices, or filter the Member->OauthAccess edges?

            IWeaverQuery q = Weave.Inst.Graph
                             .V.ExactIndex <Member>(x => x.VertexId, pMemberId)
                             .AuthenticatedByOauthAccesses.ToOauthAccess
                             .SideEffect(
                new WeaverStatementRemoveProperty <OauthAccess>(x => x.Token),
                new WeaverStatementRemoveProperty <OauthAccess>(x => x.Refresh)
                )
                             .ToQuery();

            pOpCtx.Data.Execute(q, "OauthAccess-ClearOldTokens");
        }
コード例 #24
0
        public static async Task ExecuteTasksAsync(
            IOperationContext operationContext)
        {
            if (operationContext.Execution.TaskBacklog.IsEmpty)
            {
                return;
            }

            var proposedTaskCount = operationContext.Operation.ProposedTaskCount;

            if (proposedTaskCount == 1)
            {
                await ExecuteResolversAsync(
                    operationContext.Execution,
                    HandleError,
                    operationContext.RequestAborted);
            }
            else
            {
                var tasks = new Task[proposedTaskCount];

                for (var i = 0; i < proposedTaskCount; i++)
                {
                    tasks[i] = ExecuteResolversAsync(
                        operationContext.Execution,
                        HandleError,
                        operationContext.RequestAborted);
                }

                await Task.WhenAll(tasks).ConfigureAwait(false);
            }

            void HandleError(Exception exception)
            {
                IError error =
                    operationContext.ErrorHandler
                    .CreateUnexpectedError(exception)
                    .SetCode(ErrorCodes.Execution.TaskProcessingError)
                    .Build();

                error = operationContext.ErrorHandler.Handle(error);

                // TODO : this error needs to be reported!
                operationContext.Result.AddError(error);
            }
        }
コード例 #25
0
        private static bool TryCompleteListValue(
            IOperationContext operationContext,
            MiddlewareContext resolverContext,
            ISelection selection,
            Path path,
            IType fieldType,
            string responseName,
            int responseIndex,
            object?result,
            List <ResolverTask> bufferedTasks,
            out object?completedValue)
        {
            IType elementType = fieldType.InnerType();

            if (elementType.Kind is TypeKind.NonNull)
            {
                elementType = elementType.InnerType();
            }

            if (elementType.Kind is TypeKind.Object or TypeKind.Interface or TypeKind.Union)
            {
                return(TryCompleteCompositeListValue(
                           operationContext,
                           resolverContext,
                           selection,
                           path,
                           fieldType,
                           responseName,
                           responseIndex,
                           result,
                           bufferedTasks,
                           out completedValue));
            }

            return(TryCompleteOtherListValue(
                       operationContext,
                       resolverContext,
                       selection,
                       path,
                       fieldType,
                       responseName,
                       responseIndex,
                       result,
                       bufferedTasks,
                       out completedValue));
        }
コード例 #26
0
        public AdvancedViewModel(ILumiaSettingsService lumiaSettingsService, IFileSystemOperations fileSystemOperations,
                                 UIServices uiServices, IDeploymentContext context, IOperationContext operationContext,
                                 IList <Meta <IDiskLayoutPreparer> > diskPreparers,
                                 IWindowsDeployer deployer,
                                 ILogCollector logCollector,
                                 IOperationProgress progress)
        {
            this.lumiaSettingsService = lumiaSettingsService;
            this.uiServices           = uiServices;
            this.context      = context;
            this.deployer     = deployer;
            this.logCollector = logCollector;
            this.progress     = progress;

            DiskPreparers = diskPreparers;

            DeleteDownloadedWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                      ReactiveCommand.CreateFromTask(() => DeleteDownloaded(fileSystemOperations)), uiServices.ContextDialog, operationContext);
            ForceDualBootWrapper = new CommandWrapper <Unit, Unit>(this, ReactiveCommand.CreateFromTask(ForceDualBoot),
                                                                   uiServices.ContextDialog, operationContext);
            ForceSingleBootWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                     ReactiveCommand.CreateFromTask(ForceDisableDualBoot), uiServices.ContextDialog, operationContext);

            BackupCommandWrapper =
                new CommandWrapper <Unit, Unit>(this, ReactiveCommand.CreateFromTask(Backup), uiServices.ContextDialog, operationContext);
            RestoreCommandWrapper =
                new CommandWrapper <Unit, Unit>(this, ReactiveCommand.CreateFromTask(Restore), uiServices.ContextDialog, operationContext);

            CollectLogsCommmandWrapper = new CommandWrapper <Unit, Unit>(this, ReactiveCommand.CreateFromTask(CollectLogs), uiServices.ContextDialog, operationContext);

            IsBusyObservable = Observable.Merge(DeleteDownloadedWrapper.Command.IsExecuting,
                                                BackupCommandWrapper.Command.IsExecuting, RestoreCommandWrapper.Command.IsExecuting,
                                                ForceDualBootWrapper.Command.IsExecuting, ForceSingleBootWrapper.Command.IsExecuting,
                                                CollectLogsCommmandWrapper.Command.IsExecuting);

            preparerUpdater = this.WhenAnyValue(x => x.SelectedPreparer)
                              .Where(x => x != null)
                              .Subscribe(x =>
            {
                context.DiskLayoutPreparer        = x.Value;
                lumiaSettingsService.DiskPreparer = (string)x.Metadata["Name"];
            });

            SelectedPreparer = GetInitialDiskPreparer();
        }
コード例 #27
0
        /// <inheritdoc/>
        public async Task CloseAsync(IOperationContext operationContext, IResultContext context)
        {
            // Here, if the file in the user file system is modified (not in-sync), you will send the file content,
            // creation time, modification time and attributes to the remote storage.
            // We also send ETag, to make sure the changes on the server, if any, are not overwritten.

            Logger.LogMessage("IFile.CloseAsync()", UserFileSystemPath);

            string userFileSystemFilePath = UserFileSystemPath;

            // In case the file is moved it does not exist in user file system when CloseAsync() is called.
            if (Engine.ChangesProcessingEnabled &&
                FsPath.Exists(userFileSystemFilePath) &&
                !FsPath.AvoidSync(userFileSystemFilePath))
            {
                // In case the file is overwritten it is converted to a regular file prior to CloseAsync().
                // we need to convert it back into file/folder placeholder.
                if (!PlaceholderItem.IsPlaceholder(userFileSystemFilePath))
                {
                    PlaceholderItem.ConvertToPlaceholder(userFileSystemFilePath, false);
                    Logger.LogMessage("Converted to placeholder", userFileSystemFilePath);
                }

                try
                {
                    if (PlaceholderItem.GetItem(userFileSystemFilePath).IsNew(VirtualDrive))
                    {
                        // Create new file in the remote storage.
                        await new RemoteStorageRawItem <IVirtualFile>(userFileSystemFilePath, VirtualDrive, Logger).CreateAsync();
                    }
                    else if (!PlaceholderItem.GetItem(userFileSystemFilePath).IsMoved())
                    {
                        // Send content to remote storage. Unlock if auto-locked.
                        await new RemoteStorageRawItem <IVirtualFile>(userFileSystemFilePath, VirtualDrive, Logger).UpdateAsync();
                    }
                }
                catch (IOException ex)
                {
                    // Either the file is already being synced in another thread or client or server file is blocked by concurrent process.
                    // This is a normal behaviour.
                    // The file must be synched by your synchronyzation service at a later time, when the file becomes available.
                    Logger.LogMessage("Failed to upload file. Possibly in use by an application or blocked for synchronization in another thread:", ex.Message);
                }
            }
        }
コード例 #28
0
        public void TestUpdateProperties()
        {
            string name1 = "port-test-folder1";
            string name2 = "port-test-folder2";
            string name3 = "port-test-folder3";

            IOperationContext oc = Session.CreateOperationContext();
            oc.CacheEnabled = false;

            IFolder newFolder = null;
            try
            {
                // create folder
                IFolder root = Session.GetRootFolder();
                newFolder = CreateFolder(root, name1);
                Assert.IsNotNull(newFolder);

                IFolder newFolder2 = (IFolder)Session.GetObject(newFolder, oc);
                Assert.IsNotNull(newFolder2);
                Assert.IsNotNull(name1, newFolder2.Name);

                IDictionary<string, object> updateProps = new Dictionary<string, object>();
                updateProps[PropertyIds.Name] = name2;

                newFolder2.UpdateProperties(updateProps);

                IFolder newFolder3 = (IFolder)Session.GetObject(newFolder, oc);
                Assert.IsNotNull(newFolder3);
                Assert.IsNotNull(name2, newFolder3.Name);

                newFolder3.Rename(name3);

                IFolder newFolder4 = (IFolder)Session.GetObject(newFolder, oc);
                Assert.IsNotNull(newFolder4);
                Assert.IsNotNull(name3, newFolder4.Name);
            }
            finally
            {
                if (newFolder != null)
                {
                    newFolder.DeleteTree(true, UnfileObject.Delete, true);
                    Assert.IsFalse(Session.Exists(newFolder));
                }
            }
        }
コード例 #29
0
        public AlfrescoService()
        {
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            parameters[DotCMIS.SessionParameter.BindingType] = BindingType.AtomPub;
            parameters[DotCMIS.SessionParameter.AtomPubUrl]  = "http://*****:*****@sw0rd12";

            SessionFactory factory = SessionFactory.NewInstance();

            IList <IRepository> repos = factory.GetRepositories(parameters);

            session = repos.ElementAt(0).CreateSession();

            operationContext             = session.CreateOperationContext();
            operationContext.IncludeAcls = false;
        }
コード例 #30
0
ファイル: ObjectSource.cs プロジェクト: fr830/OPCUA.NET
        /// <summary cref="NodeSource.ReadAttribute" />
        protected override ServiceResult ReadAttribute(IOperationContext context, uint attributeId, DataValue value)
        {
            switch (attributeId)
            {
            case Attributes.EventNotifier:
            {
                value.Value = EventNotifier;
                break;
            }

            default:
            {
                return(base.ReadAttribute(context, attributeId, value));
            }
            }

            return(ServiceResult.Good);
        }
コード例 #31
0
        private string GetHeader(IOperationContext context, string httpHeader, string soapHeader)
        {
            if (this.RequestAlreadyChecked(context))
            {
                return(null);
            }

            var httpHeaders = context.GetHttpRequestHeaders();

            if (httpHeaders != null)
            {
                return(httpHeaders.Headers[httpHeader]);
            }
            else
            {
                return(context.GetIncomingMessageHeader <string>(soapHeader, this.SoapHeaderNamespace));
            }
        }
        void ProcessCallbackMessage(IOperationContext operation)
        {
            var callbackHeader = operation.Message.GetHeader <CallbackHeader>();

            if (callbackHeader != null)
            {
                INetChannel callbackChannel;
                if (_callbackChannels.TryGetValue(callbackHeader.CallbackChannelId, out callbackChannel))
                {
                    operation.Message.RemoveHeader <CallbackHeader>();
                    callbackChannel.Send(operation.Message);
                }
                else
                {
                    operation.ReplyChannel.Send(new CallbackChannelDisconnected(callbackHeader.CallbackChannelId));
                }
            }
        }
コード例 #33
0
ファイル: AzureStorageApi.cs プロジェクト: sycomix/OLAF
        /// <summary>
        /// Delete the container with the specified name if it exists.
        /// </summary>
        /// <param name="containerName">Name of container to delete.</param>
        public async Task DeleteContainerAsync(string containerName)
        {
            using (IOperationContext azOp = L.Begin("Delete Azure Storage container"))
            {
                try
                {
                    CloudBlobClient    client    = GetCloudBlobClient();
                    CloudBlobContainer container = client.GetContainerReference(containerName);
                    await container.DeleteIfExistsAsync();

                    azOp.Complete();
                }
                catch (Exception e)
                {
                    L.Error(e, "Exception throw deleting Azure Storage container {c}.", containerName);
                }
            }
        }
コード例 #34
0
        /// <summary>
        /// Executes the operation's logic.
        /// </summary>
        /// <param name="context">A reference to the operation context.</param>
        protected override void Execute(IOperationContext context)
        {
            // Perform the actual, internal turn.
            this.Creature.Direction = this.Direction;

            // Send the notification if applicable.
            if (context.Map.GetTileAt(this.Creature.Location, out ITile playerTile))
            {
                var playerStackPos = playerTile.GetStackOrderOfThing(this.Creature);

                this.SendNotification(
                    context,
                    new CreatureTurnedNotification(
                        () => context.Map.PlayersThatCanSee(this.Creature.Location),
                        this.Creature,
                        playerStackPos));
            }
        }
コード例 #35
0
 public static bool TryComplete(
     IOperationContext operationContext,
     IMiddlewareContext middlewareContext,
     Path path,
     IType fieldType,
     object?result,
     out object?completedResult)
 {
     if (fieldType.IsNonNullType())
     {
         if (TryComplete(
                 operationContext,
                 middlewareContext,
                 path,
                 fieldType.InnerType(),
                 result,
                 out completedResult) &&
             completedResult is { })
コード例 #36
0
        /// <inheritdoc />
        public void Run(IOperationContext operationContext)
        {
            if (operationContext.CurrentSubpath == null)
            {
                return;
            }

            var controlPoint2 = operationContext.CurrentTransformationMatrix.Transform(new PdfPoint(X2, Y2));
            var end           = operationContext.CurrentTransformationMatrix.Transform(new PdfPoint(X3, Y3));

            operationContext.CurrentSubpath.BezierCurveTo(operationContext.CurrentPosition.X,
                                                          operationContext.CurrentPosition.Y,
                                                          controlPoint2.X,
                                                          controlPoint2.Y,
                                                          end.X,
                                                          end.Y);
            operationContext.CurrentPosition = end;
        }
コード例 #37
0
        /// <summary>
        /// Called when a telemetry item is available
        /// </summary>
        /// <param name="telemetry">The telemetry item to augment</param>
        /// <param name="operation">The operation context</param>
        protected override void OnInitialize(ITelemetry telemetry, IOperationContext operation)
        {
            if (String.IsNullOrEmpty(telemetry.Context.Operation.Name))
            {
                var opContext = operation.Request.Context.Operation;
                if (String.IsNullOrEmpty(opContext.Name))
                {
                    UpdateOperationContext(operation, opContext);
                }
                telemetry.Context.Operation.Name = opContext.Name;

                RequestTelemetry request = telemetry as RequestTelemetry;
                if (request != null)
                {
                    request.Name = opContext.Name;
                }
            }
        }
コード例 #38
0
        /// <inheritdoc/>
        public async Task GetChildrenAsync(string pattern, IOperationContext operationContext, IFolderListingResultContext resultContext)
        {
            Logger.LogMessage($"{nameof(IFolder)}.{nameof(GetChildrenAsync)}({pattern})", UserFileSystemPath);

            IEnumerable <FileSystemInfo> remoteStorageChildren = new DirectoryInfo(RemoteStoragePath).EnumerateFileSystemInfos(pattern);

            List <IFileSystemItemMetadata> userFileSystemChildren = new List <IFileSystemItemMetadata>();

            foreach (FileSystemInfo remoteStorageItem in remoteStorageChildren)
            {
                IFileSystemItemMetadata itemInfo = Mapping.GetUserFileSysteItemMetadata(remoteStorageItem);
                userFileSystemChildren.Add(itemInfo);
            }

            // To signal that the children enumeration is completed
            // always call ReturnChildren(), even if the folder is empty.
            resultContext.ReturnChildren(userFileSystemChildren.ToArray(), userFileSystemChildren.Count);
        }
コード例 #39
0
        ///<inheritdoc>
        public async Task MoveToAsync(string userFileSystemNewPath, IOperationContext operationContext, IConfirmationResultContext resultContext)
        {
            string userFileSystemOldPath = this.UserFileSystemPath;

            Logger.LogMessage($"{nameof(IFileSystemItem)}.{nameof(MoveToAsync)}()", UserFileSystemPath, userFileSystemNewPath);
            string remoteStorageNewPath = Mapping.MapPath(userFileSystemNewPath);
            string remoteStorageOldPath = RemoteStoragePath;

            if (File.Exists(RemoteStoragePath))
            {
                new FileInfo(RemoteStoragePath).MoveTo(remoteStorageNewPath);
            }
            else if (Directory.Exists(RemoteStoragePath))
            {
                new DirectoryInfo(RemoteStoragePath).MoveTo(remoteStorageNewPath);
            }
            Logger.LogMessage("Moved item in remote storage succesefully", userFileSystemOldPath, userFileSystemNewPath);
        }
コード例 #40
0
        /// <summary>
        /// Executes the operation's logic.
        /// </summary>
        /// <param name="context">A reference to the operation context.</param>
        protected override void Execute(IOperationContext context)
        {
            var targetLoginLocation = this.playerMetadata.LastLocation;

            if (context.Map[targetLoginLocation] == null)
            {
                targetLoginLocation = this.playerMetadata.StartingLocation;
            }

            var creationArguments = new PlayerCreationArguments()
            {
                Type          = CreatureType.Player,
                Metadata      = this.playerMetadata,
                PreselectedId = this.preselectedPlayerId,
            };

            if (!(context.CreatureFactory.CreateCreature(creationArguments) is IPlayer player))
            {
                context.Logger.LogWarning($"Unable to create player instance for {this.playerMetadata.Name}, aborting log in.");

                return;
            }

            if (!context.GameApi.AddCreatureToGame(targetLoginLocation, player))
            {
                // Unable to place the player in the map.
                var disconnectNotification = new DisconnectNotification(
                    player.YieldSingleItem(),
                    "Your character could not be placed on the map.\nPlease try again, or contact an administrator if the issue persists.");

                context.GameApi.SendNotification(disconnectNotification);

                return;
            }

            var descriptionTiles = context.Map.DescribeAt(player, player.Location);

            // TODO: In addition, we need to send the player's inventory, the first time login message + outfit window here if applicable.
            // And any VIP records here.
            this.SendNotification(context, new PlayerLoginNotification(player, player.Location, descriptionTiles, AnimatedEffect.BubbleBlue));
            this.SendNotification(context, new WorldLightChangedNotification(player.YieldSingleItem(), this.currentWorldLightLevel, this.currentWorldLightColor));
            this.SendNotification(context, new CreatureLightUpdateNotification(player.YieldSingleItem(), player));
            this.SendNotification(context, new TextMessageNotification(player.YieldSingleItem(), MessageType.Status, "This is a test message"));
        }
コード例 #41
0
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            IOperationContext context = WcfOperationContext.Current;

            if (context != null)
            {
                WcfOperationContext.StoreThreadContext(context);

                if (!this.LogTelemetryFor(context))
                {
                    WcfEventSource.Log.OperationIgnored(context.ContractName, context.ContractNamespace, context.OperationName);
                    return(null);
                }

                foreach (var mod in this.GetModules())
                {
                    Executor.ExceptionSafe(
                        mod.GetType().Name,
                        "OnBeginRequest",
                        mod.OnBeginRequest,
                        context);
                }

                foreach (var mod in this.GetModules())
                {
                    var tracer = mod as IWcfMessageTrace;
                    if (tracer != null)
                    {
                        Executor.ExceptionSafe(
                            mod.GetType().Name,
                            "OnTraceRequest",
                            tracer.OnTraceRequest,
                            context,
                            ref request);
                    }
                }
            }
            else
            {
                WcfEventSource.Log.NoOperationContextFound();
            }

            return(null);
        }
コード例 #42
0
        /// <inheritdoc/>
        public async Task CloseAsync(IOperationContext operationContext, IResultContext context)
        {
            // Here, if the file in user file system is modified (not in-sync), we send file content,
            // creation time, modification time and attributes to remote storage.
            // We also create new ETag, associate it with a file in user file system and send it to the server.

            LogMessage("IFile.CloseAsync()", this.FullPath);

            string userFileSystemFilePath = this.FullPath;

            // In case the file is moved it does not exist in user file system when Close() is called.
            if (!FsPath.Exists(userFileSystemFilePath) || FsPath.AvoidSync(userFileSystemFilePath))
            {
                return;
            }

            // In case the file is overwritten it is converted to a regular file prior to Close().
            // we need to convert it back into file/folder placeholder.
            if (!PlaceholderItem.IsPlaceholder(userFileSystemFilePath))
            {
                PlaceholderItem.ConvertToPlaceholder(userFileSystemFilePath, false);
                LogMessage("Converted to placeholder:", userFileSystemFilePath);
            }

            if (!PlaceholderItem.GetItem(userFileSystemFilePath).GetInSync())
            {
                LogMessage("Changed:", userFileSystemFilePath);

                string remoteStorageFilePath = Mapping.MapPath(userFileSystemFilePath);

                try
                {
                    await new RemoteStorageItem(remoteStorageFilePath).UpdateAsync(userFileSystemFilePath);
                    LogMessage("Updated succesefully:", remoteStorageFilePath);
                }
                catch (IOException ex)
                {
                    // Either the file is already being synced in another thread or client or server file is blocked by concurrent process.
                    // This is a normal behaviour.
                    // The file must be synched by your synchronyzation service at a later time, when the file becomes available.
                    LogMessage("Failed to upload file. Possibly in use by an application or blocked for synchronization in another thread:", ex.Message);
                }
            }
        }
        void IWcfTelemetryModule.OnEndRequest(IOperationContext operation, Message reply)
        {
            if (operation == null)
            {
                throw new ArgumentNullException("operation");
            }
            if (telemetryClient == null)
            {
                return;
            }

            RequestTelemetry telemetry = operation.Request;

            telemetry.Stop();

            // make some assumptions
            bool           isFault      = false;
            HttpStatusCode responseCode = HttpStatusCode.OK;

            if (reply != null)
            {
                isFault = reply.IsFault;
            }

            HttpResponseMessageProperty httpHeaders = operation.GetHttpResponseHeaders();

            if (httpHeaders != null)
            {
                responseCode = httpHeaders.StatusCode;
                if ((int)responseCode >= 400)
                {
                    isFault = true;
                }
            }
            else if (isFault)
            {
                responseCode = HttpStatusCode.InternalServerError;
            }

            telemetry.Success      = !isFault;
            telemetry.ResponseCode = responseCode.ToString("d");
            telemetry.Properties.Add("Protocol", telemetry.Url.Scheme);
            telemetryClient.TrackRequest(telemetry);
        }
コード例 #44
0
        /// <inheritdoc/>
        public async Task GetChildrenAsync(string pattern, IOperationContext operationContext, IFolderListingResultContext resultContext)
        {
            // This method has a 60 sec timeout.
            // To process longer requests and reset the timout timer call one of the following:
            // - resultContext.ReturnChildren() method.
            // - resultContext.ReportProgress() method.

            Logger.LogMessage($"IFolder.GetChildrenAsync({pattern})", UserFileSystemPath);

            IEnumerable <FileSystemItemBasicInfo> children = await new UserFolder(UserFileSystemPath).EnumerateChildrenAsync(pattern);

            // Filtering existing files/folders. This is only required to avoid extra errors in the log.
            List <IFileSystemItemBasicInfo> newChildren = new List <IFileSystemItemBasicInfo>();

            foreach (IFileSystemItemBasicInfo child in children)
            {
                string userFileSystemItemPath = Path.Combine(UserFileSystemPath, child.Name);
                if (!FsPath.Exists(userFileSystemItemPath))
                {
                    Logger.LogMessage("Creating", child.Name);
                    newChildren.Add(child);
                }
            }

            // To signal that the children enumeration is completed
            // always call ReturnChildren(), even if the folder is empty.
            resultContext.ReturnChildren(newChildren.ToArray(), newChildren.Count());


            // Save ETags and set "locked by another user" icon.
            foreach (FileSystemItemBasicInfo child in children)
            {
                string userFileSystemItemPath = Path.Combine(UserFileSystemPath, child.Name);

                // Create ETags.
                // ETags must correspond with a server file/folder, NOT with a client placeholder.
                // It should NOT be moved/deleted/updated when a placeholder in the user file system is moved/deleted/updated.
                // It should be moved/deleted when a file/folder in the remote storage is moved/deleted.
                ETag.SetETagAsync(userFileSystemItemPath, child.ETag);

                // Set the lock icon and read-only attribute, to indicate that the item is locked by another user.
                new UserFileSystemRawItem(userFileSystemItemPath).SetLockedByAnotherUserAsync(child.LockedByAnotherUser);
            }
        }
コード例 #45
0
        public void TestQuery()
        {
            if (Session.RepositoryInfo.Capabilities.QueryCapability == CapabilityQuery.None)
            {
                return;
            }

            foreach (IQueryResult qr in Session.Query("SELECT * FROM cmis:document", false))
            {
                Assert.IsNotNull(qr);
                Assert.IsNotNull(qr.GetPropertyValueByQueryName(PropertyIds.ObjectId));
                Assert.IsNotNull(qr.GetPropertyValueByQueryName(PropertyIds.Name));
            }

            int count = 0;

            foreach (IQueryResult qr in Session.Query("SELECT * FROM cmis:folder", false))
            {
                Assert.IsNotNull(qr);
                Assert.IsNotNull(qr.GetPropertyValueByQueryName(PropertyIds.ObjectId));
                Assert.IsNotNull(qr.GetPropertyValueByQueryName(PropertyIds.Name));
                count++;
            }

            Assert.IsTrue(count > 0);

            IOperationContext oc = OperationContextUtils.CreateMinimumOperationContext(PropertyIds.ObjectTypeId, PropertyIds.Name);

            IFolder rootFolder = Session.GetRootFolder(oc);
            bool    found      = false;

            foreach (ICmisObject obj in Session.QueryObjects("cmis:folder", null, false, oc))
            {
                Assert.IsNotNull(obj.Id);
                Assert.IsNotNull(obj.Name);

                if (obj.Id == rootFolder.Id)
                {
                    found = true;
                }
            }

            Assert.IsTrue(found);
        }
コード例 #46
0
        /// <summary>
        /// Executes the operation's logic.
        /// </summary>
        /// <param name="context">A reference to the operation context.</param>
        protected override void Execute(IOperationContext context)
        {
            context.Scheduler.CancelAllFor(this.Creature.Id, this.TypeToCancel);

            if (this.Creature is IPlayer player)
            {
                if (this.TypeToCancel == typeof(IOperation) && player is ICombatant playerAsCombatant)
                {
                    playerAsCombatant.SetAttackTarget(null);
                }

                this.SendNotification(
                    context,
                    new GenericNotification(
                        () => player.YieldSingleItem(),
                        new PlayerCancelAttackPacket(),
                        new PlayerCancelWalkPacket(this.Creature.Direction.GetClientSafeDirection())));
            }
        }
        async Task<JoinRoomResponse> OnRoomJoin(JoinRoom msg, IOperationContext context)
        {
            var room = await _rooms.GetActor(new ActorKey(msg.RoomName));

            var callbackRef = _callbacksNode.ExposeAsCallbackChannel(this);
            var joinRoomOnServer = new JoinRoomS2S()
            {
                CallbackChannelRef = callbackRef,
                RoomName = msg.RoomName,
                UserName = msg.UserName
            };
            var reply = await room.SendAsync<JoinRoomResponse>(joinRoomOnServer, context);
            if (reply.RetCode == JoinRoomRetCode.Ok)
            {
                _room = room;
                _userName = msg.UserName;
            }

            return reply;
        }
 public Task<Message> Process(Func<IOperationContext, Task<Message>> next, IOperationContext context)
 {
     Func<IOperationContext, Task<Message>> handler;
     if (_messageHandlingConfig.TryGetHandlerFor(context.Message.GetType(), out handler))
     {
         return handler(context);
     }
     else if (next != null)
     {
         return next(context);
     }
     else if (_throwIfUnhandled)
     {
         throw new ProcessingException(BasicErrorCode.DispatcherFuncNotFound);
     }
     else
     {
         return Task.FromResult<Message>(null);
     }
 }
        async Task<JoinRoomResponse> OnRoomJoin(JoinRoom msg, IOperationContext context)
        {
            var room = ActorProxy.Create<ISFRoomActor>(new ActorId(msg.RoomName));

            await room.SubscribeAsync(this);

            var joinRoomOnServer = new JoinRoomS2S()
            {
                RoomName = msg.RoomName,
                UserName = msg.UserName
            };
            var reply = await room.JoinRoom(joinRoomOnServer);
            if (reply.RetCode == JoinRoomRetCode.Ok)
            {
                _room = room;
                _userName = msg.UserName;
            }

            return reply;
        }
        void IWcfTelemetryModule.OnError(IOperationContext operation, Exception error)
        {
            if ( operation == null )
                throw new ArgumentNullException("operation");
            if ( error == null )
                throw new ArgumentNullException("error");
            if ( telemetryClient == null )
                return;

            ExceptionTelemetry telemetry = new ExceptionTelemetry(error);
            if ( error is FaultException )
            {
                telemetry.SeverityLevel = SeverityLevel.Error;
                telemetry.HandledAt = ExceptionHandledAt.UserCode;
            } else
            {
                telemetry.SeverityLevel = SeverityLevel.Critical;
                telemetry.HandledAt = ExceptionHandledAt.Platform;
            }
            telemetryClient.TrackException(error);
        }
コード例 #51
0
ファイル: client-objects.cs プロジェクト: emrul/CmisSync
        public IDocument GetObjectOfLatestVersion(bool major, IOperationContext context)
        {
            string objectId;
            string versionSeriesId;

            Lock();
            try
            {
                objectId = ObjectId;
                versionSeriesId = VersionSeriesId;
            }
            finally
            {
                Unlock();
            }

            if (versionSeriesId == null)
            {
                throw new CmisRuntimeException("Version series id is unknown!");
            }

            IObjectData objectData = Binding.GetVersioningService().GetObjectOfLatestVersion(RepositoryId, objectId, versionSeriesId, major,
                context.FilterString, context.IncludeAllowableActions, context.IncludeRelationships, context.RenditionFilterString,
                context.IncludePolicies, context.IncludeAcls, null);

            IDocument result = Session.ObjectFactory.ConvertObject(objectData, context) as IDocument;
            if (result == null)
            {
                throw new CmisRuntimeException("Latest version is not a document!");
            }

            return result;
        }
コード例 #52
0
ファイル: client-objects.cs プロジェクト: emrul/CmisSync
        public IList<IDocument> GetAllVersions(IOperationContext context)
        {
            string objectId;
            string versionSeriesId;

            Lock();
            try
            {
                objectId = ObjectId;
                versionSeriesId = VersionSeriesId;
            }
            finally
            {
                Unlock();
            }

            IList<IObjectData> versions = Binding.GetVersioningService().GetAllVersions(RepositoryId, objectId, versionSeriesId,
                context.FilterString, context.IncludeAllowableActions, null);

            IObjectFactory of = Session.ObjectFactory;

            IList<IDocument> result = new List<IDocument>();
            if (versions != null)
            {
                foreach (IObjectData objectData in versions)
                {
                    IDocument doc = of.ConvertObject(objectData, context) as IDocument;
                    if (doc == null)
                    {
                        // should not happen...
                        continue;
                    }

                    result.Add(doc);
                }
            }

            return result;
        }
コード例 #53
0
ファイル: client-objects.cs プロジェクト: emrul/CmisSync
        protected void Initialize(ISession session, IObjectType objectType, IObjectData objectData, IOperationContext context)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }

            if (objectType == null)
            {
                throw new ArgumentNullException("objectType");
            }

            if (objectType.PropertyDefinitions == null || objectType.PropertyDefinitions.Count < 9)
            {
                // there must be at least the 9 standard properties that all objects have
                throw new ArgumentException("Object type must have property defintions!");
            }

            this.Session = session;
            this.objectType = objectType;
            this.extensions = new Dictionary<ExtensionLevel, IList<ICmisExtensionElement>>();
            this.CreationContext = new OperationContext(context);
            this.RefreshTimestamp = DateTime.UtcNow;

            IObjectFactory of = Session.ObjectFactory;

            if (objectData != null)
            {
                // handle properties
                if (objectData.Properties != null)
                {
                    properties = of.ConvertProperties(objectType, objectData.Properties);
                    extensions[ExtensionLevel.Properties] = objectData.Properties.Extensions;
                }

                // handle allowable actions
                if (objectData.AllowableActions != null)
                {
                    allowableActions = objectData.AllowableActions;
                    extensions[ExtensionLevel.AllowableActions] = objectData.AllowableActions.Extensions;
                }

                // handle renditions
                if (objectData.Renditions != null)
                {
                    renditions = new List<IRendition>();
                    foreach (IRenditionData rd in objectData.Renditions)
                    {
                        renditions.Add(of.ConvertRendition(Id, rd));
                    }
                }

                // handle ACL
                if (objectData.Acl != null)
                {
                    acl = objectData.Acl;
                    extensions[ExtensionLevel.Acl] = objectData.Acl.Extensions;
                }

                // handle policies
                if (objectData.PolicyIds != null && objectData.PolicyIds.PolicyIds != null)
                {
                    policies = new List<IPolicy>();
                    foreach (string pid in objectData.PolicyIds.PolicyIds)
                    {
                        IPolicy policy = Session.GetObject(Session.CreateObjectId(pid)) as IPolicy;
                        if (policy != null)
                        {
                            policies.Add(policy);
                        }
                    }
                    extensions[ExtensionLevel.Policies] = objectData.PolicyIds.Extensions;
                }

                // handle relationships
                if (objectData.Relationships != null)
                {
                    relationships = new List<IRelationship>();
                    foreach (IObjectData rod in objectData.Relationships)
                    {
                        IRelationship relationship = of.ConvertObject(rod, CreationContext) as IRelationship;
                        if (relationship != null)
                        {
                            relationships.Add(relationship);
                        }
                    }
                }

                extensions[ExtensionLevel.Object] = objectData.Extensions;
            }
        }
コード例 #54
0
ファイル: client-objects.cs プロジェクト: emrul/CmisSync
        // operations

        public IDocument Copy(IObjectId targetFolderId, IDictionary<string, object> properties, VersioningState? versioningState,
                IList<IPolicy> policies, IList<IAce> addAces, IList<IAce> removeAces, IOperationContext context)
        {

            IObjectId newId = Session.CreateDocumentFromSource(this, properties, targetFolderId, versioningState, policies, addAces, removeAces);

            // if no context is provided the object will not be fetched
            if (context == null || newId == null)
            {
                return null;
            }
            // get the new object
            IDocument newDoc = Session.GetObject(newId, context) as IDocument;
            if (newDoc == null)
            {
                throw new CmisRuntimeException("Newly created object is not a document! New id: " + newId);
            }

            return newDoc;
        }
コード例 #55
0
ファイル: client-objects.cs プロジェクト: emrul/CmisSync
 public Document(ISession session, IObjectType objectType, IObjectData objectData, IOperationContext context)
 {
     Initialize(session, objectType, objectData, context);
 }
コード例 #56
0
ファイル: client-objects.cs プロジェクト: emrul/CmisSync
        public IDocument GetRenditionDocument(IOperationContext context)
        {
            if (RenditionDocumentId == null)
            {
                return null;
            }

            return session.GetObject(session.CreateObjectId(RenditionDocumentId), context) as IDocument;
        }
コード例 #57
0
ファイル: client-objects.cs プロジェクト: emrul/CmisSync
        public ICmisObject GetTarget(IOperationContext context)
        {
            Lock();
            try
            {
                IObjectId targetId = TargetId;
                if (targetId == null)
                {
                    return null;
                }

                return Session.GetObject(targetId, context);
            }
            finally
            {
                Unlock();
            }
        }
コード例 #58
0
ファイル: client-objects.cs プロジェクト: emrul/CmisSync
        public ICmisObject GetSource(IOperationContext context)
        {
            Lock();
            try
            {
                IObjectId sourceId = SourceId;
                if (sourceId == null)
                {
                    return null;
                }

                return Session.GetObject(sourceId, context);
            }
            finally
            {
                Unlock();
            }
        }
コード例 #59
0
ファイル: client-objects.cs プロジェクト: emrul/CmisSync
 public Relationship(ISession session, IObjectType objectType, IObjectData objectData, IOperationContext context)
 {
     Initialize(session, objectType, objectData, context);
 }
コード例 #60
-1
        async Task<OperationResult> Process(TestStateful msg, IOperationContext arg2)
        {
            using (var trans = _stateManager.CreateTransaction())
            {
                _state = await _stateManager.GetOrAddAsync<IReliableDictionary<string, DateTime>>(ActorRef.Key.Id);
                await _state.AddOrUpdateAsync(trans, ActorRef.Key.Id, (x) => DateTime.UtcNow, (x, _) => DateTime.UtcNow);

                await trans.CommitAsync();
            }

            return OperationResult.Success;
        }