UpdateResponse m_updateFunction; //Delegate that Calls the update function from main form

        #endregion Fields

        #region Constructors

        /*Initialise the components and loads the data in textboxes, when it is the case*/
        public DialogWindow(int option, dbRecord record, UpdateResponse updateFunction, IDataController data)
        {
            InitializeComponent();
            m_updateFunction = updateFunction;
            m_option = option;
            m_record = record;
            m_data = data;
            LoadInformation();
        }
Ejemplo n.º 2
0
        private void HandleUpdateResponse(UpdateResponse updateResponse, EntityResultSet resultSet)
        {
            if (updateResponse != null)
            {
                var updateRequest = (UpdateRequest)Request;
                var result = updateRequest.Target;
                resultSet.Results = new EntityCollection(new List<Entity>(new Entity[] { result }));

            }
        }
Ejemplo n.º 3
0
 void SendEmailRequest(UpdateResponse updateResponse)
 {
     if (string.IsNullOrEmpty(updateResponse?.Message?.Text))
         return;
     var senderUserName = updateResponse.Message.From.UserName;
     var chatId = updateResponse.Message?.Chat.Id;
     Bot.SendMessage(new SendMessageRequest
     {
         ChatId = (int)chatId,
         Text = string.Format(BusinessMessages.Start, senderUserName),
     });
 }
Ejemplo n.º 4
0
        public async void Update_NoErrorsOccurred_ShouldReturnResponse()
        {
            var mock  = new ServiceMockFacade <ITeacherService, ITeacherRepository>();
            var model = new ApiTeacherServerRequestModel();

            mock.RepositoryMock.Setup(x => x.Create(It.IsAny <Teacher>())).Returns(Task.FromResult(new Teacher()));
            mock.RepositoryMock.Setup(x => x.Get(It.IsAny <int>())).Returns(Task.FromResult(new Teacher()));
            var service = new TeacherService(mock.LoggerMock.Object,
                                             mock.MediatorMock.Object,
                                             mock.RepositoryMock.Object,
                                             mock.ModelValidatorMockFactory.TeacherModelValidatorMock.Object,
                                             mock.DALMapperMockFactory.DALTeacherMapperMock,
                                             mock.DALMapperMockFactory.DALEventTeacherMapperMock,
                                             mock.DALMapperMockFactory.DALRateMapperMock,
                                             mock.DALMapperMockFactory.DALTeacherTeacherSkillMapperMock);

            UpdateResponse <ApiTeacherServerResponseModel> response = await service.Update(default(int), model);

            response.Should().NotBeNull();
            response.Success.Should().BeTrue();
            mock.ModelValidatorMockFactory.TeacherModelValidatorMock.Verify(x => x.ValidateUpdateAsync(It.IsAny <int>(), It.IsAny <ApiTeacherServerRequestModel>()));
            mock.RepositoryMock.Verify(x => x.Update(It.IsAny <Teacher>()));
            mock.MediatorMock.Verify(x => x.Publish(It.IsAny <TeacherUpdatedNotification>(), It.IsAny <CancellationToken>()));
        }
Ejemplo n.º 5
0
        private async void downloadData()
        {
            UpdateResponse responseType = await ControllerData.Instance.updateData();

            switch (responseType.Type)
            {
            case UpdateResponse.ResponseType.type_ok:
                lvItems.ItemsSource = ControllerData.Instance.Data;
                break;

            case UpdateResponse.ResponseType.type_error_response_cache_not_found:
                MessageBox.Show(Messages.error_response_cache_not_found);
                break;

            case UpdateResponse.ResponseType.type_error_response_empty:

                MessageBox.Show(Messages.error_response_empty);
                break;

            case UpdateResponse.ResponseType.type_error_web:
                MessageBox.Show(responseType.Message);
                break;

            case UpdateResponse.ResponseType.type_error_wishlist_data:
                MessageBox.Show(Messages.error_wishlist_data);
                break;

            case UpdateResponse.ResponseType.type_error_wishlist_products_not_found:
                MessageBox.Show(Messages.error_wishlist_products_not_found);
                break;
            }

            bConfirm.IsEnabled   = true;
            cbFilter.IsEnabled   = true;
            cbDiscount.IsEnabled = true;
        }
        public virtual async Task <IActionResult> Patch(int id, [FromBody] JsonPatchDocument <ApiTransactionRequestModel> patch)
        {
            ApiTransactionResponseModel record = await this.TransactionService.Get(id);

            if (record == null)
            {
                return(this.StatusCode(StatusCodes.Status404NotFound));
            }
            else
            {
                ApiTransactionRequestModel model = await this.PatchModel(id, patch);

                UpdateResponse <ApiTransactionResponseModel> result = await this.TransactionService.Update(id, model);

                if (result.Success)
                {
                    return(this.Ok(result));
                }
                else
                {
                    return(this.StatusCode(StatusCodes.Status422UnprocessableEntity, result));
                }
            }
        }
Ejemplo n.º 7
0
        public async void Update_ErrorsOccurred_ShouldReturnErrorResponse()
        {
            var mock          = new ServiceMockFacade <ISpaceSpaceFeatureService, ISpaceSpaceFeatureRepository>();
            var model         = new ApiSpaceSpaceFeatureServerRequestModel();
            var validatorMock = new Mock <IApiSpaceSpaceFeatureServerRequestModelValidator>();

            validatorMock.Setup(x => x.ValidateUpdateAsync(It.IsAny <int>(), It.IsAny <ApiSpaceSpaceFeatureServerRequestModel>())).Returns(Task.FromResult(new ValidationResult(new List <ValidationFailure>()
            {
                new ValidationFailure("text", "test")
            })));
            mock.RepositoryMock.Setup(x => x.Get(It.IsAny <int>())).Returns(Task.FromResult(new SpaceSpaceFeature()));
            var service = new SpaceSpaceFeatureService(mock.LoggerMock.Object,
                                                       mock.MediatorMock.Object,
                                                       mock.RepositoryMock.Object,
                                                       validatorMock.Object,
                                                       mock.DALMapperMockFactory.DALSpaceSpaceFeatureMapperMock);

            UpdateResponse <ApiSpaceSpaceFeatureServerResponseModel> response = await service.Update(default(int), model);

            response.Should().NotBeNull();
            response.Success.Should().BeFalse();
            validatorMock.Verify(x => x.ValidateUpdateAsync(It.IsAny <int>(), It.IsAny <ApiSpaceSpaceFeatureServerRequestModel>()));
            mock.MediatorMock.Verify(x => x.Publish(It.IsAny <SpaceSpaceFeatureUpdatedNotification>(), It.IsAny <CancellationToken>()), Times.Never());
        }
Ejemplo n.º 8
0
        public virtual async void TestUpdate()
        {
            var builder = new WebHostBuilder()
                          .UseEnvironment("Production")
                          .UseStartup <TestStartup>();
            TestServer testServer = new TestServer(builder);

            var client = new ApiClient(testServer.CreateClient());

            client.SetBearerToken(JWTTestHelper.GenerateBearerToken());
            var mapper = new ApiEmployeeServerModelMapper();
            ApplicationDbContext           context = testServer.Host.Services.GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;
            IEmployeeService               service = testServer.Host.Services.GetService(typeof(IEmployeeService)) as IEmployeeService;
            ApiEmployeeServerResponseModel model   = await service.Get(1);

            ApiEmployeeClientRequestModel request = mapper.MapServerResponseToClientRequest(model);

            request.SetProperties("B", true, true, "B");

            UpdateResponse <ApiEmployeeClientResponseModel> updateResponse = await client.EmployeeUpdateAsync(model.Id, request);

            context.Entry(context.Set <Employee>().ToList()[0]).Reload();
            updateResponse.Record.Should().NotBeNull();
            updateResponse.Success.Should().BeTrue();
            updateResponse.Record.Id.Should().Be(1);
            context.Set <Employee>().ToList()[0].FirstName.Should().Be("B");
            context.Set <Employee>().ToList()[0].IsSalesPerson.Should().Be(true);
            context.Set <Employee>().ToList()[0].IsShipper.Should().Be(true);
            context.Set <Employee>().ToList()[0].LastName.Should().Be("B");

            updateResponse.Record.Id.Should().Be(1);
            updateResponse.Record.FirstName.Should().Be("B");
            updateResponse.Record.IsSalesPerson.Should().Be(true);
            updateResponse.Record.IsShipper.Should().Be(true);
            updateResponse.Record.LastName.Should().Be("B");
        }
Ejemplo n.º 9
0
        public virtual async void TestUpdate()
        {
            var builder = new WebHostBuilder()
                          .UseEnvironment("Production")
                          .UseStartup <TestStartup>();
            TestServer testServer = new TestServer(builder);

            var client = new ApiClient(testServer.CreateClient());

            client.SetBearerToken(JWTTestHelper.GenerateBearerToken());
            var mapper = new ApiRetweetServerModelMapper();
            ApplicationDbContext          context = testServer.Host.Services.GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;
            IRetweetService               service = testServer.Host.Services.GetService(typeof(IRetweetService)) as IRetweetService;
            ApiRetweetServerResponseModel model   = await service.Get(1);

            ApiRetweetClientRequestModel request = mapper.MapServerResponseToClientRequest(model);

            request.SetProperties(DateTime.Parse("1/1/1988 12:00:00 AM"), 1, TimeSpan.Parse("02:00:00"), 1);

            UpdateResponse <ApiRetweetClientResponseModel> updateResponse = await client.RetweetUpdateAsync(model.Id, request);

            context.Entry(context.Set <Retweet>().ToList()[0]).Reload();
            updateResponse.Record.Should().NotBeNull();
            updateResponse.Success.Should().BeTrue();
            updateResponse.Record.Id.Should().Be(1);
            context.Set <Retweet>().ToList()[0].Date.Should().Be(DateTime.Parse("1/1/1988 12:00:00 AM"));
            context.Set <Retweet>().ToList()[0].RetwitterUserId.Should().Be(1);
            context.Set <Retweet>().ToList()[0].Time.Should().Be(TimeSpan.Parse("02:00:00"));
            context.Set <Retweet>().ToList()[0].TweetTweetId.Should().Be(1);

            updateResponse.Record.Id.Should().Be(1);
            updateResponse.Record.Date.Should().Be(DateTime.Parse("1/1/1988 12:00:00 AM"));
            updateResponse.Record.RetwitterUserId.Should().Be(1);
            updateResponse.Record.Time.Should().Be(TimeSpan.Parse("02:00:00"));
            updateResponse.Record.TweetTweetId.Should().Be(1);
        }
        private static void Client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                try
                {
                    var j             = JArray.Parse(e.Result);
                    var latestVersion = j[0]["tag_name"].ToString();
                    var url           = j[0]["html_url"].ToString();

                    UpdateResponse?.Invoke(null, new UpdateResponseEventArgs(new Version(latestVersion), new Uri(url), e.UserState));
                }

                catch (Exception ex)
                {
                    UpdateResponse?.Invoke(null, new UpdateResponseEventArgs(ex, e.UserState));
                }
            }

            else
            {
                UpdateResponse?.Invoke(null, new UpdateResponseEventArgs(e.Error, e.UserState));
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 更新设备信息
        /// </summary>
        /// <param name="device_id"></param>
        /// <param name="result"></param>
        public void UpdateDevice(string device_id, string title, string desc, IUpdateDeviceResult result)
        {
            // client.Authenticator = new HttpBasicAuthenticator(username, password);

            var request = new RestRequest("devices/{device_id}", Method.PUT);

            request.AddUrlSegment("device_id", device_id); // replaces matching token in request.Resource

            // add parameters for all properties on an object
            //request.AddObject(object);

            // or just whitelisted properties
            //request.AddObject(object, "PersonId", "Name", ...);

            // easily add HTTP Headers
            request.AddHeader("api-key", "VtaeS4yK3Fk6xiOljgw69lYcH9k=");
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");
            string[] keys   = null;
            string[] values = null;
            if (!string.IsNullOrEmpty(title) && !string.IsNullOrEmpty(desc))
            {
                UpdateDevice updateDevice = new Entity.UpdateDevice();
                updateDevice.title = title;
                updateDevice.desc  = desc;
                keys   = new string[] { "title", "desc" };
                values = new string[] { title, desc };
                request.AddJsonBody(updateDevice);
            }
            else if (!string.IsNullOrEmpty(title))
            {
                UpdateTitle updateTitle = new Entity.UpdateTitle();
                updateTitle.title = title;
                keys   = new string[] { "title" };
                values = new string[] { title };
                request.AddJsonBody(updateTitle);
            }
            else if (!string.IsNullOrEmpty(desc))
            {
                UpdateDesc updateDesc = new UpdateDesc();
                updateDesc.desc = desc;
                keys            = new string[] { "desc" };
                values          = new string[] { desc };
                request.AddJsonBody(updateDesc);
            }

            IRestResponse response = client.Execute(request);
            var           content  = response.Content; // raw content as string

            if (response.ResponseStatus == ResponseStatus.Completed)
            {
                UpdateResponse updateResponse = JsonHelper.DeserializeJsonToObject <UpdateResponse>(content);
                if (updateResponse.error.Equals("succ"))
                {
                    DeviceDataDao.Instance.Update(device_id, keys, values);
                    result.OnSuccess("更新成功");
                }
                else
                {
                    result.OnFailure(updateResponse.error);
                }
            }
            else
            {
                result.OnFailure("更新设备信息失败");
            }
        }
Ejemplo n.º 12
0
        public virtual async void TestUpdate()
        {
            var builder = new WebHostBuilder()
                          .UseEnvironment("Production")
                          .UseStartup <TestStartup>();
            TestServer testServer = new TestServer(builder);

            var client = new ApiClient(testServer.CreateClient());

            client.SetBearerToken(JWTTestHelper.GenerateBearerToken());
            var mapper = new ApiTestAllFieldTypesNullableServerModelMapper();
            ApplicationDbContext context = testServer.Host.Services.GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;
            ITestAllFieldTypesNullableService service             = testServer.Host.Services.GetService(typeof(ITestAllFieldTypesNullableService)) as ITestAllFieldTypesNullableService;
            ApiTestAllFieldTypesNullableServerResponseModel model = await service.Get(1);

            ApiTestAllFieldTypesNullableClientRequestModel request = mapper.MapServerResponseToClientRequest(model);

            request.SetProperties(2, BitConverter.GetBytes(2), true, "B", DateTime.Parse("1/1/1988 12:00:00 AM"), DateTime.Parse("1/1/1988 12:00:00 AM"), DateTime.Parse("1/1/1988 12:00:00 AM"), DateTimeOffset.Parse("1/1/1988 12:00:00 AM"), 2m, 2, BitConverter.GetBytes(2), 2m, "B", "B", 2m, "B", 2m, DateTime.Parse("1/1/1988 12:00:00 AM"), 2, 2m, "B", TimeSpan.Parse("02:00:00"), BitConverter.GetBytes(2), 2, Guid.Parse("3842cac4-b9a0-8223-0dcc-509a6f75849b"), BitConverter.GetBytes(2), "B", "B");

            UpdateResponse <ApiTestAllFieldTypesNullableClientResponseModel> updateResponse = await client.TestAllFieldTypesNullableUpdateAsync(model.Id, request);

            context.Entry(context.Set <TestAllFieldTypesNullable>().ToList()[0]).Reload();
            updateResponse.Record.Should().NotBeNull();
            updateResponse.Success.Should().BeTrue();
            updateResponse.Record.Id.Should().Be(1);
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldBigInt.Should().Be(2);
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldBinary.Should().BeEquivalentTo(BitConverter.GetBytes(2));
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldBit.Should().Be(true);
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldChar.Should().Be("B");
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldDate.Should().Be(DateTime.Parse("1/1/1988 12:00:00 AM"));
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldDateTime.Should().Be(DateTime.Parse("1/1/1988 12:00:00 AM"));
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldDateTime2.Should().Be(DateTime.Parse("1/1/1988 12:00:00 AM"));
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldDateTimeOffset.Should().Be(DateTimeOffset.Parse("1/1/1988 12:00:00 AM"));
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldDecimal.Should().Be(2m);
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldFloat.Should().Be(2);
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldImage.Should().BeEquivalentTo(BitConverter.GetBytes(2));
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldMoney.Should().Be(2m);
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldNChar.Should().Be("B");
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldNText.Should().Be("B");
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldNumeric.Should().Be(2m);
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldNVarchar.Should().Be("B");
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldReal.Should().Be(2m);
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldSmallDateTime.Should().Be(DateTime.Parse("1/1/1988 12:00:00 AM"));
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldSmallInt.Should().Be(2);
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldSmallMoney.Should().Be(2m);
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldText.Should().Be("B");
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldTime.Should().Be(TimeSpan.Parse("02:00:00"));
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldTimestamp.Should().BeEquivalentTo(BitConverter.GetBytes(2));
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldTinyInt.Should().Be(2);
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldUniqueIdentifier.Should().Be(Guid.Parse("3842cac4-b9a0-8223-0dcc-509a6f75849b"));
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldVarBinary.Should().BeEquivalentTo(BitConverter.GetBytes(2));
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldVarchar.Should().Be("B");
            context.Set <TestAllFieldTypesNullable>().ToList()[0].FieldXML.Should().Be("B");

            updateResponse.Record.Id.Should().Be(1);
            updateResponse.Record.FieldBigInt.Should().Be(2);
            updateResponse.Record.FieldBinary.Should().BeEquivalentTo(BitConverter.GetBytes(2));
            updateResponse.Record.FieldBit.Should().Be(true);
            updateResponse.Record.FieldChar.Should().Be("B");
            updateResponse.Record.FieldDate.Should().Be(DateTime.Parse("1/1/1988 12:00:00 AM"));
            updateResponse.Record.FieldDateTime.Should().Be(DateTime.Parse("1/1/1988 12:00:00 AM"));
            updateResponse.Record.FieldDateTime2.Should().Be(DateTime.Parse("1/1/1988 12:00:00 AM"));
            updateResponse.Record.FieldDateTimeOffset.Should().Be(DateTimeOffset.Parse("1/1/1988 12:00:00 AM"));
            updateResponse.Record.FieldDecimal.Should().Be(2m);
            updateResponse.Record.FieldFloat.Should().Be(2);
            updateResponse.Record.FieldImage.Should().BeEquivalentTo(BitConverter.GetBytes(2));
            updateResponse.Record.FieldMoney.Should().Be(2m);
            updateResponse.Record.FieldNChar.Should().Be("B");
            updateResponse.Record.FieldNText.Should().Be("B");
            updateResponse.Record.FieldNumeric.Should().Be(2m);
            updateResponse.Record.FieldNVarchar.Should().Be("B");
            updateResponse.Record.FieldReal.Should().Be(2m);
            updateResponse.Record.FieldSmallDateTime.Should().Be(DateTime.Parse("1/1/1988 12:00:00 AM"));
            updateResponse.Record.FieldSmallInt.Should().Be(2);
            updateResponse.Record.FieldSmallMoney.Should().Be(2m);
            updateResponse.Record.FieldText.Should().Be("B");
            updateResponse.Record.FieldTime.Should().Be(TimeSpan.Parse("02:00:00"));
            updateResponse.Record.FieldTimestamp.Should().BeEquivalentTo(BitConverter.GetBytes(2));
            updateResponse.Record.FieldTinyInt.Should().Be(2);
            updateResponse.Record.FieldUniqueIdentifier.Should().Be(Guid.Parse("3842cac4-b9a0-8223-0dcc-509a6f75849b"));
            updateResponse.Record.FieldVarBinary.Should().BeEquivalentTo(BitConverter.GetBytes(2));
            updateResponse.Record.FieldVarchar.Should().Be("B");
            updateResponse.Record.FieldXML.Should().Be("B");
        }
Ejemplo n.º 13
0
 public IActionResult UpdatePayment(UpdateResponse updateResponse)
 {
     ResponseQueue.Enqueue(updateResponse);
     return(Ok());
 }
Ejemplo n.º 14
0
        /// <summary>
        /// This method first connects to the Deployment service. Then,
        /// uses RetrieveRequest, UpdateRequest and UpdateAdvancedSettingsRequest.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete
        /// all created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // Instantiate DeploymentServiceClient for calling the service.
                    DeploymentServiceClient serviceClient =
                        ProxyClientHelper.CreateClient(
                            new Uri(serverConfig.DiscoveryUri.ToString()
                                    .Replace("Services", "Deployment")
                                    .Replace("Discovery", "Deployment")));

                    // Setting credentials from the current security context.
                    if (serverConfig.Credentials != null)
                    {
                        serviceClient.ClientCredentials.Windows.ClientCredential =
                            serverConfig.Credentials.Windows.ClientCredential;
                    }
                    else
                    {
                        serviceClient.ClientCredentials.Windows.ClientCredential =
                            CredentialCache.DefaultNetworkCredentials;
                    }

                    #region RetrieveRequest

                    // Retrieve all servers available in the deployment
                    Console.WriteLine("\nRetrieving list of servers...\n");
                    var servers =
                        serviceClient.RetrieveAll(DeploymentEntityType.Server);

                    // Print list of all retrieved servers.
                    Console.WriteLine("Servers in your deployment");
                    Console.WriteLine("================================");
                    foreach (var server in servers)
                    {
                        Console.WriteLine(server.Name);
                    }
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();

                    // Retrieve details of first (other than current server) or default server from previous call.
                    var serverId = servers.FirstOrDefault(x => x.Name.ToLowerInvariant() != serverConfig.ServerAddress.ToLowerInvariant());
                    // If no other server exists then default to existing one.
                    if (serverId == null)
                    {
                        serverId = servers.FirstOrDefault();
                    }

                    Console.WriteLine("\nRetrieving details of one server...\n");
                    RetrieveRequest retrieveReqServer = new RetrieveRequest();
                    retrieveReqServer.EntityType  = DeploymentEntityType.Server;
                    retrieveReqServer.InstanceTag = serverId;
                    RetrieveResponse retrieveRespServer =
                        (RetrieveResponse)serviceClient.Execute(retrieveReqServer);
                    Server serverToUpdate =
                        (Server)retrieveRespServer.Entity;

                    Console.WriteLine("================================");
                    Console.WriteLine("Name: " + serverToUpdate.Name);
                    Console.WriteLine("State: " + serverToUpdate.State);
                    Console.WriteLine();

                    #endregion RetrieveRequest

                    #region UpdateRequest
                    // Avoid updating current server as it would disrupt the further sample execution.
                    if (servers.Count > 1)
                    {
                        // Modified the property we want to update
                        serverToUpdate.State = ServerState.Disabled;

                        // Update the deployment record
                        Console.WriteLine("\nUpdating server...\n");
                        UpdateRequest updateReq = new UpdateRequest();
                        updateReq.Entity = serverToUpdate;
                        UpdateResponse uptRes =
                            (UpdateResponse)serviceClient.Execute(updateReq);

                        // Retrieve server details again to check if it is updated
                        RetrieveResponse retrieveRespServerUpdated =
                            (RetrieveResponse)serviceClient.Execute(retrieveReqServer);
                        Server serverUpdated =
                            (Server)retrieveRespServerUpdated.Entity;

                        Console.WriteLine("Server Updated");
                        Console.WriteLine("================================");
                        Console.WriteLine("Name: " + serverUpdated.Name);
                        Console.WriteLine("State: " + serverUpdated.State);
                        Console.WriteLine();

                        // Revert change
                        serverUpdated.State = ServerState.Enabled;

                        Console.WriteLine("\nReverting change made in server...\n");
                        UpdateRequest updateReqRevert = new UpdateRequest();
                        updateReqRevert.Entity = serverUpdated;
                        UpdateResponse uptResRev =
                            (UpdateResponse)serviceClient.Execute(updateReqRevert);

                        RetrieveResponse retrieveRespServerReverted =
                            (RetrieveResponse)serviceClient.Execute(retrieveReqServer);
                        Server serverReverted =
                            (Server)retrieveRespServerReverted.Entity;

                        Console.WriteLine("Server Reverted");
                        Console.WriteLine("================================");
                        Console.WriteLine("Name: " + serverReverted.Name);
                        Console.WriteLine("State: " + serverReverted.State);
                        Console.WriteLine();
                    }
                    else
                    {
                        Console.WriteLine("\nMulti-server environment missing."
                                          + "\nSkipping server update request to avoid disruption in the sample execution.");
                    }
                    #endregion UpdateRequest

                    #region UpdateAdvanceRequest

                    // Retrieve Advanced Settings for your organization.
                    Console.WriteLine("\nRetrieving Advanced Settings...\n");
                    RetrieveAdvancedSettingsRequest requestAdvSettings =
                        new RetrieveAdvancedSettingsRequest
                    {
                        ConfigurationEntityName = "Deployment",
                        ColumnSet = new ColumnSet("Id")
                    };
                    ConfigurationEntity configuration =
                        ((RetrieveAdvancedSettingsResponse)
                         serviceClient.Execute(requestAdvSettings)).Entity;

                    // Print out all advanced settings where IsWritable==true.
                    Console.WriteLine("Advanced deployment settings that can be updated");
                    Console.WriteLine("================================================");
                    foreach (var setting in configuration.Attributes)
                    {
                        if (setting.Key != "Id")
                        {
                            Console.WriteLine(
                                String.Format("{0}: {1}",
                                              setting.Key,
                                              setting.Value));
                        }
                    }
                    Console.WriteLine();

                    // Create the Configuration Entity with the values to update
                    ConfigurationEntity configEntity = new ConfigurationEntity();
                    configEntity.LogicalName = "Deployment";
                    configEntity.Attributes  = new AttributeCollection();
                    configEntity.Attributes.Add
                        (new KeyValuePair <string, object>
                            ("AutomaticallyInstallDatabaseUpdates", true));

                    // Update Advanced Settings
                    Console.WriteLine("\nUpdating Advanced Settings...\n");
                    UpdateAdvancedSettingsRequest updateAdvanceReq =
                        new UpdateAdvancedSettingsRequest();
                    updateAdvanceReq.Entity = configEntity;
                    serviceClient.Execute(updateAdvanceReq);

                    // Retrieve Advanced Settings to check if they have been updated
                    ConfigurationEntity configurationUpdated =
                        ((RetrieveAdvancedSettingsResponse)
                         serviceClient.Execute(requestAdvSettings)).Entity;

                    Console.WriteLine("Advanced deployment settings updated");
                    Console.WriteLine("================================================");
                    foreach (var setting in configurationUpdated.Attributes)
                    {
                        if (setting.Key != "Id")
                        {
                            Console.WriteLine(
                                String.Format("{0}: {1}",
                                              setting.Key,
                                              setting.Value));
                        }
                    }
                    Console.WriteLine();

                    // Revert change
                    ConfigurationEntity entityRevert = new ConfigurationEntity();
                    entityRevert.LogicalName = "Deployment";
                    entityRevert.Attributes  = new AttributeCollection();
                    entityRevert.Attributes.Add
                        (new KeyValuePair <string, object>
                            ("AutomaticallyInstallDatabaseUpdates", false));

                    Console.WriteLine("\nReverting Advanced Settings...\n");
                    UpdateAdvancedSettingsRequest requestRevert =
                        new UpdateAdvancedSettingsRequest();
                    requestRevert.Entity = entityRevert;
                    serviceClient.Execute(requestRevert);

                    ConfigurationEntity configurationReverted =
                        ((RetrieveAdvancedSettingsResponse)
                         serviceClient.Execute(requestAdvSettings)).Entity;
                    Console.WriteLine("Advanced deployment settings reverted");
                    Console.WriteLine("================================================");
                    foreach (var setting in configurationReverted.Attributes)
                    {
                        if (setting.Key != "Id")
                        {
                            Console.WriteLine(
                                String.Format("{0}: {1}",
                                              setting.Key,
                                              setting.Value));
                        }
                    }
                    Console.WriteLine();
                    #endregion UpdateAdvanceRequest
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <DeploymentServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// This method demonstrates the optimistic concurrency feature.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,
                    serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    CreateRequiredRecords();

                    // Retrieve an account.
                    var account = _serviceProxy.Retrieve("account", _accountId, new ColumnSet("name","creditlimit"));
                    Console.WriteLine("\tThe row version of the created account is {0}", account.RowVersion);

                    if (account != null)
                    {
                        // Create an in-memory account object from the retrieved account.
                        Entity updatedAccount = new Entity()
                        {
                            LogicalName = account.LogicalName,
                            Id = account.Id,
                            RowVersion = account.RowVersion
                        };

                        // Update just the credit limit.
                        updatedAccount["creditlimit"] = new Money(1000000);

                        // Set the request's concurrency behavour to check for a row version match.
                        UpdateRequest accountUpdate = new UpdateRequest()
                        {
                            Target = updatedAccount,
                            ConcurrencyBehavior = ConcurrencyBehavior.IfRowVersionMatches
                        };

                        // Do the update.
                        UpdateResponse accountUpdateResponse = (UpdateResponse) _serviceProxy.Execute(accountUpdate);
                        Console.WriteLine("Account '{0}' updated with a credit limit of {1}.", account["name"], 
                            ((Money)updatedAccount["creditlimit"]).Value);

                        account = _serviceProxy.Retrieve("account", updatedAccount.Id, new ColumnSet());
                        Console.WriteLine("\tThe row version of the updated account is {0}", account.RowVersion);
                        _accountRowVersion = account.RowVersion;
                    }

                    DeleteRequiredRecords(promptforDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> e)
            {
                if (e.Detail.ErrorCode == CrmSdk.ErrorCodes.ConcurrencyVersionMismatch)
                {
                    var account = _serviceProxy.Retrieve("account", _accountId, new ColumnSet());
                    throw new Exception(String.Format("A mismatched row version ({0}) caused the request to fail.", account.RowVersion), e);
                }
                else
                    throw e;
            }
        }
Ejemplo n.º 16
0
        private async Task<UpdateResponse> Updates(CrunchySession s, ShowType t)
        {
            int startpage = 0;
            UpdateResponse ret = new UpdateResponse();
            bool end = false;
            do
            {
                string url = string.Format(LibSet[UpdateUrlS], ShowFromType(t), startpage);
                WebStream ws = await WebStream.Get(url, null,LibSet[UserAgentS], null, s.cookies.ToCookieCollection(),SocketTimeout,true,null,_info.ProxyFromGlobalRequirements(_global));
                if (ws != null && ws.StatusCode == HttpStatusCode.OK)
                {
                    if (!VerifyLogin(ws.Cookies))
                    {
                        ws.Dispose();
                        SetLoginError(ret);
                        return ret;
                    }
                    StreamReader rd = new StreamReader(ws);
                    string dta = rd.ReadToEnd();
                    rd.Dispose();
                    MatchCollection scol = updregex.Matches(dta);
                    if (scol.Count == 0)
                        end = true;
                    foreach (Match m in scol)
                    {
                        string show = m.Groups["show"].Value;
                        string image = m.Groups["image"].Value;
                        string title = WebUtility.HtmlDecode(m.Groups["title"].Value);
                        string ep = m.Groups["ep"].Value;
                        Uri ur = new Uri("http://www.crunchyroll.com" + m.Groups["url"].Value);
                        int a = ep.IndexOf("&ndash;", StringComparison.InvariantCulture);
                        if (a >= 0)
                        {
                            ep = ep.Substring(0, a).Trim();
                            string tag = CrunchyPluginInfo.PluginName + "|" + show + "|" + ep;
                            if (UpdateHistory.Exists(tag))
                            {
                                Episode c = JsonConvert.DeserializeObject<Episode>(UpdateHistory.Get(tag));
                                ret.Found.Add(c);
                            }
                            else
                            {
                                Episode p = new Episode();
                                p.PluginMetadata.Add("Url",ur.ToString());
                                p.ShowName = title;
                                p.ShowId = show;
                                p.PluginName = CrunchyPluginInfo.PluginName;
                                p.UniqueTag = tag;
                                p.ImageUri = new Uri(image);
                                p.Type = t;
                                ret.NotFound.Add(p);

                            }
                        }

                    }


                }
                else
                {
                    ws?.Dispose();
                    SetWebError(ret);
                    return ret;
                }
                ws?.Dispose();
                startpage++;
            } while (!end);
            return ret;
        }
Ejemplo n.º 17
0
    public void HandleUpdate(HttpListenerContext context)
    {
        UpdatePayload payload = null;

        try {
            var    strm   = context.Request.InputStream;
            var    reader = new StreamReader(strm, context.Request.ContentEncoding);
            string json   = reader.ReadToEnd();
            payload = JsonUtility.FromJson <UpdatePayload>(json);
        } catch (Exception ex) {
            UnityEngine.Debug.Log(ex);
        }

        if (payload != null)
        {
            var response   = new UpdateResponse();
            var playerInfo = GetPlayerInfo(payload.privateId);

            response.timerStart  = timerStart;
            response.timerLength = timerLength;

            if (playerInfo == null)
            {
                response.name  = "Audience Member";
                response.role  = -1;
                response.judge = null;
            }
            else
            {
                var  judgeInfo = connectedPlayers[curJudge];
                bool isJudge   = judgeInfo == playerInfo;

                playerInfo.keepAlive = true;

                response.name  = playerInfo.name;
                response.judge = judgeInfo.name;
                response.role  = isJudge ? 1 : 0;
                response.voted = winner != null;

                if (payload.leaving)
                {
                    playerInfo.left = true;
                }

                if (!isJudge && state == StateID.Insulting && (playerInfo.receivedInsult == null || playerInfo.receivedInsult.Length == 0))
                {
                    playerInfo.receivedInsult = WWW.UnEscapeURL(payload.insult);
                }
                else if (isJudge && state == StateID.Voting && winner == null && payload.vote > 0)
                {
                    winner = GetPlayerInfo(payload.vote);
                    winner.wins++;
                }

                response.insulted = playerInfo.receivedInsult != null && playerInfo.receivedInsult.Length > 0;
            }

            response.running = state != StateID.Waiting;

            if (state == StateID.Insulting)
            {
            }
            else if (state == StateID.Voting)
            {
                response.insults = GetInsultsArray();
            }
            else if (state == StateID.PostGame)
            {
                response.insults = GetInsultsArray();

                if (winner == null)
                {
                    do
                    {
                        winner = connectedPlayers[new System.Random().Next(connectedPlayers.Count)];
                    } while (winner == connectedPlayers[curJudge]);
                }

                response.winner         = new Insult();
                response.winner.caster  = winner.name;
                response.winner.content = winner.receivedInsult;
            }

            ServerManager.inst.server.WriteJsonToContext(context, response);
        }
        else
        {
            print("Invalid payload");
            context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        }
    }
Ejemplo n.º 18
0
 public UpdateResponse ConvertWebhookResponse(string json)
 {
     Log.Info(nameof(ConvertWebhookResponse));
     return(UpdateResponse.Parse(JsonData.Deserialize(json)));
 }
Ejemplo n.º 19
0
        public ActionResult BookingConfirm(string property, string index)
        {
            BookingViewModel model = TempData["BookingModel"] as BookingViewModel;

            ViewBag.indx         = index;
            ViewBag.pcode        = property;
            ViewBag.allowPayment = false;

            if (model == null)
            {
                return(View());
            }

            try
            {
                //ViewBag.pict = _repository.getImageByProp(model.property).url;

                UpdateResponse response = JsonRequestsHelper.UpdateBookingDetails(model.property, model);

                if (response.status.error.code == 0)
                {
                    #region LogFile
                    var    dateAsString = System.DateTime.Now.ToString();
                    string loginfo      = "Date: " + dateAsString + ", Property: " + model.property + ", Name: " + model.firstName + " "
                                          + model.lastName + ", Reservation: " + model.bookingNumber + ";" + Environment.NewLine
                                          + "-------------------" + Environment.NewLine;
                    logdata(loginfo);
                    #endregion

                    TempData["BookingModel"] = model;

                    #region eMail
                    sendMail();
                    #endregion

                    if (model.cardNumber != null && model.cardNumber != "" && (Convert.ToDecimal(model.total)) > 0)
                    {
                        ViewBag.allowPayment = true;
                    }
                }
                else
                {
                    #region LogFile
                    var    dateAsString = System.DateTime.Now.ToString();
                    string loginfo      = "Date: " + dateAsString +
                                          ", Property: " + model.property +
                                          ", Name: " + model.firstName + " " + model.lastName +
                                          ", Reservation: " + model.bookingNumber +
                                          ", Status: " + response.status.error.shorttext +
                                          ";" + Environment.NewLine
                                          + "-------------------" + Environment.NewLine;
                    logdata(loginfo);
                    #endregion

                    BookingViewModel m = TempData["BookingModel"] as BookingViewModel;
                    TempData["BookingModel"] = m;
                    return(RedirectToAction("BookingData", "Client", new { pcode = model.property, indx = model.index }));
                }

                return(RedirectToAction("PaymentData", "Client", new { pcode = model.property, indx = model.index }));
                //return View();
            }
            catch (WebException wex)
            {
                #region LogFile
                var    dateAsString = System.DateTime.Now.ToString();
                string loginfo      = "Date: " + dateAsString +
                                      ", Property: " + model.property +
                                      ", Name: " + model.firstName + " " + model.lastName +
                                      ", Reservation: " + model.bookingNumber +
                                      ", Status: " + wex.InnerException.Message +
                                      ";" + Environment.NewLine
                                      + "-------------------" + Environment.NewLine;
                logdata(loginfo);
                #endregion

                BookingViewModel m = TempData["BookingModel"] as BookingViewModel;
                TempData["BookingModel"] = m;
                return(RedirectToAction("BookingData", "Client", new { pcode = model.property, indx = model.index }));
            }
        }
Ejemplo n.º 20
0
        public async Task <UpdateResponse> UpdateCheck(UpdateRequest requestModel)
        {
            try
            {
                var     sw      = Stopwatch.StartNew();
                Program program = await this.Work.Programs.GetByTelemetryKey(requestModel.TelemetryKey).ConfigureAwait(false);

                if (program == null)
                {
                    return(new UpdateResponse {
                        Exception = new BadRequestException($"Failed to find program by Id: [{requestModel.TelemetryKey}]")
                    });
                }



                Trace.TraceInformation($"Program {program.GetNameAndIdString()} checking for updates with request: {requestModel.GetPropertyInfoString()}");
                List <ProgramUpdatePackageInfo> allUpdatePackages =
                    (await this.Work.UpdatePackages.GetAllPackagesNewerThan(requestModel.VersionData, program.Id).ConfigureAwait(false))
                    .OrderByDescending(x => x.Version, new TelimenaVersionStringComparer()).ToList();
                Trace.TraceInformation($"Found {allUpdatePackages.Count} packages");

                List <ProgramUpdatePackageInfo> filteredPackages = ProgramsControllerHelpers.FilterPackagesSet(allUpdatePackages, requestModel);
                //todo - for now updating the package is disabled - update packagaces are expected to contain the toolkit package
                //  string supportedToolkitVersion = await ProgramsControllerHelpers.GetMaximumSupportedToolkitVersion(this.Work, filteredPackages, program, requestModel).ConfigureAwait(false);
                // TelimenaPackageInfo toolkitPackage = await ProgramsControllerHelpers.GetToolkitUpdateInfo(this.Work, program, requestModel, supportedToolkitVersion).ConfigureAwait(false);
                Trace.TraceInformation($"Filtered {filteredPackages.Count} packages");

                List <UpdatePackageData> packageDataSets = new List <UpdatePackageData>();
                foreach (ProgramUpdatePackageInfo programUpdatePackageInfo in filteredPackages)
                {
                    packageDataSets.Add(Mapper.Map <ProgramUpdatePackageInfo, UpdatePackageData>(programUpdatePackageInfo
                                                                                                 , options => options.AfterMap((info, data) => data.DownloadUrl = Router.Api.DownloadProgramUpdate(info))));
                }

                //if (packageDataSets.Any()) //disabled for now (lets see when I look at this comment next time - it's 18.04.2019...)
                //{
                //    if (toolkitPackage != null)
                //    {
                //        packageDataSets.Add(Mapper.Map<TelimenaPackageInfo, UpdatePackageData>(toolkitPackage
                //            , options => options.AfterMap((info, data) => data.DownloadUrl = Router.Api.DownloadToolkitUpdate(info))));
                //    }
                //}


                UpdateResponse response = new UpdateResponse {
                    UpdatePackages = packageDataSets
                };
                sw.Stop();
                this.telemetryClient.TrackEvent("UpdateCheck", new Dictionary <string, string>()
                {
                    { $"ProgramName", program.Name },
                    { $"ExecutionTime", sw.ElapsedMilliseconds.ToString() },
                    { $"UpdateRequest", requestModel.GetPropertyInfoString() },
                });
                return(response);
            }
            catch (Exception ex)
            {
                this.telemetryClient.TrackException(ex, new Dictionary <string, string>()
                {
                    { $"Method", Routes.UpdateCheck },
                    { $"{nameof(Program.TelemetryKey)}", requestModel.TelemetryKey.ToString() }
                });
                return(new UpdateResponse {
                    Exception = new InvalidOperationException("Error while processing registration request", ex)
                });
            }
        }
Ejemplo n.º 21
0
        public UpdateResponse Post([FromBody] UpdateRequest request)
        {
            var response = new UpdateResponse();

            if (request == null)
            {
                response.IsError      = true;
                response.ErrorMessage = "Invalid request";
                return(response);
            }

            if (!contestantService.ContestantExists(request.Token))
            {
                response.IsError      = true;
                response.ErrorMessage = "You are not a registered player.  Register to play at /register";
                return(response);
            }

            var contestant = contestantService.GetContestantByToken(request.Token);

            if (contestant == null)
            {
                response.IsError      = true;
                response.ErrorMessage = "You are not a registered player.  Register to play at /register";
                return(response);
            }

            var timeSinceLastUpdate = timeService.Now() - contestant.LastSeen;

            if (timeSinceLastUpdate.TotalSeconds < UpdateRateLimitInSeconds)
            {
                response.IsError      = true;
                response.ErrorMessage = $"The rate limit requires you call this endpoint no more than once every {UpdateRateLimitInSeconds} seconds.";
                return(response);
            }

            // at this point we are done with validation
            contestant = new Contestant
                         (
                contestant.Name,
                contestant.Token,
                contestant.LastSeen,
                request.GenerationsComputed,
                contestant.StartedGameAt,
                contestant.EndedGameAt,
                request.ResultBoard
                         );

            var gameStatus = gameService.GetGameStatus();

            response.GameState = gameStatus.IsStarted ? GameState.InProgress : GameState.NotStarted;
            if (gameStatus.IsGameOver)
            {
                response.GameState = GameState.Over;
            }

            if (gameStatus.IsStarted)
            {
                contestant                    = StartContestantIfNotStarted(contestant);
                response.SeedBoard            = gameStatus.SeedBoard;
                response.GenerationsToCompute = gameStatus.NumberGenerations;
            }

            response.IsError = false;

            contestantService.UpdateContestant(contestant);
            return(response);
        }
Ejemplo n.º 22
0
        public void Should_Be_Able_To_Execute_An_Update_With_Output_Clause_And_Get_Back_Values()
        {
            // Arrange
            using (var sandbox = ConnectionTestsSandbox.Create())
            {
                var dbConnection = sandbox.Container.Resolve <CrmDbConnection>();

                var command = new CrmDbCommand(dbConnection);
                command.CommandText = "UPDATE contact SET firstname = 'JO', lastname = 'SCHMO' OUTPUT INSERTED.modifiedon, INSERTED.contactid WHERE contactid = '9bf20a16-6034-48e2-80b4-8349bb80c3e2'";
                command.CommandType = System.Data.CommandType.Text;

                var provider   = new SqlGenerationCrmOperationProvider(new DynamicsAttributeTypeProvider());
                var orgCommand = provider.GetOperation(command, System.Data.CommandBehavior.Default);

                // This is a fake CreateResponse that will be returned to our sut at test time.
                Guid expectedId     = Guid.Parse("9bf20a16-6034-48e2-80b4-8349bb80c3e2");
                var  createResponse = new UpdateResponse
                {
                    Results = new ParameterCollection()
                };

                // This is a fake RetrieveResponse that will be returned to our sut at test time.
                var resultEntity = new Entity("contact");
                resultEntity.Id           = expectedId;
                resultEntity["contactid"] = expectedId;
                var modifiedOnDate = DateTime.UtcNow;
                resultEntity["modifiedon"] = modifiedOnDate;
                var retrieveResponse = new RetrieveResponse
                {
                    Results = new ParameterCollection
                    {
                        { "Entity", resultEntity }
                    }
                };

                // This is a fake ExecuteMultipleResponse that will be returned to our sut at test time.
                var responses          = new ExecuteMultipleResponseItemCollection();
                var updateResponseItem = new ExecuteMultipleResponseItem();
                updateResponseItem.RequestIndex = 0;
                updateResponseItem.Response     = createResponse;
                responses.Add(updateResponseItem);

                var retrieveResponseItem = new ExecuteMultipleResponseItem();
                retrieveResponseItem.RequestIndex = 1;
                retrieveResponseItem.Response     = retrieveResponse;
                responses.Add(retrieveResponseItem);

                var executeMultipleResponse = new ExecuteMultipleResponse
                {
                    Results = new ParameterCollection
                    {
                        { "Responses", responses },
                        { "IsFaulted", false }
                    }
                };

                // Setup fake org service to return fake response.
                sandbox.FakeOrgService.Stub(f => f.Execute(Arg <OrganizationRequest> .Matches(new OrganizationRequestMessageConstraint <ExecuteMultipleRequest>())))
                .WhenCalled(x =>
                {
                    var request = ((ExecuteMultipleRequest)x.Arguments[0]);
                }).Return(executeMultipleResponse);

                // Act

                var sut = CrmOperationExecutor.Instance;
                dbConnection.Open();

                var commandResult = sut.ExecuteOperation(orgCommand);
                var results       = commandResult.ResultSet;

                //var results = sut.ExecuteCommand(orgCommand, System.Data.CommandBehavior.Default);

                // Assert

                // Should have 1 result, with the 2 output fields - createdon, and contactid
                Assert.That(results.ResultCount() == 1);
                Assert.That(results.HasColumnMetadata());

                var reader = commandResult.GetReader();
                Assert.That(reader.HasRows);
                Assert.That(reader.FieldCount == 2);

                while (reader.Read())
                {
                    Assert.That(reader.GetDateTime(0), NUnit.Framework.Is.EqualTo(modifiedOnDate));
                    Assert.That(reader.GetGuid(1), NUnit.Framework.Is.EqualTo(expectedId));
                }
            }
        }
Ejemplo n.º 23
0
        public UpdateResponse <TicketDTO> Update(Guid id, Guid userId, UpdateTicketRequest req)
        {
            var res = new UpdateResponse <TicketDTO>();

            var type = req.Type.ConvertToTicketType();

            var ticket = _ticketRepository.FindById(id);

            if (ticket == null)
            {
                return((UpdateResponse <TicketDTO>)res.ReturnErrorResponseWith("Ticket not found"));
            }

            if (ticket.Project.ProjectUsersReq.Where(
                    pur => pur.UserAssigned.Id.Equals(userId) ||
                    pur.Sender.Id.Equals(userId)).ToList().Count <= 0)
            {
                return((UpdateResponse <TicketDTO>)
                       res.ReturnErrorResponseWith("You can cnahge only tickets on projects that you are working on!"));
            }

            var user = _userRepository.FindById(userId);

            if (user == null)
            {
                return((UpdateResponse <TicketDTO>)
                       res.ReturnErrorResponseWith("User not found"));
            }

            var status = _ticketStatusRepository.FindById(req.StatusId);

            if (status == null)
            {
                return((UpdateResponse <TicketDTO>)
                       res.ReturnErrorResponseWith("Status not found"));
            }

            var histories = _ticketDomainService
                            .GetHistoriesFor(ticket,
                                             user,
                                             req.Title,
                                             req.Description,
                                             req.Deadline,
                                             type,
                                             status);


            if (type != TicketType.UNDEFINED)
            {
                ticket.Type = type;
            }


            ticket.Title       = req.Title;
            ticket.Description = req.Description;
            ticket.Deadline    = req.Deadline;
            ticket.Status      = status;

            ticket.Validate();

            if (ticket.GetBrokenRules().Count > 0)
            {
                return((UpdateResponse <TicketDTO>)
                       res.ReturnErrorResponseWithMultiple(ticket.GetBrokenRules()));
            }

            ticket.Updated = DateTime.Now;

            foreach (var history in histories)
            {
                _ticketHistoryRepository.Save(history);
            }

            _ticketRepository.Update(ticket);

            try
            {
                _uow.Commit();
            }
            catch (Exception ex)
            {
                return((UpdateResponse <TicketDTO>)
                       res.ReturnErrorResponseWith(ex.Message));
            }

            res.EntityDTO = _mapper.Map <Ticket, TicketDTO>(ticket);
            res.Success   = true;

            return(res);
        }
Ejemplo n.º 24
0
        public OrganizationResponse Execute( OrganizationRequest request )
        {
            if( request.GetType().Name == "RetrieveMultipleRequest" ) {
                RetrieveMultipleResponse response = new RetrieveMultipleResponse();
                EntityCollection result = RetrieveMultiple( ( ( RetrieveMultipleRequest )request ).Query );
                response.Results[ "EntityCollection" ] = result;
                return response;
            }
            else if(request.GetType().Name == "RetrieveRequest" ) {
                RetrieveResponse response = new RetrieveResponse();
                RetrieveRequest retrieveRequest = ( RetrieveRequest )request;
                EntityReference target = retrieveRequest.Target;

                if( target.GetType().Name == "TargetRetrieveDynamic" ) {
                /*
                    TargetRetrieveDynamic trd = ( TargetRetrieveDynamic )target;
                    response.Entity = Retrieve( trd.EntityName, trd.EntityId, retrieveRequest.ColumnSet );
                */
                }

                // TODO: entity is readonly .. will have to set this with reflection
                // response.Entity = Retrieve( target.LogicalName, target.Id, retrieveRequest.ColumnSet );

                else {
                        // request sent using a specific strongly-typed business entity
                        // rather than a DynamicEntity
                        throw new NotImplementedException();
                }
                return response;
            }
            else if( request.GetType().Name == "CreateRequest" ) {
                CreateResponse response = new CreateResponse();
                Guid result = Create( ( ( CreateRequest )request ).Target );
                response.Results[ "id" ] = result;
                return response;
            }
            else if( request.GetType().Name == "UpdateRequest" ) {
                UpdateResponse response = new UpdateResponse();
                Update( ( ( UpdateRequest )request).Target );
                return response;
            }
            else {
                throw new NotImplementedException();
            }
        }
Ejemplo n.º 25
0
        static async Task Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Pass the server address as the 1st parameter.");
                return;
            }

            var server     = args[0];
            var clientName = Environment.UserName;

            if (args.Length > 1)
            {
                clientName = args[1];
            }

            HttpWebResponse response;
            var             timer = Stopwatch.StartNew();

            do
            {
                Console.WriteLine($"Connecting to server @ {server}");
                var request = WebRequest.CreateHttp(server);
                response = (HttpWebResponse)request.GetResponse();
            } while (response.StatusCode != HttpStatusCode.OK && timer.Elapsed.TotalSeconds < 30);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                Console.WriteLine("Server didn't come up.  What's going on?");
                return;
            }

            client = RestService.For <IContestServer>(server);
            var registerRequest = new RegisterRequest {
                Name = clientName
            };
            RegisterResponse registerResponse;

            while (true)
            {
                try
                {
                    registerResponse = await client.Register(registerRequest);

                    break;
                }
                catch
                {
                    registerRequest.Name += "_1";
                }
            }

            token  = registerResponse.Token;
            status = ClientStatus.Waiting;

            UpdateResponse updateResponse = null;

            do
            {
                if (updateResponse != null)
                {
                    Console.WriteLine("Waiting for game to start... {0}", DateTime.Now);
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
                updateResponse = await client.Update(new UpdateRequest
                {
                    Token = token
                });
            } while (updateResponse.GameState == GameState.NotStarted);

            var seedBoard = updateResponse.SeedBoard;

            generationsToCompute = updateResponse.GenerationsToCompute ?? 0;
            Console.WriteLine($"Got seed board w/{seedBoard.Count()} live cells counting {generationsToCompute} generations.");

            heartbeatTimer = new Timer(new TimerCallback(heartbeat), state: null, dueTime: 500, period: 500);

            status = ClientStatus.Processing;
            GameSolver.GenerationBatchCompleted += (s, e) => Interlocked.Exchange(ref generationsComputed, e.GenerationsComputed);
            solvedBoard = GameSolver.Solve(seedBoard, generationsToCompute, batchSize: 5);
            status      = ClientStatus.Complete;


            Console.WriteLine("You finished!");
            Console.ReadLine();
        }
Ejemplo n.º 26
0
 public SingleMessageHandle(UpdateResponse messageResponse)
     : this(messageResponse.ts, messageResponse.channel)
 {
 }
Ejemplo n.º 27
0
        private OrganizationResponse CallOrganizationServiceRequestForExecuteRequest(OrganizationRequest request)
        {
            OrganizationResponse response = null;
            var associate = request as AssociateRequest;

            if (associate != null)
            {
                response = new AssociateResponse();
                Associate(associate.Target.LogicalName, associate.Target.Id, associate.Relationship, associate.RelatedEntities);
            }

            var create = request as CreateRequest;

            if (create != null)
            {
                response = new CreateResponse {
                    ["id"] = Create(create.Target)
                };
            }

            var delete = request as DeleteRequest;

            if (delete != null)
            {
                response = new DeleteResponse();
                Delete(delete.Target.LogicalName, delete.Target.Id);
            }

            var disassociate = request as DisassociateRequest;

            if (disassociate != null)
            {
                response = new AssociateResponse();
                Disassociate(disassociate.Target.LogicalName, disassociate.Target.Id, disassociate.Relationship, disassociate.RelatedEntities);
            }

            var retrieve = request as RetrieveRequest;

            if (retrieve != null)
            {
                response = new RetrieveResponse {
                    ["Entity"] = Retrieve(retrieve.Target.LogicalName, retrieve.Target.Id, retrieve.ColumnSet)
                };
            }

            var retrieveMultiple = request as RetrieveMultipleRequest;

            if (retrieveMultiple != null)
            {
                response = new RetrieveMultipleResponse {
                    ["EntityCollection"] = RetrieveMultiple(retrieveMultiple.Query)
                };
            }

            var update = request as UpdateRequest;

            if (update != null)
            {
                response = new UpdateResponse();
                Update(update.Target);
            }
            return(response);
        }
        private OrganizationResponse CallOrganizationServiceRequestForExecuteRequest(OrganizationRequest request)
        {
            OrganizationResponse response = null;
            var associate = request as AssociateRequest;
            if (associate != null)
            {
                response = new AssociateResponse();
                Associate(associate.Target.LogicalName, associate.Target.Id, associate.Relationship, associate.RelatedEntities);
            }

            var create = request as CreateRequest;
            if (create != null)
            {
                response = new CreateResponse();
                response["id"] = Create(create.Target);
            }

            var delete = request as DeleteRequest;
            if (delete != null)
            {
                response = new DeleteResponse();
                Delete(delete.Target.LogicalName, delete.Target.Id);
            }

            var disassociate = request as DisassociateRequest;
            if (disassociate != null)
            {
                response = new AssociateResponse();
                Disassociate(disassociate.Target.LogicalName, disassociate.Target.Id, disassociate.Relationship, disassociate.RelatedEntities);
            }

            var retrieve = request as RetrieveRequest;
            if (retrieve != null)
            {
                response = new RetrieveResponse();
                response["Entity"] = Retrieve(retrieve.Target.LogicalName, retrieve.Target.Id, retrieve.ColumnSet);
            }

            var retrieveMultiple = request as RetrieveMultipleRequest;
            if (retrieveMultiple != null)
            {
                response = new RetrieveMultipleResponse();
                response["EntityCollection"] = RetrieveMultiple(retrieveMultiple.Query);
            }

            var update = request as UpdateRequest;
            if (update != null)
            {
                response = new UpdateResponse();
                Update(update.Target);
            }
            return response;
        }
        public static UpdateResponse UpdateBookingDetails(string propCode, BookingViewModel model)
        {
            var webAddr        = "https://chartswebintf-fra.chartspms.com.au/json/execute?un=charteuhh&pw=hh246eu";
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);

            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method      = "POST";

            JavaScriptSerializer js = new JavaScriptSerializer();

            login logdetails = new login();

            logdetails.user = "******";
            logdetails.pasw = "";

            propIdent requestdata = new propIdent();

            requestdata.mesg     = "ResvUpdate";
            requestdata.propcode = propCode;
            requestdata.login    = logdetails;

            Update jsonupdate = new Update();

            guest g = new guest();

            g.salu = model.salu;
            g.naml = model.lastName;
            g.namf = model.firstName;
            g.comp = model.company;
            g.emai = model.email;
            g.cell = model.cellnumber;
            g.phon = model.phonenumber;
            g.secu = model.secu;

            addr a = new addr();

            a.line1 = model.address1;
            a.line2 = model.address2;
            a.city  = model.city;
            a.posc  = model.postcode;
            a.stat  = model.state;
            a.cnty  = model.country;
            g.addr  = a;

            stay s = new stay();

            s.arrt = model.timearrival;
            s.paym = model.paym;
            if (model.cardNumber != null)
            {
                s.card      = new Card();
                s.card.auth = model.cardHolder;
                s.card.numb = model.cardNumber;
                s.card.expy = model.cardEndDate;
            }

            List <exflds> ext = new List <exflds>();

            if (model.gender != null)
            {
                exflds e = new exflds();
                e.numb  = 65;
                e.value = model.gender;
                ext.Add(e);
            }

            //if (ext.Count > 0)
            //{
            //    s.exflds = ext.ToArray();
            //}

            //if (false) {
            //List<exflds> ext = new List<exflds>();

            if (model.document != null)
            {
                exflds e = new exflds();
                e.numb  = 74;
                e.value = model.document;
                ext.Add(e);
            }

            if (model.idtype != null)
            {
                exflds n = new exflds();
                n.numb  = 75;
                n.value = model.idtype;
                ext.Add(n);
            }

            if (model.secu != null)
            {
                exflds n = new exflds();
                n.numb  = 76;
                n.value = model.secu;
                ext.Add(n);
            }

            if (ext.Count > 0)
            {
                s.exflds = ext.ToArray();
            }
            //}

            jsonupdate.ident = requestdata;
            jsonupdate.indx  = model.index;
            jsonupdate.guest = g;
            jsonupdate.stay  = s;

            Update[] sendarray = { jsonupdate };

            jsonUpdateModel array = new jsonUpdateModel();

            array.requests = sendarray;

            string json = JsonConvert.SerializeObject(array);

            using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
            }

            HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader    streamReader = new StreamReader(httpResponse.GetResponseStream());

            string result = streamReader.ReadToEnd(); //in result is the end data.
            jsonUpdateResponseModel response = JsonConvert.DeserializeObject <jsonUpdateResponseModel>(result);

            UpdateResponse data = response.responses[0];

            return(data);
        }
        private async Task <UpdateResponse> UpdateAttribute(RepresentationAttribute source, RepresentationAttribute target, string resourceType)
        {
            var result        = new UpdateResponse();
            var complexSource = source as ComplexRepresentationAttribute;
            var complexTarget = target as ComplexRepresentationAttribute;

            if (complexTarget != null)
            {
                var schemaAttribute = complexTarget.SchemaAttribute;
                if (schemaAttribute.MultiValued)
                {
                    // Check mutability
                    if (schemaAttribute.Mutability == Common.Constants.SchemaAttributeMutability.Immutable)
                    {
                        if (complexTarget.CompareTo(complexSource) != 0)
                        {
                            result.SetError(_errorResponseFactory.CreateError(string.Format(ErrorMessages.TheImmutableAttributeCannotBeUpdated, schemaAttribute.Name),
                                                                              HttpStatusCode.BadRequest,
                                                                              Common.Constants.ScimTypeValues.Mutability));
                            return(result);
                        }
                    }

                    // Check uniqueness
                    if (schemaAttribute.Uniqueness == Common.Constants.SchemaAttributeUniqueness.Server)
                    {
                        var filter      = _filterParser.Parse(complexTarget.FullPath);
                        var uniqueAttrs = await _representationStore.SearchValues(resourceType, filter);

                        if (uniqueAttrs.Any())
                        {
                            if (uniqueAttrs.Any(a => a.CompareTo(complexTarget) == 0))
                            {
                                result.SetError(_errorResponseFactory.CreateError(
                                                    string.Format(ErrorMessages.TheAttributeMustBeUnique, complexTarget.SchemaAttribute.Name),
                                                    HttpStatusCode.BadRequest,
                                                    Common.Constants.ScimTypeValues.Uniqueness));
                                return(result);
                            }
                        }
                    }
                }

                complexSource.Values = complexTarget.Values;
                return(result);
            }

            // Check mutability
            if (target.SchemaAttribute.Mutability == Common.Constants.SchemaAttributeMutability.Immutable)
            {
                if (source.CompareTo(target) != 0)
                {
                    result.SetError(_errorResponseFactory.CreateError(string.Format(ErrorMessages.TheImmutableAttributeCannotBeUpdated, target.SchemaAttribute.Name),
                                                                      HttpStatusCode.BadRequest,
                                                                      Common.Constants.ScimTypeValues.Mutability));
                    return(result);
                }
            }

            // Check uniqueness
            if (target.SchemaAttribute.Uniqueness == Common.Constants.SchemaAttributeUniqueness.Server)
            {
                var filter      = _filterParser.Parse(target.FullPath);
                var uniqueAttrs = await _representationStore.SearchValues(resourceType, filter);

                if (uniqueAttrs.Any())
                {
                    if (uniqueAttrs.Any(a => a.CompareTo(target) == 0))
                    {
                        result.SetError(_errorResponseFactory.CreateError(
                                            string.Format(ErrorMessages.TheAttributeMustBeUnique, target.SchemaAttribute.Name),
                                            HttpStatusCode.BadRequest,
                                            Common.Constants.ScimTypeValues.Uniqueness));
                        return(result);
                    }
                }
            }

            // Assign the values
            AssignValues(source, target);
            return(result);
        }
Ejemplo n.º 31
0
        public byte[] Update(byte[] requestData)
        {
            object result = null;
            try
            {
                UpdateRequest request = (UpdateRequest)Deserialize(requestData);
                IDataAccess dao = DataAccessFactory.Create(request.ObjectType);
                int state = dao.Update(request.Object);
                result = new UpdateResponse() { Result = state };
            }
            catch (Exception ex)
            { result = ex; }

            return Serialize(result);
        }
        public virtual async Task <IActionResult> Update(int id, [FromBody] ApiProductModelProductDescriptionCultureRequestModel model)
        {
            ApiProductModelProductDescriptionCultureRequestModel request = await this.PatchModel(id, this.ProductModelProductDescriptionCultureModelMapper.CreatePatch(model));

            if (request == null)
            {
                return(this.StatusCode(StatusCodes.Status404NotFound));
            }
            else
            {
                UpdateResponse <ApiProductModelProductDescriptionCultureResponseModel> result = await this.ProductModelProductDescriptionCultureService.Update(id, request);

                if (result.Success)
                {
                    return(this.Ok(result));
                }
                else
                {
                    return(this.StatusCode(StatusCodes.Status422UnprocessableEntity, result));
                }
            }
        }
Ejemplo n.º 33
0
        private async Task <UpdateResponse> Updates(CrunchySession s, ShowType t)
        {
            int            startpage = 0;
            UpdateResponse ret       = new UpdateResponse();
            bool           end       = false;

            do
            {
                string    url = string.Format(LibSet[UpdateUrlS], ShowFromType(t), startpage);
                WebStream ws  = await WebStream.Get(url, null, LibSet[UserAgentS], null, s.cookies.ToCookieCollection(), SocketTimeout, true, null, _info.ProxyFromGlobalRequirements(_global));

                if (ws != null && ws.StatusCode == HttpStatusCode.OK)
                {
                    if (!VerifyLogin(ws.Cookies))
                    {
                        ws.Dispose();
                        SetLoginError(ret);
                        return(ret);
                    }
                    StreamReader rd  = new StreamReader(ws);
                    string       dta = rd.ReadToEnd();
                    rd.Dispose();
                    MatchCollection scol = updregex.Matches(dta);
                    if (scol.Count == 0)
                    {
                        end = true;
                    }
                    foreach (Match m in scol)
                    {
                        string show  = m.Groups["show"].Value;
                        string image = m.Groups["image"].Value;
                        string title = WebUtility.HtmlDecode(m.Groups["title"].Value);
                        string ep    = m.Groups["ep"].Value;
                        Uri    ur    = new Uri("http://www.crunchyroll.com" + m.Groups["url"].Value);
                        int    a     = ep.IndexOf("&ndash;", StringComparison.InvariantCulture);
                        if (a >= 0)
                        {
                            ep = ep.Substring(0, a).Trim();
                            string tag = CrunchyPluginInfo.PluginName + "|" + show + "|" + ep;
                            if (UpdateHistory.Exists(tag))
                            {
                                Episode c = JsonConvert.DeserializeObject <Episode>(UpdateHistory.Get(tag));
                                ret.Found.Add(c);
                            }
                            else
                            {
                                Episode p = new Episode();
                                p.PluginMetadata.Add("Url", ur.ToString());
                                p.ShowName   = title;
                                p.ShowId     = show;
                                p.PluginName = CrunchyPluginInfo.PluginName;
                                p.UniqueTag  = tag;
                                p.ImageUri   = new Uri(image);
                                p.Type       = t;
                                ret.NotFound.Add(p);
                            }
                        }
                    }
                }
                else
                {
                    ws?.Dispose();
                    SetWebError(ret);
                    return(ret);
                }
                ws?.Dispose();
                startpage++;
            } while (!end);
            return(ret);
        }
Ejemplo n.º 34
0
        public ExecuteTransactionResponse GetTransactionResponse(ExecuteTransactionRequest request)
        {
            var requestDictionary = new Dictionary <int, string>();

            var batchid          = "batch_" + Guid.NewGuid().ToString();
            var batchContent     = new MultipartContent("mixed", batchid);
            var changesetID      = "changeset_" + Guid.NewGuid().ToString();
            var changeSetContent = new MultipartContent("mixed", changesetID);

            for (int contentId = 1; contentId <= request.Requests.Count; contentId++)
            {
                HttpMessageContent content = new HttpMessageContent(GetRequestMessage((OrganizationRequest)request.Requests[contentId - 1]));
                content.Headers.Remove("Content-Type");
                content.Headers.TryAddWithoutValidation("Content-Type", "application/http");
                content.Headers.TryAddWithoutValidation("Content-Transfer-Encoding", "binary");
                content.Headers.TryAddWithoutValidation("Content-ID", contentId.ToString());
                changeSetContent.Add(content);
                requestDictionary.Add(contentId, ((OrganizationRequest)request.Requests[contentId - 1]).RequestName);
            }

            batchContent.Add(changeSetContent);

            var batchRequest = new HttpRequestMessage(HttpMethod.Post, _endpoint + "$batch")
            {
                Content = batchContent
            };

            var batchstring = batchRequest.Content.ReadAsStringAsync();

            var httpClient = new HttpClient(new HttpClientHandler {
                Credentials = _credential ?? CredentialCache.DefaultNetworkCredentials
            });
            var response = httpClient.SendAsync(batchRequest)?.Result;

            if (response == null)
            {
                throw new Exception("Сервер вернул пустой ответ");
            }

            if (!response.IsSuccessStatusCode)
            {
                var exception = JsonSerializer.Deserialize <CrmException>(response.Content.ReadAsStringAsync().Result);
                throw new CrmException(exception.Error.Message, exception);
            }

            var responseString = response.Content.ReadAsStringAsync();
            MultipartMemoryStreamProvider batchStream = response.Content.ReadAsMultipartAsync().Result;
            var batchStreamContent = batchStream.Contents.FirstOrDefault();

            MultipartMemoryStreamProvider changesetStream = batchStreamContent.ReadAsMultipartAsync().Result;

            var transactionResponse = new ExecuteTransactionResponse();

            foreach (var changesetContent in changesetStream.Contents)
            {
                changesetContent.Headers.Remove("Content-Type");
                changesetContent.Headers.Add("Content-Type", "application/http; msgtype=response");

                var indivdualResponse = changesetContent.ReadAsHttpResponseMessageAsync().Result;

                if (!indivdualResponse.IsSuccessStatusCode)
                {
                    var exception = JsonSerializer.Deserialize <CrmException>(response.Content.ReadAsStringAsync().Result);
                    throw new CrmException(exception.Error.Message, exception);
                }

                var operationName = requestDictionary.FirstOrDefault(dic => dic.Key == int.Parse(changesetContent.Headers.GetValues("Content-ID").FirstOrDefault())).Value;

                if (operationName == Constants.CREATE)
                {
                    var idString = indivdualResponse.Headers.GetValues("OData-EntityId").FirstOrDefault();
                    idString = idString.Replace(_endpoint, "").Replace("(", "").Replace(")", "");
                    idString = idString.Substring(idString.Length - 36);

                    var createResponse = new CreateResponse {
                        Id = Guid.Parse(idString), ResponseName = operationName
                    };
                    transactionResponse.Responses.Add(createResponse);
                }

                if (operationName == Constants.UPDATE)
                {
                    var updateResponse = new UpdateResponse {
                        ResponseName = operationName
                    };
                    transactionResponse.Responses.Add(updateResponse);
                }

                if (operationName == Constants.DELETE)
                {
                    var deleteResponse = new DeleteResponse {
                        ResponseName = operationName
                    };
                    transactionResponse.Responses.Add(deleteResponse);
                }

                if (operationName == Constants.DISASSOCIATE)
                {
                    var deleteResponse = new DissacociateResponse {
                        ResponseName = operationName
                    };
                    transactionResponse.Responses.Add(deleteResponse);
                }

                if (operationName == Constants.ASSOCIATE)
                {
                    var deleteResponse = new AssociateResponse {
                        ResponseName = operationName
                    };
                    transactionResponse.Responses.Add(deleteResponse);
                }
            }

            return(transactionResponse);
        }
Ejemplo n.º 35
0
        public UpdateResponse UpdateExercise(Exercise exercise)
        {
            var cr = new UpdateResponse();

            return cr;
        }
Ejemplo n.º 36
0
 protected override void ExpectResponse(UpdateResponse <Project> response)
 {
     response.ShouldBeValid();
     response.Result.Should().Be(Result.Noop);
 }
Ejemplo n.º 37
0
        void UpdateEmailAddress(UpdateResponse updateResponse)
        {
            if (string.IsNullOrEmpty(updateResponse?.Message?.Text))
                return;
            var senderUserName = updateResponse.Message.From.UserName;
            var chatId = updateResponse.Message?.Chat.Id;
            var Reg = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
            if (!Reg.IsMatch(updateResponse?.Message?.Text))
            {
                Bot.SendMessage(new SendMessageRequest
                {
                    ChatId = (int)chatId,
                    Text = string.Format(BusinessMessages.IncorrectEmail, senderUserName) ,
                    ReplyToMessageId = updateResponse.Message.MessageId
                });
                return;
            }
            var result = _userSercvice.Update(updateResponse?.Message?.Text, (int)chatId);
            var returnText = string.Empty;

            switch (result)
            {
                case UpdateResult.UserNotExist:
                    {
                        returnText = BusinessMessages.UserNotExist;
                        break;
                    }
                case UpdateResult.Success:
                    {
                        returnText = string.Format(BusinessMessages.EmailSaved, senderUserName);
                        try
                        {
                            Bot.GetUserProfilePhotos(new GetUserProfilePhotosRequest { UserId = (int)chatId });
                        }
                        catch (Exception e)
                        {
                            Console.Write(e.Message);
                        }
                        break;
                    }
                case UpdateResult.Error:
                    {
                        returnText = string.Format(BusinessMessages.Error, senderUserName);
                        break;
                    }
            }
            Bot.SendMessage(new SendMessageRequest
            {
                ChatId = (int)chatId,
                Text = returnText,
                ReplyToMessageId = updateResponse.Message.MessageId
            });
        }
Ejemplo n.º 38
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    ////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate
                    // Retrieve an account.
                    var account = service.Retrieve("account", accountId, new ColumnSet("name", "creditlimit"));
                    Console.WriteLine("\tThe row version of the created account is {0}", account.RowVersion);

                    if (account != null)
                    {
                        // Create an in-memory account object from the retrieved account.
                        var updatedAccount = new Entity()
                        {
                            LogicalName = account.LogicalName,
                            Id          = account.Id,
                            RowVersion  = account.RowVersion
                        };

                        // Update just the credit limit.
                        updatedAccount["creditlimit"] = new Money(1000000);

                        // Set the request's concurrency behavour to check for a row version match.
                        var accountUpdate = new UpdateRequest()
                        {
                            Target = updatedAccount,
                            ConcurrencyBehavior = ConcurrencyBehavior.IfRowVersionMatches
                        };

                        // Do the update.
                        UpdateResponse accountUpdateResponse = (UpdateResponse)service.Execute(accountUpdate);
                        Console.WriteLine("Account '{0}' updated with a credit limit of {1}.", account["name"],
                                          ((Money)updatedAccount["creditlimit"]).Value);

                        account = service.Retrieve("account", updatedAccount.Id, new ColumnSet());
                        Console.WriteLine("\tThe row version of the updated account is {0}", account.RowVersion);
                        accountRowVersion = account.RowVersion;
                    }

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }

                #endregion Demonstrate
                #endregion Sample Code
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Ejemplo n.º 39
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// basic create, retrieve, update, and delete entity operations are performed.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetInvokeDuplicateDetectionForCreateAndUpdate1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;

                    CreateRequiredRecords();

                    // Create and account record with the named Proseware, Inc. and already existing Account Number.
                    Account account = new Account
                    {
                        Name          = "Proseware, Inc.",
                        AccountNumber = "ACC005"
                    };

                    // Create operation by suppressing duplicate detection
                    CreateRequest reqCreate = new CreateRequest();
                    reqCreate.Target = account;
                    reqCreate.Parameters.Add("SuppressDuplicateDetection", true); // Change to false to activate the duplicate detection.
                    CreateResponse createResponse = (CreateResponse)_service.Execute(reqCreate);
                    _dupAccountId = createResponse.id;
                    Console.Write("Account: {0} {1} created with SuppressDuplicateDetection to true, ",
                                  account.Name, account.AccountNumber);

                    // Retrieve the account containing with its few attributes.
                    ColumnSet cols = new ColumnSet(
                        new String[] { "name", "accountnumber" });

                    Account retrievedAccount = (Account)_service.Retrieve("account", _dupAccountId, cols);
                    Console.Write("retrieved, ");

                    // Update the existing account with new account number.
                    retrievedAccount.AccountNumber = "ACC006";

                    // Update operation – update record, if a duplicate is not found.
                    UpdateRequest reqUpdate = new UpdateRequest();
                    reqUpdate.Target = retrievedAccount;
                    reqUpdate["SuppressDuplicateDetection"] = false; // Duplicate detection is activated.

                    // Update the account record.
                    UpdateResponse updateResponse = (UpdateResponse)_service.Execute(reqUpdate);
                    Console.WriteLine("and updated.");

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetInvokeDuplicateDetectionForCreateAndUpdate1>
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }