public LoginController(
     SignInService signInService,
     SignInInteraction signInInteraction,
     CredentialService credentialService)
 {
     _signInService = signInService;
     _signInInteraction = signInInteraction;
     _credentialService = credentialService;
 }
		void InitializeDefaultCredentialProvider ()
		{
			var credentialService = new CredentialService (
				GetCredentialProviders (),
				OnError,
				nonInteractive: false);

			NuGet.HttpClient.DefaultCredentialProvider = new CredentialServiceAdapter (credentialService);

			HttpHandlerResourceV3Extensions.InitializeHttpHandlerResourceV3 (credentialService);
		}
		public static void InitializeHttpHandlerResourceV3 (CredentialService credentialService)
		{
			// Set up proxy handling for v3 sources.
			// We need to sync the v2 proxy cache and v3 proxy cache so that the user will not
			// get prompted twice for the same authenticated proxy.
			var v2ProxyCache = ProxyCache.Instance;

			HttpHandlerResourceV3.CredentialService = credentialService;

			HttpHandlerResourceV3.CredentialsSuccessfullyUsed = (uri, credentials) => {
				NuGet.CredentialStore.Instance.Add (uri, credentials);
			};
		}
Example #4
0
        public ActionResult Login(string username, string password)
        {
            var credential = CredentialService.QueryCredentialByUsernameByPassword(username, password);

            if (credential == null)
            {
                return(Json(new { state = "error", message = "Invalid username and password combination" }, JsonRequestBehavior.AllowGet));
            }
            var appUserId = (Guid)credential.FirstOrDefault(x => x.Key == "AppUserId").Value;

            if (appUserId == Guid.Empty)
            {
                return(Json(new { state = "error", message = "Invalid username and password combination" }, JsonRequestBehavior.AllowGet));
            }

            var appUser = AppUserService.QueryAppUserById(appUserId);

            AccountService.SetCookie(Response, appUser);

            return(Json(new { state = "success", appUser = appUser }, JsonRequestBehavior.AllowGet));
        }
        public ReturnObject registerUser(int id, String email, String password, String name)
        {
            CredentialService credentialService = new CredentialService();

            if (credentialService.credentialsValid(name, email, password))
            {
                if (userRepository.findByEmail(email) == null)
                {
                    userRepository.createHistory(id);
                    return(userRepository.create(id, name, email, password));
                }
                else
                {
                    return(new ReturnObject(false, "User already exists."));
                }
            }
            else
            {
                return(new ReturnObject(false, "Credentials are invalid."));
            }
        }
Example #6
0
        public void Reuse_last_used_credentials()
        {
            // Arrange
            var cache = new HttpCredentialCache
            {
                new BasicCredentials(new Uri("http://example.org"), username: "", password: "")
            };

            var authService = new CredentialService(cache);
            var request     = new HttpRequestMessage()
            {
                RequestUri = new Uri("http://example.org")
            };

            authService.CreateAuthenticationHeaderFromChallenge(request, new[] { new AuthenticationHeaderValue("basic", "") });

            // Act
            var header = authService.CreateAuthenticationHeaderFromRequest(request);

            // Assert
            Assert.Equal("basic", header.Scheme);
        }
        /// <summary>
        /// Set default credential provider for the HttpClient, which is used by V2 sources.
        /// Also set up authenticated proxy handling for V3 sources.
        /// </summary>
        protected void SetDefaultCredentialProvider()
        {
            var credentialService = new CredentialService(GetCredentialProviders(), Console.WriteError, NonInteractive);

            HttpClient.DefaultCredentialProvider = new CredentialServiceAdapter(credentialService);

            NuGet.Protocol.Core.v3.HttpHandlerResourceV3.CredentialSerivce = credentialService;

            NuGet.Protocol.Core.v3.HttpHandlerResourceV3.PromptForCredentialsAsync =
                async(uri, type, message, cancellationToken) => await credentialService.GetCredentialsAsync(
                    uri,
                    proxy : null,
                    type : type,
                    message : message,
                    cancellationToken : cancellationToken);

            NuGet.Protocol.Core.v3.HttpHandlerResourceV3.CredentialsSuccessfullyUsed = (uri, credentials) =>
            {
                NuGet.CredentialStore.Instance.Add(uri, credentials);
                NuGet.Configuration.CredentialStore.Instance.Add(uri, credentials);
            };
        }
Example #8
0
        public static void InitializeHttpHandlerResourceV3(CredentialService credentialService)
        {
            // Set up proxy handling for v3 sources.
            // We need to sync the v2 proxy cache and v3 proxy cache so that the user will not
            // get prompted twice for the same authenticated proxy.
            var v2ProxyCache = ProxyCache.Instance;

            NuGet.Protocol.Core.v3.HttpHandlerResourceV3.PromptForProxyCredentials = async(uri, proxy, cancellationToken) => {
                var v2Credentials = v2ProxyCache?.GetProxy(uri)?.Credentials;
                if (v2Credentials != null && proxy.Credentials != v2Credentials)
                {
                    // if cached v2 credentials have not been used, try using it first.
                    return(v2Credentials);
                }

                return(await credentialService
                       .GetCredentials(uri, proxy, isProxy : true, cancellationToken : cancellationToken));
            };

            NuGet.Protocol.Core.v3.HttpHandlerResourceV3.ProxyPassed = proxy => {
                // add the proxy to v2 proxy cache.
                v2ProxyCache?.Add(proxy);
            };

            NuGet.Protocol.Core.v3.HttpHandlerResourceV3.PromptForCredentials = async(uri, cancellationToken) => {
                // Get the proxy for this URI so we can pass it to the credentialService methods
                // this lets them use the proxy if they have to hit the network.
                var proxyCache = ProxyCache.Instance;
                var proxy      = proxyCache?.GetProxy(uri);

                return(await credentialService
                       .GetCredentials(uri, proxy : proxy, isProxy : false, cancellationToken : cancellationToken));
            };

            NuGet.Protocol.Core.v3.HttpHandlerResourceV3.CredentialsSuccessfullyUsed = (uri, credentials) => {
                NuGet.CredentialStore.Instance.Add(uri, credentials);
                NuGet.Configuration.CredentialStore.Instance.Add(uri, credentials);
            };
        }
        public CredentialService.Account[] checkAccountsForTemplatePermissions(CredentialService.LoginResult loginResult)
        {
            List<CredentialService.Account> accountsWithTemplatesPermissions = new List<InsuranceCo.CredentialService.Account>();
            Signing.AccountCredentials creds = base.GetAPICredentials();
            Signing.DocuSignWeb.APIServiceSoap api = Signing.Envelope.CreateApiProxy(creds);

            Signing.DocuSignWeb.RequestTemplatesResponse response;
            Signing.DocuSignWeb.RequestTemplatesRequest request = new Signing.DocuSignWeb.RequestTemplatesRequest();

            foreach(CredentialService.Account account in loginResult.Accounts){
                request.AccountID = account.AccountID;
                request.IncludeAdvancedTemplates = true;
                try{
                    response = api.RequestTemplates(request);
                    accountsWithTemplatesPermissions.Add(account);
                }
                catch(Exception excp){
                    // nada
                }

            }
            return accountsWithTemplatesPermissions.ToArray();
        }
Example #10
0
        private async void TryToPerformAutoLogin()
        {
            CredentialService CService = MvvmNanoIoC.Resolve <CredentialService>();

            try
            {
                if (CService.DoCredentialsExist())
                {
                    CheckAuthentication auth = new CheckAuthentication();
                    auth.authentication          = new Authentication();
                    auth.authentication.password = CService.Password;
                    auth.authentication.userName = CService.UserName;



                    bool result = await IsValidAuthentication(auth);

                    if (result)
                    {
                        MvvmNanoIoC.RegisterAsSingleton <Authentication>(auth.authentication);
                        SetUpMainPage <MasterDetailViewModel>();
                    }
                    else
                    {
                        SetUpMainPage <LoginViewModel>();
                    }
                }
                else
                {
                    SetUpMainPage <LoginViewModel>();
                }
            }
            catch (Exception)
            {
                SetUpMainPage <LoginViewModel>();
            }
        }
		public static void InitializeHttpHandlerResourceV3 (CredentialService credentialService)
		{
			// Set up proxy handling for v3 sources.
			// We need to sync the v2 proxy cache and v3 proxy cache so that the user will not
			// get prompted twice for the same authenticated proxy.
			var v2ProxyCache = ProxyCache.Instance;
			NuGet.Protocol.Core.v3.HttpHandlerResourceV3.PromptForProxyCredentials = async (uri, proxy, cancellationToken) => {
				var v2Credentials = v2ProxyCache?.GetProxy (uri)?.Credentials;
				if (v2Credentials != null && proxy.Credentials != v2Credentials) {
					// if cached v2 credentials have not been used, try using it first.
					return v2Credentials;
				}

				return await credentialService
					.GetCredentials (uri, proxy, isProxy: true, cancellationToken: cancellationToken);
			};

			NuGet.Protocol.Core.v3.HttpHandlerResourceV3.ProxyPassed = proxy => {
				// add the proxy to v2 proxy cache.
				v2ProxyCache?.Add (proxy);
			};

			NuGet.Protocol.Core.v3.HttpHandlerResourceV3.PromptForCredentials = async (uri, cancellationToken) => {
				// Get the proxy for this URI so we can pass it to the credentialService methods
				// this lets them use the proxy if they have to hit the network.
				var proxyCache = ProxyCache.Instance;
				var proxy = proxyCache?.GetProxy (uri);

				return await credentialService
					.GetCredentials (uri, proxy: proxy, isProxy: false, cancellationToken: cancellationToken);
			};

			NuGet.Protocol.Core.v3.HttpHandlerResourceV3.CredentialsSuccessfullyUsed = (uri, credentials) => {
				NuGet.CredentialStore.Instance.Add (uri, credentials);
				NuGet.Configuration.CredentialStore.Instance.Add (uri, credentials);
			};
		}
Example #12
0
        public ActionResult Create()
        {
            List <CredentialItem> lst        = new List <CredentialItem>();
            CredentialService     objService = new CredentialService();
            int cid = 0;

            if (Session["CompID"] != null)
            {
                cid = Convert.ToInt32(Session["CompID"].ToString());
            }
            lst = objService.getCredentialData(cid);
            CredentialItem objModel = new CredentialItem();

            objModel.ListCredential = new List <CredentialItem>();
            objModel.ListCredential.AddRange(lst);
            ViewBag.Menuid = Request.QueryString["menuId"];

            SponsorService     objService1 = new SponsorService();
            List <CompanyItem> lstCompany  = new List <CompanyItem>();

            lstCompany           = objService1.GetCompany();
            objModel.ListCompany = new List <CompanyItem>();
            objModel.ListCompany.AddRange(lstCompany);

            VehicleMasterService objVehicle = new VehicleMasterService();

            #region Bind DropDown Branch
            List <BranchItem> lstBranch = new List <BranchItem>();
            lstBranch           = objVehicle.GetBranch();
            objModel.ListBranch = new List <BranchItem>();
            objModel.ListBranch.AddRange(lstBranch);

            #endregion

            return(View(objModel));
        }
        public async Task CanRegisterNewUser()
        {
            var vm = await GetSut();

            NavigationAdapter.Should().BeDisplaying <AddUserViewModel>();

            vm.AddNewUserCommand.Should().BeDisabled();

            vm.EmailAddress    = "*****@*****.**";
            vm.Firstname       = "John";
            vm.Lastname        = "Doe";
            vm.Password        = "******";
            vm.ConfirmPassword = vm.Password;

            vm.AddNewUserCommand.Should().BeEnabled();

            vm.AddNewUserCommand.Click();

            vm.AddNewUserCommand.Should().BeDisabled();

            CredentialService.Should().HaveRegistered("John", "Doe");

            NavigationAdapter.Should().NotBeDisplaying <AddUserViewModel>();
        }
        public async Task GetCredentialProvidersExecutedOnlyOnce()
        {
            var counter = new CallCounter();
            var service = new CredentialService(new AsyncLazy <IEnumerable <ICredentialProvider> >(() => counter.GetProviders()), nonInteractive: true, handlesDefaultCredentials: true);

            var uri1 = new Uri("http://uri1");

            // Act
            var result1 = await service.GetCredentialsAsync(
                uri1,
                proxy : null,
                type : CredentialRequestType.Unauthorized,
                message : null,
                cancellationToken : CancellationToken.None);

            var result2 = await service.GetCredentialsAsync(
                uri1,
                proxy : null,
                type : CredentialRequestType.Unauthorized,
                message : null,
                cancellationToken : CancellationToken.None);

            Assert.Equal(1, counter.CallCount);
        }
Example #15
0
 private static void Main(string[] args)
 {
     var test = CredentialService.Encrypt("bbU9tG!kH");
 }
        public async Task GetCredentials_TriesAllProviders_EvenWhenSameType()
        {
            // Arrange
            var mockProvider1 = new Mock <ICredentialProvider>();

            mockProvider1
            .Setup(x => x.GetAsync(
                       It.IsAny <Uri>(),
                       It.IsAny <IWebProxy>(),
                       It.IsAny <CredentialRequestType>(),
                       It.IsAny <string>(),
                       It.IsAny <bool>(),
                       It.IsAny <bool>(),
                       It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new CredentialResponse(CredentialStatus.ProviderNotApplicable)));
            mockProvider1.Setup(x => x.Id).Returns("1");
            var mockProvider2 = new Mock <ICredentialProvider>();

            mockProvider2
            .Setup(x => x.GetAsync(
                       It.IsAny <Uri>(),
                       It.IsAny <IWebProxy>(),
                       It.IsAny <CredentialRequestType>(),
                       It.IsAny <string>(),
                       It.IsAny <bool>(),
                       It.IsAny <bool>(),
                       It.IsAny <CancellationToken>()))
            .Returns(
                Task.FromResult(new CredentialResponse(CredentialStatus.ProviderNotApplicable)));
            mockProvider2.Setup(x => x.Id).Returns("2");
            var service = new CredentialService(
                new[] { mockProvider1.Object, mockProvider2.Object },
                TestableErrorWriter,
                nonInteractive: false);
            var uri1 = new Uri("http://host/some/path");

            // Act
            var result1 = await service.GetCredentialsAsync(
                uri1,
                proxy : null,
                type : CredentialRequestType.Unauthorized,
                message : null,
                cancellationToken : CancellationToken.None);

            // Assert
            Assert.Null(result1);
            mockProvider1.Verify(
                x => x.GetAsync(
                    It.IsAny <Uri>(),
                    It.IsAny <IWebProxy>(),
                    It.IsAny <CredentialRequestType>(),
                    It.IsAny <string>(),
                    It.IsAny <bool>(),
                    It.IsAny <bool>(),
                    It.IsAny <CancellationToken>()),
                Times.Once);
            mockProvider2.Verify(
                x => x.GetAsync(
                    It.IsAny <Uri>(),
                    It.IsAny <IWebProxy>(),
                    It.IsAny <CredentialRequestType>(),
                    It.IsAny <string>(),
                    It.IsAny <bool>(),
                    It.IsAny <bool>(),
                    It.IsAny <CancellationToken>()),
                Times.Once);
        }
Example #17
0
 /// <summary>
 /// Constructor called once for every test
 /// </summary>
 public CredentialServiceTests()
 {
     credStore = CredentialService.GetStoreForOS(Config);
     service   = new CredentialService(credStore, Config);
     DeleteDefaultCreds();
 }
Example #18
0
 public PersonController(PersonServices _personServices, CredentialService _credentialService)
 {
     personServices    = _personServices;
     credentialService = _credentialService;
 }
        protected override void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            if (_isWorkerExecuted)
            {
                return;
            }

            // set the flag the this bw_DoWork has already called
            _isWorkerExecuted = true;
            var counter    = 0;
            var service    = new CredentialService();
            var credential = (eBayCredentialDto)service.GetCredential(CredentialType.EBAY, _systemJob.SupportiveParameters);

            _itemFeeds = readProductItemFeeds(_systemJob.Parameters);

            // init the eBay API
            RequestHelper.SetCredentials(credential);

            // init the context
            var context = new ApiContext();

            context.ApiCredential    = RequestHelper.ApiCredential;
            context.SoapApiServerUrl = RequestHelper.ServiceUrl;

            setTotalItemsProcessed(_itemFeeds.Count);
            _logger.LogInfo(LogEntryType.eBayEndListing, string.Format("{0} items for eBay Product ReListing has started...", _itemFeeds.Count));

            // iterate and submit end item feed to the eBay
            for (var i = 0; i < _itemFeeds.Count; i++)
            {
                var percentage = (((double)i + 1) / _itemFeeds.Count) * 100.00;
                Console.WriteLine(string.Format("{0:#0.00}% Sending feed 1 x 1 for eBay Product ReListing...", percentage));

                // report the progress
                counter++;
                _bw.ReportProgress(counter);
                var itemFeed = _itemFeeds[i];

                try
                {
                    // get the product detailf or the product relisting
                    var productFeed = _service.GetProductPostFeedByEisSku(_itemFeeds[i].EisSKU);

                    if (string.IsNullOrEmpty(itemFeed.ItemId))
                    {
                        itemFeed.Status  = Status.NOT_PROCESSED;
                        itemFeed.Message = "ItemId is NULL or empty";
                        continue;
                    }

                    // build item type
                    var itemType = RequestHelper.CreateItemType(productFeed, credential.eBayDescriptionTemplate);
                    itemType.ItemID = productFeed.eBayProductFeed.ItemId;

                    // submit the item for relisting
                    var apiCall = new RelistFixedPriceItemCall(context);
                    apiCall.Item = itemType;
                    apiCall.Execute();

                    // update the product ItemId
                    _repo.UpdateReListedeBayProduct(itemFeed.EisSKU, apiCall.ItemID);

                    itemFeed.Status  = Status.SUCCESS;
                    itemFeed.Message = string.Format("{0} - New relisted ItemId: {1}", apiCall.ApiResponse.Ack, apiCall.ItemID);

                    // sleep for 1 second - throttle limit
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error in submitting eBay Product ReListing {0}. Error Message: {1}", _itemFeeds[i].EisSKU, EisHelper.GetExceptionMessage(ex));
                    itemFeed.Status  = Status.FAILED;
                    itemFeed.Message = string.Format("Error in sending relisting feed. Message: {0}", EisHelper.GetExceptionMessage(ex));
                }
            }

            _logger.LogInfo(LogEntryType.eBayEndListing, string.Format("{0} items for eBay EndListing has finished!", _itemFeeds.Count));
        }
Example #20
0
 private void DeleteUsers()
 {
     CredentialService.DeleteAll();
     NotifyPropertyChanged(nameof(Credentials));
 }
Example #21
0
        private async Task DeleteCredential(Guid id)
        {
            await CredentialService.RemoveCredentialAsync(id);

            SavedCredentials = await CredentialService.GetCredentialsAsync();
        }
Example #22
0
        public void Reuse_last_used_credentials()
        {
            // Arrange
            var cache = new HttpCredentialCache
            {
                new BasicCredentials(new Uri("http://example.org"), username: "", password: "")
            };

            var authService = new CredentialService(cache);
            var request = new HttpRequestMessage(){RequestUri = new Uri("http://example.org")};
            authService.CreateAuthenticationHeaderFromChallenge(request, new[] { new AuthenticationHeaderValue("basic", "") });

            // Act
            var header = authService.CreateAuthenticationHeaderFromRequest(request);

            // Assert
            Assert.Equal("basic", header.Scheme);

        }
Example #23
0
 public MonitoringController(StvContext db)
 {
     _db = db;
     credentialService = new CredentialService(_db);
     settingService    = new SettingService(_db);
 }
Example #24
0
 public void Setup()
 {
     CredentialServiceObject = new CredentialService();
 }
Example #25
0
 public CredentialController(StvContext db)
 {
     _db            = db;
     service        = new CredentialService(_db);
     settingService = new SettingService(_db);
 }
Example #26
0
 protected override async Task OnInitializedAsync()
 {
     Model          = new StandUpModel();
     HasCredentials = (await CredentialService.GetCredentialsAsync()).Any();
     GenerateLabel  = "Generate!";
 }
 public void SetUp()
 {
     CryptoProviderMock = new Mock <ICryptoProvider>();
     CredentialService  = new CredentialService(CryptoProviderMock.Object);
 }
        public void GenerateData()
        {
            var optionsBuilder = new DbContextOptionsBuilder <StvContext>();

            optionsBuilder.UseSqlServer(@"Data Source=.\SQL2014;Database=stvsystemDB;Integrated Security=True;Persist Security Info=False;Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True", null);
            StvContext db = new StvContext(optionsBuilder.Options);

            db.Database.ExecuteSqlCommand("delete from dbo.setting");
            db.Database.ExecuteSqlCommand("delete from dbo.credential");
            db.Database.ExecuteSqlCommand("delete from dbo.result");
            db.Database.ExecuteSqlCommand("delete from dbo.candidate");


            db.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT[dbo].[Candidate] ON
INSERT[dbo].[Candidate] ([CandidateID], [FirstName], [LastName], [MiddleName], [BirthDate], [GenderID], [CourtID], [SpecializationID]) VALUES(1, N'Թեկնածու 1', N'Ազգանուն', N'Հայրանուն', NULL, 1, 1, 1)
INSERT[dbo].[Candidate] ([CandidateID], [FirstName], [LastName], [MiddleName], [BirthDate], [GenderID], [CourtID], [SpecializationID]) VALUES(2, N'Թեկնածու 2', N'Ազգանուն', N'Հայրանուն', NULL, 1, 2, 2)
INSERT[dbo].[Candidate] ([CandidateID], [FirstName], [LastName], [MiddleName], [BirthDate], [GenderID], [CourtID], [SpecializationID]) VALUES(3, N'Թեկնածու 3', N'Ազգանուն', N'Հայրանուն', NULL, 2, 3, 3)
INSERT[dbo].[Candidate] ([CandidateID], [FirstName], [LastName], [MiddleName], [BirthDate], [GenderID], [CourtID], [SpecializationID]) VALUES(4, N'Թեկնածու 4', N'Ազգանուն', N'Հայրանուն', NULL, 1, 4, 1)
INSERT[dbo].[Candidate] ([CandidateID], [FirstName], [LastName], [MiddleName], [BirthDate], [GenderID], [CourtID], [SpecializationID]) VALUES(5, N'Թեկնածու 5', N'Ազգանուն', N'Հայրանուն', NULL, 1, 5, 2)
SET IDENTITY_INSERT[dbo].[Candidate] OFF
SET IDENTITY_INSERT[dbo].[Setting] ON
INSERT[dbo].[Setting]([SettingID], [SelectionName], [SelectionDate], [StartTime], [FinishTime], [SelectionCount], [ParticipantCount], [SelectionStatus]) VALUES(1, N'Թեսթային ընտրություն', '2018-01-01', '08:00', '20:00', 3, 10, 1)
SET IDENTITY_INSERT[dbo].[Setting] OFF");

            var setting          = db.Settings.Single();
            int participantCount = 30;
            /////////
            CredentialService credentialService = new CredentialService(db);
            var dictionary = credentialService.GenerateCredentials((int)participantCount);

            for (var i = 0; i < participantCount; i++)
            {
                Credential credential = new Credential
                {
                    SettingID = setting.SettingID,
                    Password  = dictionary.ElementAt(i).Key,
                    Status    = CredentialStatus.NoSelection,
                    Setting   = setting
                };
                db.Credentials.Add(credential);
            }
            db.SaveChanges();
            //////////



            int[]  cycleCount  = { 1, 2, 3, 4, 5 };
            Random cycleRandom = new Random();


            var    candidates      = (from p in db.Candidates select p.CandidateID).ToArray();
            Random candidateRandom = new Random();

            foreach (Credential credential in db.Credentials.ToList())
            {
                int credentialCycleCount = cycleCount[cycleRandom.Next(0, cycleCount.Length)];
                int candidateID          = 0;

                for (int i = 1; i <= credentialCycleCount; i++)
                {
                    bool isRecordExists = true;
                    while (isRecordExists)
                    {
                        candidateID = candidates[candidateRandom.Next(0, candidates.Length)];
                        var q = from p in db.Results where p.CredentialID == credential.CredentialID && p.CandidateID == candidateID select p;
                        if (q.Count() > 0)
                        {
                            isRecordExists = true;
                        }
                        else
                        {
                            isRecordExists = false;
                        }
                    }


                    Result result = new Result
                    {
                        CandidateID    = candidateID,
                        CandidateIndex = i,
                        CredentialID   = credential.CredentialID,
                        Status         = ResultStatus.Permanent
                    };
                    db.Results.Add(result);

                    db.SaveChanges();
                }
            }
        }
Example #29
0
 public static void InitializeHttpHandlerResourceV3(CredentialService credentialService)
 {
     HttpHandlerResourceV3.CredentialService = credentialService;
 }
        protected override void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            if (_isWorkerExecuted)
            {
                return;
            }

            // set the flag the this bw_DoWork has already called
            _isWorkerExecuted = true;
            var counter    = 0;
            var service    = new CredentialService();
            var credential = (eBayCredentialDto)service.GetCredential(CredentialType.EBAY, _systemJob.SupportiveParameters);

            _itemFeeds = readProductItemFeeds(_systemJob.Parameters);

            // init the eBay API
            RequestHelper.SetCredentials(credential);

            // init the context
            var context = new ApiContext();

            context.ApiCredential    = RequestHelper.ApiCredential;
            context.SoapApiServerUrl = RequestHelper.ServiceUrl;

            setTotalItemsProcessed(_itemFeeds.Count);
            _logger.LogInfo(LogEntryType.eBayEndListing, string.Format("{0} items for eBay EndListing has started...", _itemFeeds.Count));

            // iterate and submit end item feed to the eBay
            for (var i = 0; i < _itemFeeds.Count; i++)
            {
                var itemFeed   = _itemFeeds[i];
                var percentage = (((double)i + 1) / _itemFeeds.Count) * 100.00;
                Console.WriteLine(string.Format("{0:#0.00}% Sending feed 1 x 1 for eBay Product EndItem...", percentage));

                // report the progress
                counter++;
                _bw.ReportProgress(counter);

                try
                {
                    if (string.IsNullOrEmpty(itemFeed.ItemId))
                    {
                        itemFeed.Status  = Status.NOT_PROCESSED;
                        itemFeed.Message = "ItemId is NULL or empty";
                        continue;
                    }

                    // create the end item request
                    var apiCall = new EndItemCall(context);
                    apiCall.EndItem(itemFeed.ItemId, EndReasonCodeType.NotAvailable);

                    // let's set the eBay product ItemId to null
                    _repo.UpdateeBayEndedItem(itemFeed.EisSKU);
                    itemFeed.Status = Status.SUCCESS;

                    // sleep for 1 second - throttle limit
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error in submitting eBay product end listing {0}. Error Message: {1}", _itemFeeds[i].EisSKU, EisHelper.GetExceptionMessage(ex));
                    itemFeed.Status  = Status.FAILED;
                    itemFeed.Message = string.Format("Error in sending endlisting feed. Message: {0}", EisHelper.GetExceptionMessage(ex));
                }
            }

            _logger.LogInfo(LogEntryType.eBayEndListing, string.Format("{0} items for eBay EndListing has finished!", _itemFeeds.Count));
        }
Example #31
0
        public async Task Gateway_key_with_wrong_host()
        {
            // Arrange
            var cache = new HttpCredentialCache
            {
                new GatewayKey(new Uri("http://example.org/foo"), "gateway-key","key value goes here")
            };

            var authService = new CredentialService(cache);
            var request = new HttpRequestMessage() { RequestUri = new Uri("http://example.org") };
            var invoker = new HttpMessageInvoker(new AuthMessageHandler(new DummyHttpHandler(), authService));

            // Act
            var response = await invoker.SendAsync(request, new System.Threading.CancellationToken());

            // Assert

            Assert.False(request.Headers.Contains("gateway-key"));
            //Assert.Equal("key value goes here", request.Headers.GetValues("gateway-key").First());
        }
Example #32
0
 protected override async Task OnInitializedAsync()
 {
     SavedCredentials = await CredentialService.GetCredentialsAsync();
 }