public JsonResult InsertNewCharacterAJAX(int? gameID, string charName, int? classID, int? factionID, int? level) { //Do some Validation CommitResponse newCharResponse = new CommitResponse(); if (gameID == null || charName == null || classID == null || factionID == null || level == null) { newCharResponse.success = false; newCharResponse.errorMsg = Errors.INVALID_CHARACTER_INFORMATION; } if (newCharResponse.success) { MemCharacter memChar = new MemCharacter() { MemberID = MemberInfo.MemberID, CharacterName = charName, ClassID = (int)classID, FactionID = factionID, GameID = (int)gameID, LVL = level }; newCharResponse = charInterface.AddNewCharacter(memChar, new int[0]); } return new JsonResult() { Data = newCharResponse }; }
public CommitResponse AddNewCharacter(MemCharacter newMemChar, int[] roleIDs) { CommitResponse response = new CommitResponse(); //Validate CharData? //Validate Role Data if (!ValidateUserRoles(newMemChar.ClassID, roleIDs)) { response.success = false; response.errorMsg = Errors.ROLE_IS_NOT_VALID_FOR_CLASS; } if (response.success) { newMemChar.CreateDT = DateTime.Now; newMemChar.LastModifiedDT = DateTime.Now; try { // Insert Member Data LeetRaidsDB.MemCharacters.InsertOnSubmit(newMemChar); LeetRaidsDB.SubmitChanges(); response.ReturnData = newMemChar; // Insert RoleData CommitResponse rolesResponse = AddRolesForCharacter(newMemChar.CharacterID, roleIDs, newMemChar.ClassID); } catch (Exception ex) { response.success = false; response.errorMsg = Errors.INSERT_CHARACTER_FAILED; if (!Convert.ToBoolean(ConfigurationManager.AppSettings["RETHROW_HANDLED_ERRORS"])) { } else { throw ex; } } } return response; }
public ActionResult EditCharacter(MemCharacter memChar) { //Assert that the current member is editing charater data only for his account bool valid = true; if (memChar.MemberID != 0 && MemberInfo.MemberID != memChar.MemberID) { valid = false; ModelState.AddModelError("MemberHoax", Errors.CAN_NOT_OPERATE_ON_OTHER_MEMBERS_DATA); } //Assert User Selected Some Roles int[] roleIDs = (!String.IsNullOrEmpty(Request["RoleID"])) ? Request["RoleID"].Split(new char[] { ',' }).Select(roleID => Convert.ToInt32(roleID)).ToArray() : new int[0]; if (roleIDs.Length == 0) { valid = false; ModelState.AddModelError("NoRolesSelected", Errors.NO_ROLES_SELECTED); } memChar.MemberID = (memChar.MemberID != 0) ? memChar.MemberID : MemberInfo.MemberID; if (valid) { CommitResponse editCharResponse = charInterface.EditCharacter(memChar); if (editCharResponse.success) { CommitResponse roleUpdate; if (charInterface.ValidateUserRoles(memChar.ClassID, roleIDs)) { charInterface.DeleteRolesForCharacter(memChar.CharacterID); roleUpdate = charInterface.AddRolesForCharacter(memChar.CharacterID, roleIDs, memChar.ClassID); } else { roleUpdate = new CommitResponse() { success = false }; ModelState.AddModelError("RoleInvalid", Errors.ROLE_IS_NOT_VALID_FOR_CLASS); } if (roleUpdate.success) { TempData[GlobalConst.TEMPDATA_CONFIRMATION_MESSAGE] = "Character was successfully edited."; return RedirectToAction("Confirmation", "Shared"); } } else { ModelState.AddModelError("EditFailed", Errors.EDIT_CHARACTER_FAILED); } } //return RedirectToAction("EditCharacter", new { id = memChar.CharacterID }); return View(memChar); }
public JsonResult AddCharacterToEventAJAX(int? charID, int? roleID) { CommitResponse commitResponse = new CommitResponse(); if (charID != null && roleID != null) { commitResponse = eventInterface.AddNewEventAttendee((int)charID, CurrentEvent.EventID, (int)roleID, String.Empty, (int)ATTENDEE_STATUS.INVITED, null); } return new JsonResult() { Data = commitResponse }; }
public CommitResponse AddBasicRestrictions(int eventID, int? serverID, int? factionID) { CommitResponse response = new CommitResponse(); EventRestriction evtRestriction = GetEventRestrictionOrCreate(eventID); evtRestriction.ServerID = serverID; evtRestriction.FactionID = factionID; //LeetRaidsDB.EventRestrictions.InsertOnSubmit(evtRestriction); LeetRaidsDB.SubmitChanges(); response.success = true; return response; }
public CommitResponse InsertMember(Member member) { CommitResponse response = new CommitResponse(); var uniqueUserName = !LeetRaidsDB.Members.Any(mem => mem.UserName == member.UserName); if (!uniqueUserName) { response.Errors.Add(Errors.USERNAME_TAKEN); } if (member.UserName.Length < 5 || member.UserName.Length > 15) { response.Errors.Add(Errors.CHECK_USER_NAME); } if (!member.AgreedToTerms) { response.Errors.Add(Errors.MUST_AGREE_TO_TERMS); } if (member.Password.Length < 5 || member.Password.Length > 14) { response.Errors.Add(Errors.CHECK_PASSWORD); } if(!Validate.Email(member.Email)) { response.Errors.Add(Errors.INVALID_EMAIL); } response.success = (response.Errors.Count < 1); if (response.success) { try { LeetRaidsDB.Members.InsertOnSubmit(member); LeetRaidsDB.SubmitChanges(); } catch (Exception ex) { if (!Convert.ToBoolean(ConfigurationManager.AppSettings["RETHROW_HANDLED_ERRORS"])) { response.success = false; } else { throw ex; } } } return response; }
/// <summary>Snippet for CommitAsync</summary> public async Task CommitAsync() { // Snippet: CommitAsync(string, IEnumerable<Write>, CallSettings) // Additional: CommitAsync(string, IEnumerable<Write>, CancellationToken) // Create client FirestoreClient firestoreClient = await FirestoreClient.CreateAsync(); // Initialize request argument(s) string database = ""; IEnumerable <Write> writes = new Write[] { new Write(), }; // Make the request CommitResponse response = await firestoreClient.CommitAsync(database, writes); // End snippet }
public void Commit1() { // Snippet: Commit(string,CommitRequest.Types.Mode,ByteString,IEnumerable<Mutation>,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; CommitRequest.Types.Mode mode = CommitRequest.Types.Mode.Unspecified; ByteString transaction = ByteString.CopyFromUtf8(""); IEnumerable <Mutation> mutations = new List <Mutation>(); // Make the request CommitResponse response = datastoreClient.Commit(projectId, mode, transaction, mutations); // End snippet }
public void Commit_RequestObject() { // Snippet: Commit(CommitRequest,CallSettings) // Create client FirestoreClient firestoreClient = FirestoreClient.Create(); // Initialize request argument(s) CommitRequest request = new CommitRequest { Database = new DatabaseRootName("[PROJECT]", "[DATABASE]").ToString(), Writes = { }, }; // Make the request CommitResponse response = firestoreClient.Commit(request); // End snippet }
private static void PropagateKeys <T>(IList <T> values, CommitResponse response, Action <T, Key> keyPropagation) { if (keyPropagation == null) { return; } for (int i = 0; i < values.Count; i++) { var key = response.MutationResults[i].Key; if (key != null) { keyPropagation(values[i], key); } } }
public void Commit_RequestObject() { // Snippet: Commit(CommitRequest,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) CommitRequest request = new CommitRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Mutations = { }, }; // Make the request CommitResponse response = spannerClient.Commit(request); // End snippet }
/// <summary>Snippet for CommitAsync</summary> public async Task CommitAsync() { // Snippet: CommitAsync(string,IEnumerable<Write>,CallSettings) // Additional: CommitAsync(string,IEnumerable<Write>,CancellationToken) // Create client FirestoreClient firestoreClient = await FirestoreClient.CreateAsync(); // Initialize request argument(s) string formattedDatabase = new DatabaseRootName("[PROJECT]", "[DATABASE]").ToString(); IEnumerable <Write> writes = new List <Write>(); // Make the request CommitResponse response = await firestoreClient.CommitAsync(formattedDatabase, writes); // End snippet }
public async void CreateContact_ContactInvalid_False() { //arrange var contact = ContactFaker.GetContactContactNameLess(); var createContactCommand = new CreateContactCommand( contactName: contact.Name, contactPhone: contact.PhoneNumber, contactBirthDate: contact.BirthDate, contactTypeId: contact.ContactTypeId ); _dependencyResolverMock .Setup(x => x.Resolve <IContactTypeRepository>()) .Returns(_contactTypeRepositoryMock.Object); _dependencyResolverMock .Setup(x => x.Resolve <IContactRepository>()) .Returns(_contactRepositoryMock.Object); _dependencyResolverMock .Setup(x => x.Resolve <IMediatorHandler>()) .Returns(_mediatorHandler.Object); _contactTypeRepositoryMock.Setup(x => x.GetByIdAsync(createContactCommand.ContactTypeId)) .Returns(Task.FromResult(contact.ContactType)); _contactRepositoryMock.Setup(x => x.CommitAsync()) .Returns(Task.FromResult(CommitResponse.Ok())); var handler = new ContactCommandHandler(_dependencyResolverMock.Object); //act var result = await handler.Handle(createContactCommand, new CancellationToken()); //Assert Assert.False(result.Success); _contactTypeRepositoryMock.Verify(x => x.GetByIdAsync(createContactCommand.ContactTypeId), Times.Once); _mediatorHandler.Verify(x => x.NotifyDomainNotification(It.IsAny <DomainNotification>()), Times.AtLeastOnce); _contactRepositoryMock.Verify(x => x.AddAsync(It.IsAny <Contact>()), Times.Never); _contactRepositoryMock.Verify(x => x.CommitAsync(), Times.Never); }
public async Task CommitAsync1() { // Snippet: CommitAsync(string,ByteString,IEnumerable<Mutation>,CallSettings) // Additional: CommitAsync(string,ByteString,IEnumerable<Mutation>,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) string formattedSession = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").ToString(); ByteString transactionId = ByteString.CopyFromUtf8(""); IEnumerable <Mutation> mutations = new List <Mutation>(); // Make the request CommitResponse response = await spannerClient.CommitAsync(formattedSession, transactionId, mutations); // End snippet }
/// <summary>Snippet for Commit</summary> public void CommitRequestObject() { // Snippet: Commit(CommitRequest, CallSettings) // Create client FirestoreClient firestoreClient = FirestoreClient.Create(); // Initialize request argument(s) CommitRequest request = new CommitRequest { Database = "", Writes = { new Write(), }, Transaction = ByteString.Empty, }; // Make the request CommitResponse response = firestoreClient.Commit(request); // End snippet }
public async Task CommitAsync2() { // Snippet: CommitAsync(string,CommitRequest.Types.Mode,IEnumerable<Mutation>,CallSettings) // Additional: CommitAsync(string,CommitRequest.Types.Mode,IEnumerable<Mutation>,CancellationToken) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; CommitRequest.Types.Mode mode = CommitRequest.Types.Mode.Unspecified; IEnumerable <Mutation> mutations = new List <Mutation>(); // Make the request CommitResponse response = await datastoreClient.CommitAsync(projectId, mode, mutations); // End snippet }
// Used by TransactionReadAndWrite. Could promote to the fixture. private Key CreateAccount(string name, long balance) { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; DatastoreClient client = DatastoreClient.Create(); KeyFactory factory = new KeyFactory(projectId, namespaceId, "Account"); Entity entity = new Entity { Key = factory.CreateIncompleteKey(), ["name"] = name, ["balance"] = balance }; CommitResponse response = client.Commit(projectId, Mode.NonTransactional, new[] { entity.ToInsert() }); return(response.MutationResults[0].Key); }
public void Commit_RequestObject() { // Snippet: Commit(CommitRequest,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) CommitRequest request = new CommitRequest { ProjectId = "", Mode = CommitRequest.Types.Mode.Unspecified, Mutations = { }, }; // Make the request CommitResponse response = datastoreClient.Commit(request); // End snippet }
/// <summary>Snippet for CommitAsync</summary> public async Task CommitAsync2() { // Snippet: CommitAsync(SessionName,TransactionOptions,IEnumerable<Mutation>,CallSettings) // Additional: CommitAsync(SessionName,TransactionOptions,IEnumerable<Mutation>,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); TransactionOptions singleUseTransaction = new TransactionOptions(); IEnumerable <Mutation> mutations = new List <Mutation>(); // Make the request CommitResponse response = await spannerClient.CommitAsync(session, singleUseTransaction, mutations); // End snippet }
public async void DeleteContact_True() { //arrange var contact = ContactFaker.GetContactOk(); var deleteContactCommand = new DeleteContactCommand(contact.Id); _dependencyResolverMock .Setup(x => x.Resolve <IContactRepository>()) .Returns(_contactRepositoryMock.Object); _dependencyResolverMock .Setup(x => x.Resolve <IContactTypeRepository>()) .Returns(_contactTypeRepositoryMock.Object); _contactRepositoryMock .Setup(x => x.GetByIdAsync(deleteContactCommand.ContactId)) .Returns(Task.FromResult(contact)); _contactRepositoryMock .Setup(x => x.CommitAsync()) .Returns(Task.FromResult(CommitResponse.Ok())); var handler = new ContactCommandHandler(_dependencyResolverMock.Object); //act var result = await handler.Handle(deleteContactCommand, new CancellationToken()); //Assert Assert.True(result.Success); _contactRepositoryMock.Verify(x => x.GetByIdAsync(deleteContactCommand.ContactId), Times.Once); _contactRepositoryMock.Verify(x => x.Update(contact), Times.Once); _contactRepositoryMock.Verify(x => x.CommitAsync(), Times.Once); _mediatorHandler.Verify(x => x.NotifyDomainNotification(It.IsAny <DomainNotification>()), Times.Never); }
public async Task CommitAsync_RequestObject() { // Snippet: CommitAsync(CommitRequest,CallSettings) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) CommitRequest request = new CommitRequest { Session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").ToString(), Mutations = { }, }; // Make the request CommitResponse response = await spannerClient.CommitAsync(request); // End snippet }
public Action<NetMQMessage> Send(NetMQSocket socket, PendingResRequest pendingRequest, Guid requestId) { var pending = (PendingResRequest<CommitResponse>) pendingRequest; var msg = new NetMQMessage(); msg.AppendEmptyFrame(); msg.Append(ResProtocol.ResClient01); msg.Append(ResCommands.AppendCommit); msg.Append(requestId.ToByteArray()); msg.Append(Context); msg.Append(Stream); msg.Append(ExpectedVersion.ToNetMqFrame()); msg.Append(Events.Length.ToNetMqFrame()); foreach (var e in Events) { msg.Append(e.EventId.ToByteArray()); msg.Append(e.Timestamp.ToNetMqFrame()); msg.Append(e.TypeTag); msg.Append(e.Headers.ToNetMqFrame()); msg.Append(e.Body); } socket.SendMultipartMessage(msg); return m => { var command = m.Pop().ConvertToString(); if (command == ResCommands.Error) { var errorCode = m.Pop().ConvertToString(); var errorDetails = m.Pop().ConvertToString(); ErrorResolver.RaiseException(errorCode, errorDetails, pending.SetException); return; } if (command != ResCommands.CommitResult) pending.SetException(new UnsupportedCommandException(command)); var commitId = new Guid(m.Pop().ToByteArray()); var result = new CommitResponse(commitId); pending.SetResult(result); }; }
public void Commit3() { Mock <Spanner.SpannerClient> mockGrpcClient = new Mock <Spanner.SpannerClient>(MockBehavior.Strict); CommitRequest request = new CommitRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Mutations = { }, }; CommitResponse expectedResponse = new CommitResponse(); mockGrpcClient.Setup(x => x.Commit(request, It.IsAny <CallOptions>())) .Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); CommitResponse response = client.Commit(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); }
public void Commit2() { Mock <Firestore.FirestoreClient> mockGrpcClient = new Mock <Firestore.FirestoreClient>(MockBehavior.Strict); CommitRequest request = new CommitRequest { Database = new DatabaseRootName("[PROJECT]", "[DATABASE]").ToString(), Writes = { }, }; CommitResponse expectedResponse = new CommitResponse(); mockGrpcClient.Setup(x => x.Commit(request, It.IsAny <CallOptions>())) .Returns(expectedResponse); FirestoreClient client = new FirestoreClientImpl(mockGrpcClient.Object, null); CommitResponse response = client.Commit(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); }
/// <summary>Snippet for CommitAsync</summary> public async Task Commit1Async() { // Snippet: CommitAsync(string, CommitRequest.Types.Mode, ByteString, IEnumerable<Mutation>, CallSettings) // Additional: CommitAsync(string, CommitRequest.Types.Mode, ByteString, IEnumerable<Mutation>, CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; CommitRequest.Types.Mode mode = CommitRequest.Types.Mode.Unspecified; ByteString transaction = ByteString.Empty; IEnumerable <Mutation> mutations = new Mutation[] { new Mutation(), }; // Make the request CommitResponse response = await datastoreClient.CommitAsync(projectId, mode, transaction, mutations); // End snippet }
public async Task CommitAsync2() { Mock <Firestore.FirestoreClient> mockGrpcClient = new Mock <Firestore.FirestoreClient>(MockBehavior.Strict); CommitRequest request = new CommitRequest { Database = new DatabaseRootName("[PROJECT]", "[DATABASE]").ToString(), Writes = { }, }; CommitResponse expectedResponse = new CommitResponse(); mockGrpcClient.Setup(x => x.CommitAsync(request, It.IsAny <CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall <CommitResponse>(Task.FromResult(expectedResponse), null, null, null, null)); FirestoreClient client = new FirestoreClientImpl(mockGrpcClient.Object, null); CommitResponse response = await client.CommitAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); }
/// <summary>Snippet for CommitAsync</summary> public async Task CommitAsync_RequestObject() { // Snippet: CommitAsync(CommitRequest,CallSettings) // Additional: CommitAsync(CommitRequest,CancellationToken) // Create client FirestoreClient firestoreClient = await FirestoreClient.CreateAsync(); // Initialize request argument(s) CommitRequest request = new CommitRequest { Database = new DatabaseRootName("[PROJECT]", "[DATABASE]").ToString(), Writes = { }, }; // Make the request CommitResponse response = await firestoreClient.CommitAsync(request); // End snippet }
public async Task CommitAsync3() { Mock <Spanner.SpannerClient> mockGrpcClient = new Mock <Spanner.SpannerClient>(MockBehavior.Strict); CommitRequest request = new CommitRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Mutations = { }, }; CommitResponse expectedResponse = new CommitResponse(); mockGrpcClient.Setup(x => x.CommitAsync(request, It.IsAny <CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall <CommitResponse>(Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); CommitResponse response = await client.CommitAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); }
/// <summary>Snippet for CommitAsync</summary> public async Task CommitAsync_RequestObject() { // Snippet: CommitAsync(CommitRequest,CallSettings) // Additional: CommitAsync(CommitRequest,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) CommitRequest request = new CommitRequest { ProjectId = "", Mode = CommitRequest.Types.Mode.Unspecified, Mutations = { }, }; // Make the request CommitResponse response = await datastoreClient.CommitAsync(request); // End snippet }
/// <summary>Snippet for CommitAsync</summary> public async Task CommitRequestObjectAsync() { // Snippet: CommitAsync(CommitRequest, CallSettings) // Additional: CommitAsync(CommitRequest, CancellationToken) // Create client FirestoreClient firestoreClient = await FirestoreClient.CreateAsync(); // Initialize request argument(s) CommitRequest request = new CommitRequest { Database = "", Writes = { new Write(), }, Transaction = ByteString.Empty, }; // Make the request CommitResponse response = await firestoreClient.CommitAsync(request); // End snippet }
public void Commit() { moq::Mock <Firestore.FirestoreClient> mockGrpcClient = new moq::Mock <Firestore.FirestoreClient>(moq::MockBehavior.Strict); CommitRequest request = new CommitRequest { Database = "projects/test/databases/databased8eee011", Writes = { new Write(), }, }; CommitResponse expectedResponse = new CommitResponse { WriteResults = { new WriteResult(), }, CommitTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.Commit(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(expectedResponse); FirestoreClient client = new FirestoreClientImpl(mockGrpcClient.Object, null); CommitResponse response = client.Commit(request.Database, request.Writes); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); }
public void InsertEntity() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Sample: InsertEntity KeyFactory keyFactory = new KeyFactory(projectId, namespaceId, "Task"); Entity entity = new Entity { Key = keyFactory.CreateIncompleteKey(), ["category"] = "Personal", ["done"] = false, ["priority"] = 4, ["description"] = "Learn Cloud Datastore", ["percent_complete"] = 75.0 }; DatastoreClient client = DatastoreClient.Create(); CommitResponse response = client.Commit(projectId, Mode.NonTransactional, new[] { entity.ToInsert() }); Key insertedKey = response.MutationResults[0].Key; // End sample }
public void Commit3() { Mock <Datastore.DatastoreClient> mockGrpcClient = new Mock <Datastore.DatastoreClient>(MockBehavior.Strict); CommitRequest request = new CommitRequest { ProjectId = "projectId-1969970175", Mode = CommitRequest.Types.Mode.Unspecified, Mutations = { }, }; CommitResponse expectedResponse = new CommitResponse { IndexUpdates = 1425228195, }; mockGrpcClient.Setup(x => x.Commit(request, It.IsAny <CallOptions>())) .Returns(expectedResponse); DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null); CommitResponse response = client.Commit(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); }
public void Commit2() { Mock <Spanner.SpannerClient> mockGrpcClient = new Mock <Spanner.SpannerClient>(MockBehavior.Strict); CommitRequest expectedRequest = new CommitRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), SingleUseTransaction = new TransactionOptions(), Mutations = { }, }; CommitResponse expectedResponse = new CommitResponse(); mockGrpcClient.Setup(x => x.Commit(expectedRequest, It.IsAny <CallOptions>())) .Returns(expectedResponse); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); TransactionOptions singleUseTransaction = new TransactionOptions(); IEnumerable <Mutation> mutations = new List <Mutation>(); CommitResponse response = client.Commit(session, singleUseTransaction, mutations); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); }
public async Task CommitAsync() { Mock <Spanner.SpannerClient> mockGrpcClient = new Mock <Spanner.SpannerClient>(MockBehavior.Strict); CommitRequest expectedRequest = new CommitRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = ByteString.CopyFromUtf8("28"), Mutations = { }, }; CommitResponse expectedResponse = new CommitResponse(); mockGrpcClient.Setup(x => x.CommitAsync(expectedRequest, It.IsAny <CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall <CommitResponse>(Task.FromResult(expectedResponse), null, null, null, null)); SpannerClient client = new SpannerClientImpl(mockGrpcClient.Object, null); SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); ByteString transactionId = ByteString.CopyFromUtf8("28"); IEnumerable <Mutation> mutations = new List <Mutation>(); CommitResponse response = await client.CommitAsync(session, transactionId, mutations); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); }
public async Task CommitAsync3() { Mock <Datastore.DatastoreClient> mockGrpcClient = new Mock <Datastore.DatastoreClient>(MockBehavior.Strict); CommitRequest request = new CommitRequest { ProjectId = "projectId-1969970175", Mode = CommitRequest.Types.Mode.Unspecified, Mutations = { }, }; CommitResponse expectedResponse = new CommitResponse { IndexUpdates = 1425228195, }; mockGrpcClient.Setup(x => x.CommitAsync(request, It.IsAny <CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall <CommitResponse>(Task.FromResult(expectedResponse), null, null, null, null)); DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null); CommitResponse response = await client.CommitAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); }
public void Save(T obj) { DatastoreDb db = DatastoreDb.Create("fantasyfootball-204922", "default"); KeyFactory keyFactory = db.CreateKeyFactory(obj.Kind); Entity entity = new Entity { Key = keyFactory.CreateKey(obj.id), ["updated"] = DateTime.UtcNow, ["text"] = JsonConvert.SerializeObject(obj), ["tags"] = obj.Tags.ToArray() }; using (DatastoreTransaction transaction = db.BeginTransaction()) { transaction.Upsert(entity); CommitResponse commitResponse = transaction.Commit(); Key insertedKey = commitResponse.MutationResults[0].Key; Console.WriteLine($"Inserted key: {insertedKey}"); // The key is also propagated to the entity Console.WriteLine($"Entity key: {entity.Key}"); } }
public CommitResponse AddRolesForCharacter(int charID, int[] roleIDs, int classID) { CommitResponse response = new CommitResponse(); classID = (classID != null) ? classID : GetCharacterByID(charID).ClassID; if (!ValidateUserRoles((int)classID, roleIDs)) { response.success = false; response.errorMsg = Errors.ROLE_IS_NOT_VALID_FOR_CLASS; return response; } foreach (int roleID in roleIDs) { MemCharacterRole memRole = new MemCharacterRole() { CharacterID = charID, LastModified = DateTime.Now, RoleID = roleID }; LeetRaidsDB.MemCharacterRoles.InsertOnSubmit(memRole); } try { LeetRaidsDB.SubmitChanges(); response.success = true; } catch (Exception ex) { response.success = false; } return response; }
public CommitResponse UpdateAttendeeStatus(int eventID, int memberID, int newStatusID, int newCharID, string newNote, int newRoleID) { CommitResponse response = new CommitResponse(); EventAttendee attendee = (from attn in LeetRaidsDB.EventAttendees where attn.EventID == eventID && attn.MemberID == memberID select attn).SingleOrDefault(); if (attendee != null) { //I am not supporting nullable value. If you dont want to update the info then pass in the current values. attendee.Status = newStatusID; attendee.CharacterID = newCharID; attendee.Note = HttpUtility.HtmlEncode((newNote.Length > 50) ? newNote.SubStrMax(49) : newNote); attendee.RoleID = newRoleID; LeetRaidsDB.SubmitChanges(); } else { response.success = false; response.errorMsg = Errors.ATTENDEE_COULDNT_BE_FOUND; } return response; }
public CommitResponse UpdateAttendeeAttendenceStatusBulk(int eventID, IEnumerable<int> charIDs, int statusID) { CommitResponse response = new CommitResponse(); var attendees = (from attn in LeetRaidsDB.EventAttendees where attn.EventID == eventID && charIDs.Contains(attn.CharacterID) select attn); if (attendees.Count() > 0) { foreach (EventAttendee attn in attendees) { attn.Status = statusID; } LeetRaidsDB.SubmitChanges(); } else { response.success = false; response.errorMsg = Errors.ATTENDEE_COULDNT_BE_FOUND; } return response; }
public CommitResponse RemoveAttendeeBulk(int eventID, IEnumerable<int> charIDs) { CommitResponse response = new CommitResponse(); var attendees = (from attn in LeetRaidsDB.EventAttendees where attn.EventID == eventID && charIDs.Contains(attn.CharacterID) select attn); if (attendees.Count() > 0) { LeetRaidsDB.EventAttendees.DeleteAllOnSubmit(attendees); LeetRaidsDB.SubmitChanges(); } else { response.success = false; response.errorMsg = Errors.ATTENDEE_COULDNT_BE_FOUND; } return response; }
public CommitResponse LeaveEvent(int eventID, int characterID) { CommitResponse response = new CommitResponse(); EventAttendee eventAttn = (from attn in LeetRaidsDB.EventAttendees where attn.EventID == eventID && attn.CharacterID == characterID select attn).SingleOrDefault(); if (eventAttn != null) { LeetRaidsDB.EventAttendees.DeleteOnSubmit(eventAttn); LeetRaidsDB.SubmitChanges(); } else { response.success = false; response.errorMsg = Errors.CHARACTER_NOT_FOUND; } return response; }
public CommitResponse CaptureEmailInvite(int inviterMemberID, string inviteeEmail, int inviteEventID) { CommitResponse response = new CommitResponse(); Invite invite = new Invite() { InviteType = (int)InviteTypes.EMAIL, InviterMemberID = inviterMemberID, InviteDT = DateTime.Now, InviteeEmailAddress = inviteeEmail, EventID = inviteEventID }; try { LeetRaidsDB.Invites.InsertOnSubmit(invite); LeetRaidsDB.SubmitChanges(); } catch (Exception ex) { response.success = false; } return response; }
//[NoCache] cache so that if users enter the same emai twice nothing happens public JsonResult InviteViaEmailAJAX(string e) { string emailAddress = e; if(!Validate.Email(emailAddress)) { ValidationErrors.Add("Invalid Email", Errors.INVALID_EMAIL); } CommitResponse response = new CommitResponse() { success = false }; if (ValidationErrors.Count == 0) { //Capture the Invitation accountInterface.CaptureEmailInvite(MemberInfo.MemberID, emailAddress, CurrentEvent.EventID); //Send out the email Dictionary<string, string> replaceValues = new Dictionary<string, string>(); replaceValues.Add("INVITERS_EMAIL", MemberInfo.Email); string gameName = gameInterface.GetGameByID(CurrentEvent.GameID).GameName; replaceValues.Add("GAME_NAME", gameName); string eventTypeName = eventInterface.GetEventTypeByID(CurrentEvent.EventID).EventTypeName; replaceValues.Add("EVENT_TYPE", eventTypeName); replaceValues.Add("EVENT_LINK", CurrentEvent.GenerateEventURL(System.Web.HttpContext.Current)); try { SMTPEmail.SMTPEMailS email = new SMTPEmail.SMTPEMailS(replaceValues); string emailFileLocation = Server.MapPath("~/Static/InviteEmail.txt"); response.success = email.SendEmailFromFile(new string[] { emailAddress }, "*****@*****.**", "A friend has invited you to a Group", emailFileLocation, null, false); } catch (Exception ex) { //TODO: We really want to know if this fails. Its possible to capture all the failures and then email them out later } } return new JsonResult() { Data = response }; }
public CommitResponse UpdateAccountSettings(int memberID, AccountSettings settings) { CommitResponse response = new CommitResponse(); Member memberInfo = GetMemberInfoByID(memberID); memberInfo.Email = settings.Email; LeetRaidsDB.SubmitChanges(); return response; }
public CommitResponse EditCharacter(MemCharacter memChar) { CommitResponse response = new CommitResponse(); //Make sure the User is only editing a character that he owns already. if (!CharacterBelongsToMember(memChar.MemberID, memChar.CharacterID)) { response.success = false; response.errorMsg = Errors.CAN_NOT_OPERATE_ON_OTHER_MEMBERS_CHARACTER; } if (response.success) { memChar.LastModifiedDT = memChar.LastModifiedDT = DateTime.Now; MemCharacter editMemChar = (from eMemChar in LeetRaidsDB.MemCharacters where eMemChar.CharacterID == memChar.CharacterID select eMemChar).Single(); editMemChar.CharacterName = memChar.CharacterName; editMemChar.ClassID = memChar.ClassID; editMemChar.FactionID = memChar.FactionID; //editMemChar.GameID = memChar.GameID; editMemChar.LVL = memChar.LVL; //editMemChar.RegionID = memChar.RegionID; editMemChar.ServerID = memChar.ServerID; //How the f**k to handle roles LeetRaidsDB.SubmitChanges(); } return response; }
public CommitResponse UpdateRestrictions(int eventID, IEnumerable<RoleRestriction> updtRoleRest, int? serverID, int? factionID) { CommitResponse response = new CommitResponse(); EventRestriction evtRestriction = GetEventRestrictionOrCreate(eventID); //Go ahead and update the basic restrictions evtRestriction.ServerID = serverID; evtRestriction.FactionID = factionID; LeetRaidsDB.SubmitChanges(); //Update Role Restrictions response.success = UpdateRoleRestrictions(eventID, updtRoleRest).success; return response; }
public CommitResponse UpdateRoleRestrictions(int eventID, IEnumerable<RoleRestriction> updtRoleRest) { CommitResponse response = new CommitResponse(); //Get Existing Role Restrictions var roleRestrictions = from roleRest in LeetRaidsDB.RoleRestrictions join evtRest in LeetRaidsDB.EventRestrictions on roleRest.RestrictionID equals evtRest.RoleRestrictionID where evtRest.EventID == eventID select roleRest; foreach (RoleRestriction roleRest in updtRoleRest) { RoleRestriction existingRestriction = roleRestrictions.Where(r => r.RoleID == roleRest.RoleID).SingleOrDefault(); if (existingRestriction != null) { //If some exist then update existingRestriction.Quantity = roleRest.Quantity; } else { //Else Make new ones LeetRaidsDB.RoleRestrictions.InsertOnSubmit(roleRest); } } LeetRaidsDB.SubmitChanges(); return response; }
public JsonResult UpdateAttendeeStatusAsCreatorAJAX(int statusID, string chars) { CommitResponse response = new CommitResponse(); //bool userOwnsThisCharacter = charInterface.GetAllMemberCharacters(MemberInfo.MemberID).Any(c => c.CharacterID == charID); bool userIsEventCreator = eventInterface.GetEventCreatorsMemberInfo(CurrentEvent.EventID).MemberID == MemberInfo.MemberID; if (userIsEventCreator) { int[] realCharIDs = chars.Split(new char[] { '|' }).Select(s => Int32.Parse(s)).ToArray(); if (realCharIDs.Length > 0) { response = eventInterface.UpdateAttendeeAttendenceStatusBulk(CurrentEvent.EventID, realCharIDs, statusID); } } else { response.success = false; response.errorMsg = Errors.CAN_NOT_OPERATE_ON_OTHER_MEMBERS_CHARACTER; } return new JsonResult() { Data = response }; }
public CommitResponse DeactivateEvent(int memberID, int eventID) { CommitResponse response = new CommitResponse(); // Ensure that user deleting event is the creator if (GetEventCreatorsMemberInfo(eventID).MemberID == memberID) { response.success = false; response.errorMsg = Errors.NOT_EVENT_CREATOR; return response; } Event eventToDeactivate = (from evt in LeetRaidsDB.Events where evt.EventID == eventID select evt).SingleOrDefault(); if (eventToDeactivate != null) { eventToDeactivate.Active = false; LeetRaidsDB.SubmitChanges(); } else { response.success = false; response.errorMsg = Errors.INVALID_EVENT_ID; } return response; }
public CommitResponse InsertRoleRestrictions(int eventID, IEnumerable<RoleRestriction> restrictions) { CommitResponse response = new CommitResponse(); //Create Identity for Role Restrictions int? maxRoleRestricitons = LeetRaidsDB.RoleRestrictions.Select(r => (int?)r.RestrictionID).Max(); maxRoleRestricitons = (maxRoleRestricitons != null) ? maxRoleRestricitons : 0; int restrictionID = ((int)maxRoleRestricitons) + 1; //Update roleRestrictions with the restrictionID Identity foreach (RoleRestriction rest in restrictions) { rest.RestrictionID = restrictionID; } //Setup Insert for Role Restrictions LeetRaidsDB.RoleRestrictions.InsertAllOnSubmit(restrictions); //Get The EventRestriction, or create it if it doesnt exist EventRestriction evtRestriction = GetEventRestrictionOrCreate(eventID); //Update Event Restriction evtRestriction.RoleRestrictionID = restrictionID; try { LeetRaidsDB.SubmitChanges(); } catch (Exception ex) { throw ex; } return response; }
public CommitResponse InsertNewMemberGame(int memberID, int gameID) { CommitResponse response = new CommitResponse(); // Check if user already has this game added if(GetMembersGames(memberID).Any(game => game.GameID == gameID)) { response.success = false; response.errorMsg = Errors.MEMBER_ALREADY_ADDED_THIS_GAME; } if (response.success) { MemGame newMemGame = new MemGame() { GameID = gameID, MemberID = memberID }; try { LeetRaidsDB.MemGames.InsertOnSubmit(newMemGame); LeetRaidsDB.SubmitChanges(); } catch (Exception ex) { response.success = false; throw ex; //if (!Convert.ToBoolean(ConfigurationManager.AppSettings["RETHROW_HANDLED_ERRORS"])) //{ //} //else //{ // throw ex; //} } } return response; }
public CommitResponse DeleteCharacter(int currentMemberID, int charID) { CommitResponse response = new CommitResponse(); //Ensure that character belongs to use if (!CharacterBelongsToMember(currentMemberID, charID)) { response.success = false; response.errorMsg = Errors.CAN_NOT_OPERATE_ON_OTHER_MEMBERS_CHARACTER; return response; } MemCharacter charToDelete = GetCharacterByID(charID); if (charToDelete != null) { LeetRaidsDB.MemCharacters.DeleteOnSubmit(charToDelete); LeetRaidsDB.SubmitChanges(); DeleteRolesForCharacter(charID); } else { response.success = false; response.errorMsg = Errors.CHARACTER_NOT_FOUND; } return response; }