Пример #1
0
        /// <summary>
        /// Deletes data by the given primary key value.
        /// </summary>
        /// <param name="tableName">Name of the table.</param>
        /// <param name="primaryKeyValues">The primary key values.</param>
        /// <returns><c>true</c> if delete data success, <c>false</c> otherwise.</returns>
        public bool Delete(string tableName, params object[] primaryKeyValues)
        {
            try
            {
                if (database != null && primaryKeyValues != null)
                {
                    using (IBox box = database.Cube())
                    {
                        for (int i = 0, length = primaryKeyValues.Length; i < length; ++i)
                        {
                            object primaryKeyValue = primaryKeyValues[i];
                            box.Bind(tableName, primaryKeyValue).Delete();
                        }

                        CommitResult result = box.Commit();

                        if (result.Equals(CommitResult.OK))
                        {
                            return(true);
                        }
                        else
                        {
                            DebugLogger.LogError(result.GetErrorMsg(box), this);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                DebugLogger.LogException(exception, this);
            }

            return(false);
        }
Пример #2
0
        /// <summary>
        /// Updates data.
        /// </summary>
        /// <typeparam name="T">The type definition of data.</typeparam>
        /// <param name="tableName">Name of the table.</param>
        /// <param name="values">The list of data.</param>
        /// <returns><c>true</c> if update the list of data success, <c>false</c> otherwise.</returns>
        public bool Update <T>(string tableName, params T[] values) where T : class
        {
            try
            {
                if (database != null && values != null)
                {
                    using (IBox box = database.Cube())
                    {
                        for (int i = 0, length = values.Length; i < length; ++i)
                        {
                            T data = values[i];
                            box.Bind(tableName).Update <T>(data);
                        }

                        CommitResult result = box.Commit();

                        if (result.Equals(CommitResult.OK))
                        {
                            return(true);
                        }
                        else
                        {
                            DebugLogger.LogError(result.GetErrorMsg(box), this);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                DebugLogger.LogException(exception, this);
            }

            return(false);
        }
Пример #3
0
        public CommitResult Commit()
        {
            CommitResult result = new CommitResult();

            try
            {
                if (_RCMDbContext.SaveChanges() > 0)
                {
                    return(new CommitResult(success: true));
                }
                else
                {
                    result.AddError(new DataNotModifiedException());
                }
            }
            catch (DbUpdateException ex)
            {
                result.AddError(ex);
            }
            catch (Exception ex)
            {
                result.AddError(ex);
            }

            return(result);
        }
 private void LogSuccessfulResults(CommitResult commitResult)
 {
     _loggerService.WriteMessage("Commit info:");
     _loggerService.WriteMessage($"\tCommit digest: {commitResult.CommitDigest}");
     _loggerService.WriteMessage($"\tBranch: {commitResult.Branch}");
     _loggerService.WriteMessage("\tFiles updated:");
     commitResult.ContentFiles.ForEach(file => _loggerService.WriteMessage($"\t\t{file}"));
 }
Пример #5
0
        private OperationResult <TEntity> DatabaseResult(CommitResult commitResult, TEntity entity = null)
        {
            if (commitResult.Success)
            {
                return(new OperationResult <TEntity>(OperationStatus.Successful, entity));
            }

            return(new OperationResult <TEntity>(OperationStatus.DatabaseError, commitResult.Exception));
        }
Пример #6
0
        public IUnitOfWork <ICommunityDbContext> GetUnitOfWork()
        {
            Mock <IUnitOfWork <ICommunityDbContext> > mock = new Mock <IUnitOfWork <ICommunityDbContext> >();

            mock.Setup(uow => uow.CommitAsync())
            .ReturnsAsync(CommitResult.Ok());

            return(mock.Object);
        }
Пример #7
0
        private async Task <IActionResult> CommitAsync()
        {
            CommitResult result = await _unitOfWork.CommitAsync();

            if (!result.Success)
            {
                return(BadRequest(result.Exception.Message));
            }

            return(Ok());
        }
        protected async Task <bool> CommitAsync()
        {
            CommitResult commitResult = await _unitOfWork.CommitAsync();

            if (commitResult.Success)
            {
                return(true);
            }

            return(false);
        }
Пример #9
0
 public string Put(long id, [FromBody] string value)
 {
     using (var box = App.Auto.Cube())
     {
         User u = box["User", id].Select <User>();
         u.ImageURL = value;
         u.Time     = DateTime.Now;
         box["User"].Update(u);
         CommitResult cr = box.Commit();
         return(cr.ToString());
     }
 }
        private async Task <CommitResult> WaitForIngestionAsync(IMcrStatusClient statusClient)
        {
            CommitResult commitResult = null;

            DateTime startTime  = DateTime.Now;
            bool     isComplete = false;

            while (!isComplete)
            {
                commitResult = await statusClient.GetCommitResultAsync(Options.CommitDigest);

                foreach (CommitStatus commitStatus in commitResult.Value)
                {
                    _loggerService.WriteMessage(
                        $"Readme status results for commit digest '{Options.CommitDigest}' with request ID '{commitStatus.OnboardingRequestId}': {commitStatus.OverallStatus}");

                    switch (commitStatus.OverallStatus)
                    {
                    case StageStatus.Processing:
                    case StageStatus.NotStarted:
                        await Task.Delay(Options.RequeryDelay);

                        break;

                    case StageStatus.Failed:
                        _loggerService.WriteError(await GetFailureResultsAsync(statusClient, commitStatus));
                        break;

                    case StageStatus.Succeeded:
                        isComplete = true;
                        break;

                    case StageStatus.NotApplicable:
                    default:
                        throw new NotSupportedException(
                                  $"Unexpected status for commit digest '{Options.CommitDigest}' with request ID '{commitStatus.OnboardingRequestId}: {commitStatus.OverallStatus}");
                    }
                }

                if (commitResult.Value.All(status => status.OverallStatus == StageStatus.Failed))
                {
                    _loggerService.WriteError("Doc ingestion failed.");
                    _environmentService.Exit(1);
                }

                if (DateTime.Now - startTime >= Options.WaitTimeout)
                {
                    throw new TimeoutException($"Timed out after '{Options.WaitTimeout}' waiting for the docs to be ingested.");
                }
            }

            return(commitResult);
        }
Пример #11
0
        public CommitResult TryCommit(IAsyncCompletionSession session, ITextBuffer buffer, CompletionItem item, char typedChar, CancellationToken token)
        {
            var etoitem = item.Properties["eto"] as Designer.Completion.CompletionItem;

            // only complete on '.' for child properties.
            if (typedChar == '.' && !etoitem.Behavior.HasFlag(Designer.Completion.CompletionBehavior.ChildProperty))
            {
                return(CommitResult.Unhandled);
            }

            var span = session.ApplicableToSpan.GetSpan(buffer.CurrentSnapshot);

            span = FindTokenSpan(span);
            var text   = item.InsertText;
            var result = CommitResult.Handled;

            switch (typedChar)
            {
            case '.':
                if (!text.EndsWith("."))
                {
                    text += ".";
                }
                result = new CommitResult(true, CommitBehavior.CancelCommit | CommitBehavior.SuppressFurtherTypeCharCommandHandlers);
                break;

            case '/':
                text  += " />";
                result = new CommitResult(true, CommitBehavior.SuppressFurtherTypeCharCommandHandlers);
                break;

            case '\n':
                result = new CommitResult(true, CommitBehavior.RaiseFurtherReturnKeyAndTabKeyCommandHandlers);
                break;
            }
            var newSnapshot = buffer.Replace(span, text);
            var endLocation = new SnapshotPoint(newSnapshot, span.End.Position + text.Length - span.Length);

            switch (typedChar)
            {
            case '.':
                session.OpenOrUpdate(new CompletionTrigger(CompletionTriggerReason.Insertion, newSnapshot, '.'), endLocation, token);
                break;
            }
            var ch = endLocation.GetChar();

            if (ch == '\'' || ch == '"')
            {
                endLocation += 1;
                textView.Caret.MoveTo(endLocation);
            }
            return(result);
        }
Пример #12
0
        //with transaction, faster
        private static async Task <String> indexTextWithTranAsync(String url, bool onlyDelete)
        {
            return(await pageLockAsync(url, async() =>
            {
                using (var box = App.Auto.Cube())
                {
                    Page defaultPage = null;
                    foreach (Page p in box.Select <Page>("from Page where url==?", url).ToArray())
                    {
                        engine.indexText(box, p.id, p.content, true);
                        engine.indexText(box, p.rankUpId(), p.rankUpDescription(), true);
                        box["Page", p.id].Delete();
                        defaultPage = p;
                    }

                    if (onlyDelete)
                    {
                        return box.Commit() == CommitResult.OK ? "deleted" : "not deleted";
                    }
                    {
                        Page p = await Html.GetAsync(url);
                        if (p == null)
                        {
                            //p = defaultPage;
                        }
                        if (p == null)
                        {
                            return "temporarily unreachable";
                        }
                        else
                        {
                            if (p.id == 0)
                            {
                                p.id = box.NewId();
                            }
                            box["Page"].Insert(p);
                            engine.indexText(box, p.id, p.content, false);
                            engine.indexText(box, p.rankUpId(), p.rankUpDescription(), false);

                            CommitResult cr = box.Commit();
                            if (cr != CommitResult.OK)
                            {
                                return cr.GetErrorMsg(box);
                            }
                            return p.url;
                        }
                    }
                }
            }));
        }
Пример #13
0
        protected async Task <bool> CommitAsync()
        {
            CommitResult result = await _unitOfWork.CommitAsync();

            if (result.Success)
            {
                _logger.LogInformation("Commit dos dados feito com sucesso.");
                return(true);
            }
            else
            {
                _logger.LogError(result.Exception, "Commit dos dados falhou: {message}", result.Exception.Message);
                return(false);
            }
        }
Пример #14
0
            /// <summary>
            /// 提交数据修改
            /// </summary>
            public CommitResult Commit()
            {
                var commitResult = new CommitResult();

                try
                {
                    commitResult.ExecuteNum = SaveChange();
                    commitResult.State      = true;
                }
                catch (Exception ex)
                {
                    commitResult.State     = false;
                    commitResult.Exception = ex;
                }
                return(commitResult);
            }
Пример #15
0
            /// <summary>
            /// 异步提交数据修改
            /// </summary>
            public async Task <CommitResult> CommitAsync(CancellationToken cancellationToken = default(CancellationToken))
            {
                var commitResult = new CommitResult();

                try
                {
                    commitResult.ExecuteNum = await SaveChangeAsync(cancellationToken);

                    commitResult.State = true;
                }
                catch (Exception ex)
                {
                    commitResult.State     = false;
                    commitResult.Exception = ex;
                }
                return(commitResult);
            }
Пример #16
0
        private void CommitNewObjects()
        {
            if (m_commitQueue.Count == 0)
            {
                return;
            }

            CommitResult result = m_client.CommitObjects(m_ownGuid, m_commitQueue.ToArray());

            for (int i = 0; i < result.ObjectsIds.Count; i++)
            {
                UpdateMaxId(result.ObjectsIds[i]);

                m_commitQueue[i].Id = result.ObjectsIds[i];
            }

            m_commitQueue.Clear();
        }
        public override async Task ExecuteAsync()
        {
            _loggerService.WriteHeading("QUERYING COMMIT RESULT");

            if (!Options.IsDryRun)
            {
                IMcrStatusClient statusClient = _mcrStatusClientFactory.Create(
                    Options.ServicePrincipal.Tenant, Options.ServicePrincipal.ClientId, Options.ServicePrincipal.Secret);

                CommitResult result = await WaitForIngestionAsync(statusClient);

                LogSuccessfulResults(result);
            }

            _loggerService.WriteMessage();

            _loggerService.WriteMessage("Doc ingestion successfully completed!");
        }
Пример #18
0
        public static String indexText(String name, bool isDelete)
        {
            String url = getUrl(name);

            using (var box = SDB.search_db.Cube()) {
                foreach (Page p in box.Select <Page>("from Page where url==?", url))
                {
                    engine.indexText(box, p.id, p.content.ToString(), true);
                    box ["Page", p.id].Delete();
                    break;
                }
                box.Commit().Assert();
            }
            if (isDelete)
            {
                return("deleted");
            }
            {
                Page p = Page.Get(url);
                if (p == null)
                {
                    return("temporarily unreachable");
                }
                else
                {
                    using (var box = SDB.search_db.Cube()) {
                        p.id = box.NewId();
                        box ["Page"].Insert(p);
                        engine.indexText(box, p.id, p.content.ToString(), false);
                        CommitResult cr = box.Commit();
                        cr.Assert(cr.GetErrorMsg(box));
                    }
                    urlList.Enqueue(p.url);
                    while (urlList.Count > 3)
                    {
                        String t;
                        urlList.TryDequeue(out t);
                    }
                    return(p.url);
                }
            }
        }
        public async Task Consume(ConsumeContext <UserRegisteredIntegrationEvent> context)
        {
            Image defaultAvatarImage = new Image(_communityDefaultOptions.Value.DefaultAvatarImageUrlPath, _communityDefaultOptions.Value.DefaultAvatarImageName);

            Profile profile = new Profile(
                context.Message.UserId,
                context.Message.Genre,
                defaultAvatarImage,
                context.Message.Name,
                context.Message.Username,
                new EmailAddress(context.Message.Email),
                context.Message.BirthDate);

            await _profileRepository.RegisterAsync(profile);

            CommitResult result = await _unitOfWork.CommitAsync();

            if (!result.Success)
            {
                _logger.LogCritical(result.Exception, "Falha ao criar Profile em [Community]: {exception}", result.Exception.Message);
                throw result.Exception;
            }
        }
Пример #20
0
        public CommitResult CommitObjects(Guid playerGuid, List <GameObject> objects)
        {
            CommitResult result = new CommitResult()
            {
                ObjectsIds = new List <int>(objects.Count)
            };

            foreach (var obj in objects)
            {
                if (obj is Plane)
                {
                    m_playerToPlaneMapping[playerGuid] = obj as Plane; // If player commit plane when it his own plane
                }
                IntegrityDataHelper.ProcessRecieved(obj, World);

                World.AddGameObject(obj);

                result.ObjectsIds.Add(obj.Id.Value);
            }

            LogMessage(string.Format("{0} object(s) has been commited (last ID={1})", objects.Count, m_lastObjectID));

            return(result);
        }
Пример #21
0
        public async Task <CommitResult> CommitAsync()
        {
            try
            {
                int modifiedRows = await _dbContext.SaveChangesAsync();

                if (modifiedRows > 0)
                {
                    return(CommitResult.Ok());
                }
                else
                {
                    throw new DataNotModifiedException();
                }
            }
            catch (DataNotModifiedException dnmex)
            {
                return(CommitResult.Failure(dnmex));
            }
            catch (DbUpdateException dbex)
            {
                return(CommitResult.Failure(dbex));
            }
            catch (InvalidOperationException ioex)
            {
                return(CommitResult.Failure(ioex));
            }
            catch (NotSupportedException nsex)
            {
                return(CommitResult.Failure(nsex));
            }
            catch (Exception ex)
            {
                return(CommitResult.Failure(ex));
            }
        }
Пример #22
0
        public string Commit(string workspaceId, object changeSet)
        {
            Guid guidWorkspaceId = Guid.Parse(workspaceId);
            //transform changeSet into IsolatedChangeSet object
            IsolatedChangeSet <Guid, object, EdgeData> serverChangeSet = ChangeSetParser.Parse(changeSet);
            //commit changes
            CommitResult <Guid> commitResult =
                ServerContextSingleton.Instance.ServerContext.Commit(guidWorkspaceId, serverChangeSet);

            String resultSnapshotId             = commitResult.ResultSnapshotId.ToString();
            Dictionary <string, string> mapping = new Dictionary <string, string>();

            foreach (KeyValuePair <Guid, Guid> mapObject in commitResult.Mapping)
            {
                mapping.Add(mapObject.Key.ToString(), mapObject.Value.ToString());
            }

            CommitResult <String> commitResultString = new CommitResult <string>(resultSnapshotId, mapping);

            Dictionary <String, CommitResult <String> > rez = new Dictionary <string, CommitResult <string> >();

            rez.Add(RESULT, commitResultString);
            return(rez.ToJSON());
        }
        public async Task <CommitResult> CheckCommitAsync(int resourceId, Guid sessionId)
        {
            if (resourceId <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(resourceId));
            }

            var fullUri = new Uri(this.mdsBaseUrl, $"Files({resourceId})/UploadSessions({sessionId})/MetadataService.CheckCommit");

            var method = Convert.ToString(HttpMethod.Get);

            await this.SetAuthorizationHeaderInHttpClientAsync(resourceId);

            OnNavigating(new NavigatingEventArgs(resourceId, method, fullUri));

            var policy = GetRetryPolicy(resourceId, method, fullUri);

            var httpResponse = await policy
                               .ExecuteAsync(() => _httpClient.GetAsync(fullUri, this.cancellationToken));

            var content = await httpResponse.Content.ReadAsStringAsync();

            OnNavigated(new NavigatedEventArgs(resourceId, method, fullUri, httpResponse.StatusCode.ToString(), content));

            switch (httpResponse.StatusCode)
            {
            case HttpStatusCode.OK:
            {
                var clientResponse = JsonConvert.DeserializeObject <UploadSession>(content);

                var result = new CommitResult
                {
                    StatusCode = httpResponse.StatusCode,
                    FullUri    = fullUri,
                    Session    = clientResponse
                };

                return(result);
            }

            case HttpStatusCode.Accepted:
            {
                // the server is processing this asynchronously
                var result = new CommitResult
                {
                    StatusCode = httpResponse.StatusCode,
                    FullUri    = fullUri
                };

                return(result);
            }

            case HttpStatusCode.BadRequest:
            {
                return(new CommitResult
                    {
                        StatusCode = httpResponse.StatusCode,
                        FullUri = fullUri,
                        Error = content
                    });
            }

            default:
            {
                return(new CommitResult
                    {
                        StatusCode = httpResponse.StatusCode,
                        Error = content,
                        FullUri = fullUri
                    });
            }
            }
        }
Пример #24
0
        public static void TestiBoxDB()
        {
            DB.Root(root);
            long idbFile = 1L;

            BoxSystem.DBDebug.DeleteDBFiles(idbFile);

            using var server = new AppServer();

            using var db = server.GetInstance(idbFile);
            Console.Write("Database Transaction Test: ");
            using var box1 = db.Cube();
            box1["T1"].Insert(new T1 {
                Id = -1, Value = (-1).ToString()
            });

            using var box2 = db.Cube();
            box2["T1"].Insert(new T1 {
                Id = -2, Value = (-2).ToString()
            });

            var transaction1 = box1.Select <T1>("from T1").ToArray();
            var transaction2 = box2.Select <T1>("from T1").ToArray();

            if (transaction1.Length == 1 && transaction1[0].Id == -1 &&
                transaction2.Length == 1 && transaction2[0].Id == -2)
            {
                Console.WriteLine("Succeeded");
            }
            else
            {
                Console.WriteLine("Failed");
            }
            box1.Commit();
            box2.Commit();


            BoxSystem.DBDebug.StartWatch();
            int count = 0;

            Parallel.For(0, threadCount, (p) =>
            {
                using var box = db.Cube();
                for (int i = 0; i < batchCount; i++)
                {
                    var id = (p * batchCount) + i;
                    box["T1"].Insert(new T1 {
                        Id = id, Value = id.ToString()
                    });
                    Interlocked.Add(ref count, 1);
                }
                CommitResult cr = box.Commit();

                var minId = p * batchCount + 0;
                var maxId = p * batchCount + batchCount;
                for (int r = 0; r < reinterationSelect; r++)
                {
                    using (var boxt = db.Cube())
                    {
                        var reader = boxt.Select <T1>("from T1 where Id>=? & Id<? order by Id", minId, maxId).GetEnumerator();
                        var ti     = minId;
                        while (reader.MoveNext())
                        {
                            var iv = reader.Current.Id;
                            if (ti != iv)
                            {
                                throw new Exception(ti + "  " + iv);
                            }
                            ti++;
                        }
                        if (ti != maxId)
                        {
                            throw new Exception();
                        }
                    }
                }
            }
                         );

            if (count != (batchCount * threadCount))
            {
                throw new Exception(count + "  " + (batchCount * threadCount));
            }
            var avg = (int)(count / BoxSystem.DBDebug.StopWatch().TotalSeconds);

            Console.WriteLine("iBoxDB Insert:" + count.ToString("N0") + "  AVG: " + avg.ToString("N0") + " objects/s");

            //---------Update-----------------//
            BoxSystem.DBDebug.StartWatch();
            count = 0;
            Parallel.For(0, threadCount, (p) =>
            {
                using var box = db.Cube();
                for (int i = 0; i < batchCount; i++)
                {
                    var id  = (p * batchCount) + i;
                    var t   = box["T1", id].Update <T1>();
                    t.Value = "A" + t.Value;
                    Interlocked.Add(ref count, 1);
                }
                CommitResult cr = box.Commit();



                var minId = p * batchCount + 0;
                var maxId = p * batchCount + batchCount;

                for (int r = 0; r < reinterationSelect; r++)
                {
                    using var boxt = db.Cube();
                    var reader     = boxt.Select <T1>("from T1 where Id>=? & Id<? order by Id", minId, maxId).GetEnumerator();
                    var ti         = minId;
                    while (reader.MoveNext())
                    {
                        var iv = reader.Current.Id;
                        if (ti != iv)
                        {
                            throw new Exception(ti + "  " + iv);
                        }
                        if (reader.Current.Value != ("A" + iv))
                        {
                            throw new Exception();
                        }
                        ti++;
                    }
                    if (ti != maxId)
                    {
                        throw new Exception();
                    }
                }
            }
                         );

            if (count != (batchCount * threadCount))
            {
                throw new Exception(count + "  " + (batchCount * threadCount));
            }
            avg = (int)(count / BoxSystem.DBDebug.StopWatch().TotalSeconds);
            Console.WriteLine("iBoxDB Update:" + count.ToString("N0") + "  AVG: " + avg.ToString("N0") + " objects/s");

            //-------Delete---------------//
            BoxSystem.DBDebug.StartWatch();
            count = 0;
            Parallel.For(0, threadCount, (p) =>
            {
                var minId = p * batchCount + 0;
                var maxId = p * batchCount + batchCount;
                for (int r = 0; r < reinterationSelect; r++)
                {
                    using var boxt = db.Cube();
                    var reader     = boxt.Select <T1>("from T1 where Id>=? & Id<? order by Id", minId, maxId).GetEnumerator();
                    var ti         = minId;
                    while (reader.MoveNext())
                    {
                        var iv = reader.Current.Id;
                        if (ti != iv)
                        {
                            throw new Exception(ti + "  " + iv);
                        }
                        if (reader.Current.Value != ("A" + iv))
                        {
                            throw new Exception();
                        }
                        ti++;
                    }
                    if (ti != maxId)
                    {
                        throw new Exception();
                    }
                }


                using var box = db.Cube();
                for (int i = 0; i < batchCount; i++)
                {
                    var id = (p * batchCount) + i;
                    box["T1", id].Delete();
                    Interlocked.Add(ref count, 1);
                }
                CommitResult cr = box.Commit();
            }
                         );

            if (count != (batchCount * threadCount))
            {
                throw new Exception(count + "  " + (batchCount * threadCount));
            }
            avg = (int)(count / BoxSystem.DBDebug.StopWatch().TotalSeconds);
            Console.WriteLine("iBoxDB Delete:" + count.ToString("N0") + "  AVG: " + avg.ToString("N0") + " objects/s");

            if (db.Get().SelectCount("from T1") != 2) //transaction insert 2 more objects.
            {
                throw new Exception();
            }
        }
Пример #25
0
    void Start()
    {
        if (auto == null)
        {
            DB.Root(Application.persistentDataPath);

            DB db = new DB(5);
            //load from Resources
            //db = new DB(((TextAsset)(UnityEngine.Resources.Load("db2"))).bytes);

            // two tables(Player,Item) and their keys(ID,Name)
            db.GetConfig().EnsureTable <Player> ("Player", "ID");

            // set max-length to 20 , default is 32
            db.GetConfig().EnsureTable <Item> ("Item", "Name(20)");

            {
                // [Optional]
                // if device has small memory & disk
                db.MinConfig();
                // smaller DB file size
                db.GetConfig().DBConfig.FileIncSize = 1;
            }

            auto = db.Open();
        }
        //Transaction
        using (var box = auto.Cube()) {
            // set " limit 0,1 " will faster
            if (box.SelectCount("from Item limit 0,1") == 0)
            {
                // insert player's score to database
                var player = new Player {
                    Name  = "Player_" + (int)Time.realtimeSinceStartup,
                    Score = DateTime.Now.Second + (int)Time.realtimeSinceStartup + 1,
                    ID    = box.NewId()
                };
                box ["Player"].Insert(player);


                //dynamic data, each object has different properties
                var shield = new Item()
                {
                    Name = "Shield", Position = 1
                };
                shield ["attributes"] = new string[] { "earth" };
                box ["Item"].Insert(shield);


                var spear = new Item()
                {
                    Name = "Spear", Position = 2
                };
                spear ["attributes"]     = new string[] { "metal", "fire" };
                spear ["attachedSkills"] = new string[] { "dragonFire" };
                box ["Item"].Insert(spear);


                var composedItem = new Item()
                {
                    Name = "ComposedItem", Position = 3, XP = 0
                };
                composedItem ["Source1"] = "Shield";
                composedItem ["Source2"] = "Spear";
                composedItem ["level"]   = 0;
                box ["Item"].Insert(composedItem);
            }
            CommitResult cr = box.Commit();
        }
        DrawToString();
    }
Пример #26
0
        public async Task UploadFileIsSuccessful()
        {
            // arrange
            var    fileName = "foo.txt";
            string filePath = Path.Combine(Path.GetTempPath(), fileName);

            File.WriteAllText(filePath, "123");
            long fullFileSize = new FileInfo(filePath).Length;
            var  hashForFile  = new MD5FileHasher().CalculateHashForFile(filePath);

            int resourceId      = 1;
            var checkFileResult = new CheckFileResult
            {
                StatusCode          = HttpStatusCode.NoContent,
                LastModified        = DateTimeOffset.UtcNow,
                FileNameOnServer    = fileName,
                HashForFileOnServer = "MyHash"
            };

            mockFileService.Setup(
                service => service.CheckFileAsync(resourceId))
            .ReturnsAsync(checkFileResult);

            var sessionId     = Guid.NewGuid();
            var uploadSession = new UploadSession
            {
                SessionId = sessionId,
                FileUploadChunkSizeInBytes       = 1,
                FileUploadMaxFileSizeInMegabytes = 10
            };
            var createSessionResult = new CreateSessionResult
            {
                StatusCode = HttpStatusCode.OK,
                Session    = uploadSession
            };

            mockFileService.Setup(
                service => service.CreateNewUploadSessionAsync(resourceId))
            .ReturnsAsync(createSessionResult);

            var fileSplitter     = new FileSplitter();
            var countOfFileParts = fileSplitter.GetCountOfFileParts(createSessionResult.Session.FileUploadChunkSizeInBytes, fullFileSize);

            var uploadStreamResult = new UploadStreamResult
            {
                StatusCode    = HttpStatusCode.OK,
                PartsUploaded = 1
            };

            mockFileService.Setup(
                service => service.UploadStreamAsync(resourceId, sessionId,
                                                     It.IsAny <Stream>(), It.IsAny <FilePart>(), fileName, fullFileSize, countOfFileParts))
            .ReturnsAsync(uploadStreamResult);

            var commitResult = new CommitResult
            {
                StatusCode = HttpStatusCode.OK,
                Session    = uploadSession
            };

            mockFileService.Setup(
                service => service.CommitAsync(resourceId, sessionId, fileName, hashForFile, fullFileSize,
                                               It.IsAny <IList <FilePart> >()))
            .ReturnsAsync(commitResult);

            // act
            await this.classUnderTest.UploadFileAsync(resourceId, filePath, this.cancellationToken);

            // assert
            mockFileService.Verify(
                service => service.CheckFileAsync(1),
                Times.Once);

            mockFileService.Verify(
                service => service.CreateNewUploadSessionAsync(resourceId),
                Times.Once);

            mockFileService.Verify(
                service => service.UploadStreamAsync(resourceId, sessionId,
                                                     It.IsAny <Stream>(), It.IsAny <FilePart>(), fileName, fullFileSize, countOfFileParts),
                Times.Exactly(countOfFileParts));

            mockFileService.Verify(
                service => service.CommitAsync(resourceId, sessionId, fileName, hashForFile, fullFileSize,
                                               It.IsAny <IList <FilePart> >()),
                Times.Once);
        }
Пример #27
0
        /// <summary>
        /// Invokes events for object change subscriptions
        /// </summary>
        /// <param name="workspaceId">Workspace Id which is making the changes</param>
        /// <param name="commitResult">Commit result to process</param>
        public void InvokeEvents(Guid workspaceId, CommitResult<Guid> commitResult)
        {
            lock (subscriptions)
            {
                Collection<Guid> removalList = new Collection<Guid>();

                foreach (var item in subscriptions.Values)
                {
                    // Was the object changed in the commit?
                    if (commitResult.Mapping.ContainsKey(item.InstanceId))
                    {
                        // Is the change originating from different workspace OR we wanted events from same workspace
                        bool doThrowEvent = !item.WorkspaceId.Equals(workspaceId) || item.NotifyChangesFromSameWorkspace;

                        // If property was specified
                        if (doThrowEvent && !item.MemberId.Equals(Guid.Empty))
                        {
                            var isScalarMember = typesService.IsScalarType(typesService.GetMemberTypeId(item.MemberId));

                            if (isScalarMember)
                            {
                                // Get scalar property values
                                var oldValue = objectInstancesService.GetScalarInstanceMember(item.InstanceId, item.MemberId);
                                var newValue = objectInstancesService.GetScalarInstanceMember(commitResult.Mapping[item.InstanceId], item.MemberId);

                                // Throw event if they are not the same
                                doThrowEvent = Comparer.Default.Compare(oldValue, newValue) != 0;
                            }
                            else
                            {
                                bool isPermanent;
                                // Get reference property values
                                var oldValue = objectInstancesService.GetReferenceInstanceMember(item.InstanceId, item.MemberId, out isPermanent);
                                var newValue = objectInstancesService.GetReferenceInstanceMember(commitResult.Mapping[item.InstanceId], item.MemberId, out isPermanent);

                                // Throw event if they are not pointing to the same Ids
                                doThrowEvent = Comparer.Default.Compare(oldValue, newValue) != 0;
                            }
                        }

                        if (doThrowEvent)
                        {
                            var args = new ObjectChangedEventArgs(commitResult.ResultSnapshotId, item.InstanceId, commitResult.Mapping[item.InstanceId], new Subscription(item.SubscriptionId, item.WorkspaceId));
                            // Throw event
                            item.Del(this, args);

                            if (args.RenewSubscription)
                            {
                                // Renew subscription to new version
                                item.InstanceId = commitResult.Mapping[item.InstanceId];
                            }
                            else
                            {
                                // Register for removal
                                removalList.Add(item.SubscriptionId);
                            }
                        }
                        else
                        {
                            // Automatically renew subscriptions when processing own changes
                            item.InstanceId = commitResult.Mapping[item.InstanceId];
                        }
                    }
                }

                // Remove items which are not renewed
                foreach (var item in removalList)
                {
                    subscriptions.Remove(item);
                }
            }
        }
Пример #28
0
 public CommitResult Commit()
 {
     return(CommitResult.Ok());
 }
Пример #29
0
        /// <summary>
        /// Invokes events for object change subscriptions
        /// </summary>
        /// <param name="workspaceId">Workspace Id which is making the changes</param>
        /// <param name="commitResult">Commit result to process</param>
        public void InvokeEvents(Guid workspaceId, CommitResult <Guid> commitResult)
        {
            lock (subscriptions)
            {
                Collection <Guid> removalList = new Collection <Guid>();

                foreach (var item in subscriptions.Values)
                {
                    // Was the object changed in the commit?
                    if (commitResult.Mapping.ContainsKey(item.InstanceId))
                    {
                        // Is the change originating from different workspace OR we wanted events from same workspace
                        bool doThrowEvent = !item.WorkspaceId.Equals(workspaceId) || item.NotifyChangesFromSameWorkspace;

                        // If property was specified
                        if (doThrowEvent && !item.MemberId.Equals(Guid.Empty))
                        {
                            var isScalarMember = typesService.IsScalarType(typesService.GetMemberTypeId(item.MemberId));

                            if (isScalarMember)
                            {
                                // Get scalar property values
                                var oldValue = objectInstancesService.GetScalarInstanceMember(item.InstanceId, item.MemberId);
                                var newValue = objectInstancesService.GetScalarInstanceMember(commitResult.Mapping[item.InstanceId], item.MemberId);

                                // Throw event if they are not the same
                                doThrowEvent = Comparer.Default.Compare(oldValue, newValue) != 0;
                            }
                            else
                            {
                                bool isPermanent;
                                // Get reference property values
                                var oldValue = objectInstancesService.GetReferenceInstanceMember(item.InstanceId, item.MemberId, out isPermanent);
                                var newValue = objectInstancesService.GetReferenceInstanceMember(commitResult.Mapping[item.InstanceId], item.MemberId, out isPermanent);

                                // Throw event if they are not pointing to the same Ids
                                doThrowEvent = Comparer.Default.Compare(oldValue, newValue) != 0;
                            }
                        }

                        if (doThrowEvent)
                        {
                            var args = new ObjectChangedEventArgs(commitResult.ResultSnapshotId, item.InstanceId, commitResult.Mapping[item.InstanceId], new Subscription(item.SubscriptionId, item.WorkspaceId));
                            // Throw event
                            item.Del(this, args);

                            if (args.RenewSubscription)
                            {
                                // Renew subscription to new version
                                item.InstanceId = commitResult.Mapping[item.InstanceId];
                            }
                            else
                            {
                                // Register for removal
                                removalList.Add(item.SubscriptionId);
                            }
                        }
                        else
                        {
                            // Automatically renew subscriptions when processing own changes
                            item.InstanceId = commitResult.Mapping[item.InstanceId];
                        }
                    }
                }

                // Remove items which are not renewed
                foreach (var item in removalList)
                {
                    subscriptions.Remove(item);
                }
            }
        }
        /// <inheritdoc />
        /// <summary>
        /// This calls POST Files({resourceId})/UploadSessions({sessionId})/MetadataService.Commit
        /// </summary>
        /// <param name="resourceId"></param>
        /// <param name="sessionId"></param>
        /// <param name="filename"></param>
        /// <param name="fileHash"></param>
        /// <param name="fileSize"></param>
        /// <param name="utFileParts"></param>
        /// <returns></returns>
        public async Task <CommitResult> CommitAsync(int resourceId, Guid sessionId,
                                                     string filename, string fileHash, long fileSize, IList <FilePart> utFileParts)
        {
            if (resourceId <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(resourceId));
            }

            var fullUri = new Uri(this.mdsBaseUrl, $"Files({resourceId})/UploadSessions({sessionId})/MetadataService.Commit");

            var method = Convert.ToString(HttpMethod.Post);

            await this.SetAuthorizationHeaderInHttpClientAsync(resourceId);

            OnNavigating(new NavigatingEventArgs(resourceId, method, fullUri));

            var form = new
            {
                FileDetail = new
                {
                    FileName = filename,
                    Hash     = fileHash,
                    Size     = fileSize,
                    Parts    = utFileParts.Select(p => new FilePart
                    {
                        Id     = p.Id,
                        Hash   = p.Hash,
                        Size   = p.Size,
                        Offset = p.Offset
                    })
                               .ToList()
                }
            };

            var policy = GetRetryPolicy(resourceId, method, fullUri);

            var httpResponse = await policy
                               .ExecuteAsync(() =>
            {
                var jsonSerializerSettings = new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                };
                return(_httpClient.PostAsync(
                           fullUri,
                           new StringContent(JsonConvert.SerializeObject(form, jsonSerializerSettings),
                                             Encoding.UTF8,
                                             ApplicationJsonMediaType),
                           this.cancellationToken));
            });

            var content = await httpResponse.Content.ReadAsStringAsync();

            OnNavigated(new NavigatedEventArgs(resourceId, method, fullUri, httpResponse.StatusCode.ToString(), content));

            switch (httpResponse.StatusCode)
            {
            case HttpStatusCode.OK:
            {
                var clientResponse = JsonConvert.DeserializeObject <UploadSession>(content);

                var result = new CommitResult
                {
                    StatusCode = httpResponse.StatusCode,
                    FullUri    = fullUri,
                    Session    = clientResponse
                };

                return(result);
            }

            case HttpStatusCode.Accepted:
            {
                // the server is processing this asynchronously
                var result = new CommitResult
                {
                    StatusCode = httpResponse.StatusCode,
                    FullUri    = fullUri
                };

                return(result);
            }

            case HttpStatusCode.BadRequest:
            {
                return(new CommitResult
                    {
                        StatusCode = httpResponse.StatusCode,
                        FullUri = fullUri,
                        Error = content
                    });
            }

            default:
            {
                return(new CommitResult
                    {
                        StatusCode = httpResponse.StatusCode,
                        Error = content,
                        FullUri = fullUri
                    });
            }
            }
        }
Пример #31
0
        public string Commit(string workspaceId, object changeSet)
        {
            Guid guidWorkspaceId = Guid.Parse(workspaceId);
            //transform changeSet into IsolatedChangeSet object
            IsolatedChangeSet<Guid, object, EdgeData> serverChangeSet = ChangeSetParser.Parse(changeSet);
            //commit changes
            CommitResult<Guid> commitResult =
                ServerContextSingleton.Instance.ServerContext.Commit(guidWorkspaceId, serverChangeSet);

            String resultSnapshotId = commitResult.ResultSnapshotId.ToString();
            Dictionary<string, string> mapping = new Dictionary<string, string>();
            foreach (KeyValuePair<Guid, Guid> mapObject in commitResult.Mapping)
            {
                mapping.Add(mapObject.Key.ToString(), mapObject.Value.ToString());
            }

            CommitResult<String> commitResultString = new CommitResult<string>(resultSnapshotId, mapping);

            Dictionary<String, CommitResult<String>> rez = new Dictionary<string, CommitResult<string>>();
            rez.Add(RESULT, commitResultString);
            return rez.ToJSON();
        }