Example #1
0
        public void And_callback_target_does_not_return_200_Then_callback_fields_are_not_updated()
        {
            _mockHttp.When("https://localhost/callback").Respond(HttpStatusCode.BadRequest);

            var invitationId = Guid.NewGuid();
            var invitation   = new Invitation
            {
                Id          = invitationId,
                SourceId    = "S0U4C31D",
                CallbackUri = new Uri("https://localhost/callback")
            };

            _loginContext.Invitations.Add(invitation);
            _loginContext.SaveChanges();

            var callbackService = new CallbackService(_mockHttp.ToHttpClient(), _loginContext);


            SystemTime.UtcNow = () => new DateTime(2018, 2, 27, 9, 0, 0);

            callbackService.Callback(invitation, "LOGINUSERID");

            var updatedInvitation = _loginContext.Invitations.Single(i => i.Id == invitationId);

            updatedInvitation.IsCalledBack.Should().BeFalse();
            updatedInvitation.CallbackDate.Should().BeNull();
        }
Example #2
0
        public void And_callback_target_url_cannot_be_resolved_Then_callback_fields_are_not_updated()
        {
            _mockHttp.When("https://localhost/callback").Throw(new HttpRequestException());

            var invitationId = Guid.NewGuid();
            var invitation   = new Invitation
            {
                Id          = invitationId,
                SourceId    = "S0U4C31D",
                CallbackUri = new Uri("https://localhost/callback")
            };

            _loginContext.Invitations.Add(invitation);
            _loginContext.SaveChanges();

            var callbackService = new CallbackService(_mockHttp.ToHttpClient(), _loginContext);


            SystemTime.UtcNow = () => new DateTime(2018, 2, 27, 9, 0, 0);

            callbackService.Invoking(cs => cs.Callback(invitation, "LOGINUSERID")).Should().NotThrow <HttpRequestException>();

            var updatedInvitation = _loginContext.Invitations.Single(i => i.Id == invitationId);

            updatedInvitation.IsCalledBack.Should().BeFalse();
            updatedInvitation.CallbackDate.Should().BeNull();
        }
        /// <summary>
        /// Constructs the Freshbooks API authentication and wrapper class
        /// </summary>
        /// <param name="accountName">The account name for which you are trying to access</param>
        /// <param name="consumerKey">The developer's freshbooks account name</param>
        /// <param name="oauthSecret">The developer's oauth-secret provided by freshbooks</param>
        public FreshbooksApi(string accountName, string consumerKey, string oauthSecret)
        {
            _accountName = accountName;
            _consumerKey = consumerKey;
            _oauthSecret = oauthSecret ?? String.Empty;

            _baseUri = new UriBuilder { Scheme = "https", Host = accountName + ".freshbooks.com" }.Uri;
            _serviceUri = new Uri(_baseUri, "/api/2.1/xml-in");
            Clear();

            UserAgent = String.Format("{0}/{1} ({2})", 
                GetType().Name,
                GetType().Assembly.GetName().Version.ToString(2), 
                GetType().Assembly.FullName);

            Callback = new CallbackService(new ServiceProxy(this, "callback"));
            Category = new CategoryService(new ServiceProxy(this, "category"));
            Client = new ClientService(new ServiceProxy(this, "client"));
            Estimate = new EstimateService(new ServiceProxy(this, "estimate"));
            Expense = new ExpenseService(new ServiceProxy(this, "expense"));
            Gateway = new GatewayService(new ServiceProxy(this, "gateway"));
            Invoice = new InvoiceService(new ServiceProxy(this, "invoice"));
            Item = new ItemService(new ServiceProxy(this, "item"));
            Language = new LanguageService(new ServiceProxy(this, "language"));
            Payment = new PaymentService(new ServiceProxy(this, "payment"));
            Project = new ProjectService(new ServiceProxy(this, "project"));
            Recurring = new RecurringService(new ServiceProxy(this, "recurring"));
            System = new SystemService(new ServiceProxy(this, "system"));
            Staff = new StaffService(new ServiceProxy(this, "staff"));
            Task = new TaskService(new ServiceProxy(this, "task"));
            Tax = new TaxService(new ServiceProxy(this, "tax"));
            TimeEntry = new TimeEntryService(new ServiceProxy(this, "time_entry"));
        }
 public void InvokeAsync(AsyncExecutionRequest request, Action <AsyncExecutionResponse> responseHandler = null)
 {
     responseHandler = responseHandler ?? DefaultResponseHandler;
     if (!request.UseCachedResponse)
     {
         CallExecuteRemoteAsync(request, responseHandler);
     }
     else
     {
         AsyncExecutionResponseData response = CallbackService.GetCachedResponse(request.GetRequestHash());
         if (response != null && new Instant(DateTime.UtcNow).DiffInMinutes(response.Created.Value) <= request.ResponseMaxAgeInMinutes)
         {
             AsyncExecutionResponse result = response.CopyAs <AsyncExecutionResponse>();
             result.Success    = true;
             result.Request    = request;
             result.ResultJson = response.ResultJson;
             responseHandler(result);
         }
         else
         {
             if (response != null)
             {
                 CallbackService.AsyncCallbackRepository.Delete(response);
             }
             CallExecuteRemoteAsync(request, responseHandler);
         }
     }
 }
Example #5
0
        public async Task Then_ClientCallBack_user_log_entry_is_created()
        {
            _mockHttp.When("https://localhost/callback").Respond(HttpStatusCode.OK);

            var callbackService = new CallbackService(_mockHttp.ToHttpClient(), _loginContext);

            var invitation = new Invitation
            {
                Email       = "*****@*****.**",
                SourceId    = "S0U4C31D",
                CallbackUri = new Uri("https://localhost/callback")
            };

            SystemTime.UtcNow = () => new DateTime(2019, 1, 1, 1, 1, 1);
            var logId = Guid.NewGuid();

            GuidGenerator.NewGuid = () => logId;

            await callbackService.Callback(invitation, "LOGINUSERID");

            var logEntry = _loginContext.UserLogs.Single();

            var expectedLogEntry = new UserLog
            {
                Id        = logId,
                DateTime  = SystemTime.UtcNow(),
                Email     = "*****@*****.**",
                Action    = "Client callback",
                Result    = "Callback OK",
                ExtraData = JsonConvert.SerializeObject(new { CallbackUri = "https://localhost/callback", SourceId = "S0U4C31D", UserId = "LOGINUSERID" })
            };

            logEntry.Should().BeEquivalentTo(expectedLogEntry);
        }
Example #6
0
        public void Then_callback_service_is_called()
        {
            Handler.Handle(new CreatePasswordRequest {
                InvitationId = InvitationId, Password = "******"
            }, CancellationToken.None).Wait();

            CallbackService.Received().Callback(Arg.Is <Invitation>(i => i.SourceId == "ABC123"), NewLoginUserId.ToString());
        }
        public void Then_callback_service_is_not_called()
        {
            Handler.Handle(new CreatePasswordRequest {
                InvitationId = InvitationId, Password = "******"
            }, CancellationToken.None).Wait();

            CallbackService.DidNotReceiveWithAnyArgs().Callback(Arg.Any <Invitation>(), Arg.Any <string>());
        }
Example #8
0
    public void CallbackAsync(Func <TReturnValue> callback)
    {
        var callbackService = new CallbackService(_originalMethodInfo, _hookServiceFactory, _hookBuilder);

        using (callbackService.CallbackAsync(callback))
        {
            _action();
        }
    }
Example #9
0
        public CallbackServiceTests()
        {
            _mockAuthorizationService   = new Mock <IAuthorizationService>();
            _mockUserDataCachingService = new Mock <IUserDataCachingService>();

            _callbackService = new CallbackService(_mockAuthorizationService.Object, _mockUserDataCachingService.Object);

            _mockUserDataCachingService.Setup(x => x.ClearUserData(It.IsAny <string>()))
            .ReturnsAsync(ServiceResult.Succeeded);
        }
Example #10
0
        public void TestManyDumplexServersAndClientsCreatingsConcurencyOnNamedPipe()
        {
            var address  = @"net.pipe://127.0.0.1/testpipename" + MethodBase.GetCurrentMethod().Name;
            var servers  = 5;
            var clients  = 5;
            var srv      = new CallbackService();
            var callback = new CallbackServiceCallback();

            var tasks = new List <Task>();

            for (int i = 0; i < servers; i++)
            {
                var custom = address + i;
                var task   = new Task(() =>
                {
                    using (var server = new ServiceHost(srv, new Uri(address)))
                    {
                        server.AddServiceEndpoint(typeof(ICallbackService), new NetNamedPipeBinding {
                        }, custom);
                        server.Open();
                        var requests = new List <Task>();
                        var channels = new ConcurrentBag <DuplexChannelFactory <ICallbackService> >();
                        for (int j = 0; j < clients; j++)
                        {
                            var childTask = new Task(() =>
                            {
                                var channelFactory = new DuplexChannelFactory <ICallbackService>(new InstanceContext(callback), new NetNamedPipeBinding());
                                var client         = channelFactory.CreateChannel(new EndpointAddress(custom));
                                client.Execute();
                                channels.Add(channelFactory);
                            });
                            requests.Add(childTask);
                        }
                        foreach (var request in requests)
                        {
                            request.Start();
                        }
                        Task.WaitAll(requests.ToArray());

                        foreach (var factory in channels)
                        {
                            factory.Dispose();
                        }
                    }
                });
                task.Start();
                tasks.Add(task);
            }
            while (callback.Count != servers * clients)
            {
                Thread.Sleep(10);
            }
            Task.WaitAll(tasks.ToArray());
        }
Example #11
0
 public void StartService(string port = "50052")
 {
     servicePort   = Int32.Parse(port);
     service       = new CallbackService();
     serviceServer = new Server {
         Services = { BindService(new CallbackService()) },
         Ports    = { new ServerPort("localhost", servicePort, ServerCredentials.Insecure) }
     };
     serviceServer.Start();
     running = true;
     Debug.Log("CallbackService server listening on port " + servicePort);
 }
Example #12
0
 public void TestDuplexService()
 {
     using (ServiceHost host = new ServiceHost(typeof(DuplexService)))
     {
         EndpointAddress address         = new EndpointAddress(new Uri("net.threadless://test/DuplexService.svc"));
         CallbackService callbackService = new CallbackService();
         using (var client = new ThreadlessDuplexClient <DuplexService, IDuplexService>(address, callbackService))
         {
             client.Client.Ping("Hello");
             callbackService.Text.Should().Be("Ping: Hello");
         }
     }
 }
Example #13
0
    public void Callback <TReturnValue>(Func <TReturnValue> callback)
    {
        if (callback == null)
        {
            throw new ArgumentNullException(nameof(callback));
        }

        var callbackService = new CallbackService(_originalMethodInfo, _hookServiceFactory, _hookBuilder);

        using (callbackService.Callback(callback))
        {
            _action();
        }
    }
Example #14
0
        public void Then_correct_json_is_posted_to_callback_uri()
        {
            _mockHttp.Expect("https://localhost/callback").WithContent(JsonConvert.SerializeObject(new { sub = "LOGINUSERID", sourceId = "S0U4C31D" }));

            var callbackService = new CallbackService(_mockHttp.ToHttpClient(), _loginContext);

            var invitation = new Invitation
            {
                SourceId    = "S0U4C31D",
                CallbackUri = new Uri("https://localhost/callback")
            };

            callbackService.Callback(invitation, "LOGINUSERID");

            _mockHttp.VerifyNoOutstandingExpectation();
        }
Example #15
0
        static void Main(string[] args)
        {
            // Setup the service host here
            var serviceInstance = new CallbackService();

            using (var serviceHost = new ServiceHost(serviceInstance))
            {
                try
                {
                    serviceHost.Open();

                    Console.WriteLine("CallbackService is ready.");
                    while (true)
                    {
                        Console.WriteLine("Enter a message to send to the clients or type 'exit' to end:");
                        var message = Console.ReadLine();
                        if (string.IsNullOrWhiteSpace(message))
                        {
                            continue;
                        }
                        if (message.ToLower() == "exit")
                        {
                            break;
                        }
                        serviceInstance.SendMessageToClients(message);
                    }

                    serviceHost.Close();
                }
                catch (TimeoutException timeProblem)
                {
                    Console.WriteLine(timeProblem.Message);
                    Console.ReadLine();
                }
                catch (CommunicationException commProblem)
                {
                    Console.WriteLine(commProblem.Message);
                    Console.ReadLine();
                }
            }
        }
Example #16
0
        public async Task And_callback_target_url_cannot_be_resolved_Then_callback_error_log_entry_inserted()
        {
            _mockHttp.When("https://localhost/callback").Throw(new HttpRequestException());

            var invitationId = Guid.NewGuid();
            var invitation   = new Invitation
            {
                Email       = "*****@*****.**",
                Id          = invitationId,
                SourceId    = "S0U4C31D",
                CallbackUri = new Uri("https://localhost/callback")
            };

            _loginContext.Invitations.Add(invitation);
            _loginContext.SaveChanges();

            var callbackService = new CallbackService(_mockHttp.ToHttpClient(), _loginContext);

            SystemTime.UtcNow = () => new DateTime(2019, 1, 1, 1, 1, 1);
            var logId = Guid.NewGuid();

            GuidGenerator.NewGuid = () => logId;

            await callbackService.Callback(invitation, "LOGINUSERID");

            var logEntry = _loginContext.UserLogs.Single();

            var expectedLogEntry = new UserLog
            {
                Id        = logId,
                DateTime  = SystemTime.UtcNow(),
                Email     = "*****@*****.**",
                Action    = "Client callback",
                Result    = "Callback error",
                ExtraData = JsonConvert.SerializeObject(new { CallbackUri = "https://localhost/callback", SourceId = "S0U4C31D",
                                                              UserId      = "LOGINUSERID",
                                                              Content     = "Exception of type 'System.Net.Http.HttpRequestException' was thrown." })
            };

            logEntry.Should().BeEquivalentTo(expectedLogEntry);
        }
Example #17
0
        public void CanCallDuplexChannelAsynchronously()
        {
            CallbackService callbackService = new CallbackService();

            IWindsorContainer localContainer = new WindsorContainer();

            localContainer.AddFacility <WcfFacility>();

            DuplexClientModel model = new DuplexClientModel
            {
                Endpoint = WcfEndpoint.ForContract <IServiceWithCallback>()
                           .BoundTo(new NetTcpBinding())
                           .At("net.tcp://localhost/ServiceWithCallback")
            }.Callback(callbackService);

            localContainer.Register(WcfClient.ForChannels(model));

            IServiceWithCallback proxy = localContainer.Resolve <IServiceWithCallback>();

            proxy.BeginWcfCall(p => p.DoSomething(21)).End();

            Assert.AreEqual(42, callbackService.ValueFromTheOtherSide);
        }
Example #18
0
        private RequestStatus sendRequest(string relativeUrl, HttpMethod httpMethod, Guid?previewToolId, string parameters)
        {
            Communication.Model.ConnectionResponse response;
            ErrorCodes?errorCode;
            string     errorMessage;

            var result = sendRequest(relativeUrl, httpMethod, previewToolId, parameters, out response, out errorCode, out errorMessage);

            if (result == HttpStatusCode.OK)
            {
                if (response != null)
                {
                    callbackService = new CallbackService(response.CallbackAddress, CallbackHandler, response.PingIntervalInSecs, onConnectionClosed);
                    callbackService.Start();
                }

                return(RequestStatus.Success());
            }
            else
            {
                return(RequestStatus.Failed(errorCode.Value, errorMessage));
            }
        }
 private void CallExecuteRemoteAsync(AsyncExecutionRequest request, Action <AsyncExecutionResponse> responseHandler)
 {
     CallbackService.RegisterPendingAsyncExecutionRequest(request, responseHandler);
     ExecuteRemoteAsync(request);
 }
 public void InvokeAsync(Action <AsyncExecutionResponse> responseHandler, string methodName, params object[] arguments)
 {
     InvokeAsync(CallbackService.CreateRequest(GetProxiedType(), methodName, arguments), responseHandler);
 }
        public void TestManyDumplexServersAndClientsCreatingsConcurencyOnNamedPipe()
        {
            var address = @"net.pipe://127.0.0.1/testpipename" + MethodBase.GetCurrentMethod().Name;
            var servers = 5;
            var clients = 5;
            var srv = new CallbackService();
            var callback = new CallbackServiceCallback();

            var tasks = new List<Task>();
            for (int i = 0; i < servers; i++)
            {
                var custom = address + i;
                var task = new Task(() =>
                    {
                        using (var server = new ServiceHost(srv, new Uri(address)))
                        {
                            server.AddServiceEndpoint(typeof(ICallbackService), new NetNamedPipeBinding { }, custom);
                            server.Open();
                            var requests = new List<Task>();
                            var channels = new ConcurrentBag<DuplexChannelFactory<ICallbackService>>();
                            for (int j = 0; j < clients; j++)
                            {

                                var childTask = new Task(() =>
                                {
                                    var channelFactory = new DuplexChannelFactory<ICallbackService>(new InstanceContext(callback), new NetNamedPipeBinding());
                                    var client = channelFactory.CreateChannel(new EndpointAddress(custom));
                                    client.Execute();
                                    channels.Add(channelFactory);
                                });
                                requests.Add(childTask);
                            }
                            foreach (var request in requests)
                            {
                                request.Start();
                            }
                            Task.WaitAll(requests.ToArray());

                            foreach (var factory in channels)
                            {
                                factory.Dispose();
                            }
                        }
                    });
                task.Start();
                tasks.Add(task);
            }
            while (callback.Count != servers * clients)
            {
                Thread.Sleep(10);
            }
            Task.WaitAll(tasks.ToArray());
        }
        private void btnStart_Click(object sender, EventArgs e)
        {
            List <string> tableNames = new List <string>();

            CallbackService callbackService = new CallbackService();

            callbackService.SetCallback(DoCallback);
            callbackService.Initialize(lvTables.CheckedItems.Count);

            tbProgress.Clear();

            foreach (ListViewItem item in lvTables.CheckedItems)
            {
                LocalTableItem tableItem = (LocalTableItem)item.Tag;

                if (tableItem.RemoteTable != null)
                {
                    tableNames.Add(tableItem.RemoteTable.TableName);
                }
            }


            bool changesMade = false;

            if (tableNames.Count > 0)
            {
                IList <BusinessEntity> businessEntities         = null;
                DataModelChanges       detectedChanges          = null;
                IList <BusinessEntity> existingBusinessEntities = null;

                try
                {
                    this.Cursor      = Cursors.WaitCursor;
                    btnClose.Enabled = false;

                    using (new SessionScope(MetaManagerServices.GetSessionFactory(), MetaManagerServices.GetDomainInterceptor(), true, FlushMode.Never, true))
                    {
                        businessEntities         = DataModelImporter.AnalyzeTables(currentSchema, tableNames, false);
                        existingBusinessEntities = modelService.GetAllDomainObjectsByApplicationId <BusinessEntity>(BackendApplication.Id);

                        AddToProgressText("\nAnalyzing fetched data compared to MetaManager database... ");

                        detectedChanges = DataModelImporter.CompareEntities(businessEntities, existingBusinessEntities);

                        AddToProgressText("done!\n");
                    }
                }
                catch (Exception ex)
                {
                    // Exception caught. Do nothing further!
                    MessageBox.Show(string.Format("Error caught when retreiving information from database!\r\nFix the problem and try again!\r\nError:\r\n\t{0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                finally
                {
                    this.Cursor      = Cursors.Default;
                    btnClose.Enabled = true;
                }

                if (detectedChanges != null &&
                    detectedChanges.Count > 0)
                {
                    AddToProgressText("\nShowing changes to user to decide what changes to apply...\n");

                    using (ShowDataModelChanges form = new ShowDataModelChanges())
                    {
                        form.BackendApplication  = BackendApplication;
                        form.FrontendApplication = FrontendApplication;

                        form.DetectedChanges = detectedChanges;

                        if (form.ShowDialog() == DialogResult.OK)
                        {
                            AddToProgressText("\nSaving new and changed properties and business entities... ");
                            // Update detected changes depending on user input from dialog.
                            DataModelImporter.CompareEntities(businessEntities, existingBusinessEntities, detectedChanges);

                            try
                            {
                                MetaManagerServices.Helpers.ApplicationHelper.UpdateBackendDataModel(detectedChanges, BackendApplication);
                                changesMade = true;
                            }
                            catch (ModelAggregatedException ex)
                            {
                                string mess = ex.Message;
                                string ids  = string.Empty;
                                foreach (string id in ((ModelAggregatedException)ex).Ids)
                                {
                                    ids += id + "\r\n";
                                }

                                Clipboard.SetText(ids);
                                mess += "\r\n\r\nThe Ids has been copied to the clipboard";
                                AddToProgressText("\r\n");
                                AddToProgressText("\r\n");
                                AddToProgressText(mess);
                                AddToProgressText("\r\n");
                            }
                            catch (Exception ex)
                            {
                                AddToProgressText("\n\n");
                                AddToProgressText(ex.Message);
                                AddToProgressText("\n");
                            }
                        }
                        else
                        {
                            AddToProgressText("\nUser canceled!\n");
                        }
                    }
                }
                else
                {
                    AddToProgressText("\nNo changes found!\n");
                }
            }

            if (changesMade)
            {
                AddToProgressText("\nFetching all tables to repopulate the list...\n");
                PopulateTables();
                AddToProgressText("Done!\n");
            }
        }
Example #23
0
 public void LevantarCallback()
 {
     Callback = new CallbackService(this, this, this);
     Callback.CorrerCallback();
 }