Ejemplo n.º 1
0
        private IEnumerable<MarketCategory> GetMarketCategories()
        {
            if (_marketCategoriesCache == null)
            {
                var client = new RestClient("http://network.adsmarket.com/site/API2");

                client.DefaultParameters.Add(new Parameter { Name = "userid", Value = ConfigurationManager.AppSettings["SuperMarketApiUserId"], Type = ParameterType.QueryString });
                client.DefaultParameters.Add(new Parameter { Name = "uid", Value = ConfigurationManager.AppSettings["SuperMarketApiUserId"], Type = ParameterType.QueryString });
                client.DefaultParameters.Add(new Parameter { Name = "key", Value = ConfigurationManager.AppSettings["SuperMarketApiKey"], Type = ParameterType.QueryString });

                var request = new RestRequest();
                request.AddParameter("fn", "getcategories");

                var response = client.Execute<CategoryList>(request);

                if (response == null)
                {
                    throw new Exception(String.Format("Failed to communicate with MarketApi: {0} Response: {1}", client.BuildUri(request), response.Content));
                }
                if (response.Data == null)
                {
                    throw new Exception(String.Format("Failed to communicate with MarketApi: {0} No response", client.BuildUri(request)));
                }
                var cats = response.Data.Categories.ToArray();

                _marketCategoriesCache = cats.Select(c => new MarketCategory() { Id = c.CategoryId, Name = c.CategoryTitle });
            }

            return _marketCategoriesCache;
        }
        private void LogRequest(RestClient restClient, IRestRequest request, IRestResponse response, long durationMs)
        {
            var requestToLog = new
            {
                resource = request.Resource,
                // Parameters are custom anonymous objects in order to have the parameter type as a nice string
                // otherwise it will just show the enum value
                parameters = request.Parameters.Select(parameter => new
                {
                    name = parameter.Name,
                    value = parameter.Value,
                    type = parameter.Type.ToString()
                }),
                // ToString() here to have the method as a nice string otherwise it will just show the enum value
                method = request.Method.ToString(),
                // This will generate the actual Uri used in the request
                uri = restClient.BuildUri(request),
            };

            var responseToLog = new
            {
                statusCode = response.StatusCode,
                content = response.Content,
                headers = response.Headers,
                // The Uri that actually responded (could be different from the requestUri if a redirection occurred)
                responseUri = response.ResponseUri,
                errorMessage = response.ErrorMessage,
            };

            Trace.Write(string.Format("Request completed in {0} ms, Request: {1}, Response: {2}",
                    durationMs,
                    JsonConvert.SerializeObject(requestToLog),
                    JsonConvert.SerializeObject(responseToLog)));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Use this method first to retrieve the url to redirect the user to to allow the url.
        /// Once they are done there, Fitbit will redirect them back to the predetermined completion URL
        /// </summary>
        /// <returns></returns>
        public string GetAuthUrlToken()
        {
			var baseUrl = "https://api.fitbit.com";
			var client = new RestClient(baseUrl);
			client.Authenticator = OAuth1Authenticator.ForRequestToken(this.ConsumerKey, this.ConsumerSecret);
            
            var request = new RestRequest("oauth/request_token", Method.POST);
			var response = client.Execute(request);


			//Assert.NotNull(response);
			//Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            if(response.StatusCode != System.Net.HttpStatusCode.OK)
                throw new Exception("Request Token Step Failed");

			var qs = HttpUtility.ParseQueryString(response.Content);
			var oauth_token = qs["oauth_token"];
			var oauth_token_secret = qs["oauth_token_secret"];

			//Assert.NotNull(oauth_token);
			//Assert.NotNull(oauth_token_secret);

			request = new RestRequest("oauth/authorize");
			request.AddParameter("oauth_token", oauth_token);
			var url = client.BuildUri(request).ToString();
			//Process.Start(url);

            return url;
        }
Ejemplo n.º 4
0
		private string GenerateAuthUrlToken(bool forceLogoutBeforeAuth)
		{
			var baseUrl = "https://api.fitbit.com";
			var client = new RestClient(baseUrl);
			client.Authenticator = OAuth1Authenticator.ForRequestToken(this.ConsumerKey, this.ConsumerSecret);

			var request = new RestRequest("oauth/request_token", Method.POST);
			var response = client.Execute(request);

			var qs = HttpUtility.ParseQueryString(response.Content);
			RequestToken = qs["oauth_token"];
			RequestTokenSecret = qs["oauth_token_secret"];

			if (response.StatusCode != System.Net.HttpStatusCode.OK)
				throw new Exception("Request Token Step Failed");

			if(forceLogoutBeforeAuth)
				request = new RestRequest("oauth/logout_and_authorize"); //this url will force the user to type in username and password
			else
				request = new RestRequest("oauth/authorize");           //this url will show allow/deny if a user is currently logged in
			request.AddParameter("oauth_token", RequestToken);
			var url = client.BuildUri(request).ToString();

			return url;
		}
Ejemplo n.º 5
0
        public void Can_Authenticate_With_OAuth()
        {
            const string consumerKey = "HEGlGLuqfR1Aa8CwJNB0sw";
            const string consumerSecret = "D4UC98WMZbPaLztm47b7TwktQBiPhqpqJUd99hPhqw";

            var baseUrl = "http://api.twitter.com";
            var client = new RestClient(baseUrl);
            client.Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret);
            // Token anfragen für Authorisierung
            var request = new RestRequest("oauth/request_token", Method.POST);
            var response = client.Execute(request);

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            var qs = HttpUtility.ParseQueryString(response.Content);
            var oauth_token = qs["oauth_token"];
            var oauth_token_secret = qs["oauth_token_secret"];
            Assert.IsNotNull(oauth_token);
            Assert.IsNotNull(oauth_token_secret);

            // Authorisierung starten
            request = new RestRequest("oauth/authorize");
            request.AddParameter("oauth_token", oauth_token);
            var url = client.BuildUri(request).ToString();
            Process.Start(url);

            // mit Authorisierungs-PIN ein Zugriffs-Token anfordern
            var verifier = "8083248"; // <-- Breakpoint here (set verifier in debugger)
            request = new RestRequest("oauth/access_token", Method.POST);
            client.Authenticator = OAuth1Authenticator.ForAccessToken(
                consumerKey, consumerSecret, oauth_token, oauth_token_secret, verifier
                );
            response = client.Execute(request);

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            qs = HttpUtility.ParseQueryString(response.Content);
            oauth_token = qs["oauth_token"];
            oauth_token_secret = qs["oauth_token_secret"];
            Assert.IsNotNull(oauth_token);
            Assert.IsNotNull(oauth_token_secret);

            request = new RestRequest("1.1/statuses/user_timeline.json");
            request.AddParameter("count", 30);
            client.Authenticator = OAuth1Authenticator.ForProtectedResource(
                consumerKey, consumerSecret, oauth_token, oauth_token_secret
                );

            var typedResponse = client.Execute<List<Tweet>>(request);
            var tweets = typedResponse.Data;

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            Assert.IsNotNull(tweets);
            Assert.IsTrue(tweets.Count > 0);
        }
Ejemplo n.º 6
0
 public string GenerateAuthUrlFromRequestToken(RequestToken token)
 {
     RestRequest request = null;
     request = new RestRequest(token.Token + "/");
     var authclient = new RestClient(AuthorizeUrl);
     var url = authclient.BuildUri(request).ToString();
     return url;
 }
Ejemplo n.º 7
0
        public void TestPort_AllowsChangingPort_InCaseOfConflictInTheMachineRunningTests()
        {
            var client = new RestClient(BaseUrl.ToString());
            var request = new RestRequest("/echo", Method.GET);

            var response = client.Execute(request);
            var uri = client.BuildUri(response.Request);

            Assert.That(uri.Port, Is.EqualTo(49160));
        }
		public void HomePage_WhenCalled_ShouldContainHelloWorld()
		{
			// arrange
			Setup();
			// assert
			var client = new RestClient(BaseUri);
			var request = new RestRequest("", Method.GET);
			_log.Info("Placing request to " + client.BuildUri(request));
			IRestResponse executeTaskAsync = client.Execute(request);
			Console.Out.WriteLine("executeTaskAsync.Content:" + executeTaskAsync.Content);
			executeTaskAsync.Content.Should().Contain("Hello World!");
		}
        public void Authenticate_UrlParameters_ShouldSucceed( )
        {
            const string ROUTE = "/d2l/api/{foo}/{bar}";

            var client = new RestClient( BASE_ROUTE );
            var request = new RestRequest( ROUTE );
            request.AddUrlSegment( "foo", "abc" );
            request.AddUrlSegment( "bar", "xyz" );

            m_authenticator.Authenticate( client, request );

            string expectedUrl = GenerateExepctedUrl( "/d2l/api/abc/xyz" );
            Assert.AreEqual( expectedUrl, client.BuildUri(request).PathAndQuery );
        }
        public void Authenticate_UrlAndQueryParameters_ShouldSucceed( )
        {
            const string ROUTE = "/d2l/api/lp/{version}/users/";
            const string VERSION = "1.4";

            var client = new RestClient( BASE_ROUTE );
            var request = new RestRequest( ROUTE );
            request.AddUrlSegment( "version", VERSION );
            request.AddParameter( "userName", "user name" );

            m_authenticator.Authenticate( client, request );

            string expectedUrl = GenerateExepctedUrl( ROUTE.Replace( "{version}", VERSION ) + "?userName=user%20name" );

            Assert.AreEqual( expectedUrl, client.BuildUri(request).PathAndQuery );
        }
Ejemplo n.º 11
0
        private static void Main(string[] args)
        {
            using (var output = new StreamWriter(@"..\..\results.txt")) {
                foreach (var ep in endpoints) {
                    var url = String.Format("http://restival.local/api.{0}", ep);
                    var client = new RestClient(url);
                    var request = new RestRequest("whoami");
                    request.AddHeader("Accept", "application/json");
                    request.Credentials = new NetworkCredential("bob", "hope");
                    Console.WriteLine(client.BuildUri(request));
                    var response = client.Execute<WhoAmIResponse>(request);

                    output.WriteLine(ep);
                    output.WriteLine(response.Content);
                    output.WriteLine(String.Empty.PadLeft(72, '='));
                }
            }
        }
        public void Authenticate_QueryParameters_ShouldSucceed(
				[Values(
					"/api/versions/", 
					"/api/collection/resource/?sort=asc", 
					"/api/versions?sort=asc",
					"/api/versions/?sort=asc&count=10",
					"/api/collection/resource?sort=asc&count=10")]string pathAndQuery
			)
        {
            var client = new RestClient( BASE_ROUTE );

            var request = new RestRequest( pathAndQuery );

            m_authenticator.Authenticate( client, request );

            string expectedUrl = GenerateExepctedUrl( pathAndQuery );

            Assert.AreEqual( expectedUrl, client.BuildUri(request).PathAndQuery );
        }
Ejemplo n.º 13
0
        public async Task<Token> LoginAsync(WebBrowser browser)
        {
            // Check for network connectivity
            if (!NetworkInterface.GetIsNetworkAvailable()) return null;

            var client =
                new RestClient("https://api.twitter.com/oauth/")
                {
                    FollowRedirects = true,
                    Authenticator = OAuth1Authenticator.ForRequestToken(_consumerKey, _consumerSecret)
                };

            var requestToken = await GetRequestToken(client);

            var uri = client.BuildUri(
                new RestRequest("authorize")
                    .AddParameter("oauth_token", requestToken["oauth_token"]));
            var verifier = await GetVerifier(browser, uri);

            client.Authenticator =
                OAuth1Authenticator.ForAccessToken(
                    _consumerKey, _consumerSecret,
                    requestToken["oauth_token"], requestToken["oauth_token_secret"],
                    verifier["oauth_verifier"]);
            var accessToken = await GetAccessToken(client);

            Debug.Assert(requestToken["oauth_token"] == verifier["oauth_token"]);

            InsertOrUpdateToken(
                new Token
                {
                    Id = int.Parse(accessToken["user_id"]),
                    Network = "twitter",
                    ScreenName = accessToken["screen_name"],
                    AccessToken = accessToken["oauth_token"],
                    AccessTokenSecret = accessToken["oauth_token_secret"]
                });

            Events.Publish(Token);

            return Token;
        }
Ejemplo n.º 14
0
        public async Task<Token> LoginAsync(WebBrowser browser)
        {
            // Check for network connectivity
            if (!NetworkInterface.GetIsNetworkAvailable()) return null;

            var guid = Guid.NewGuid().ToString();
            var client = new RestClient("https://www.facebook.com/dialog/oauth/");
            var request =
                new RestRequest()
                    .AddParameter("client_id", _consumerKey)
                    .AddParameter("redirect_uri", Redirect)
                    .AddParameter("scope", string.Empty)
                    .AddParameter("state", guid)
                    .AddParameter("response_type", "token");

            browser.IsScriptEnabled = true;

            var uri = client.BuildUri(request);
            var jsonToken = await GetRequestToken(browser, uri);

            if (jsonToken.ContainsKey("error_reason"))
                return null;
            if (jsonToken["state"] != guid)
                throw new SecurityException("Cross site forgery happend, the state did not equal the guid");

            var user = await GetUserInfo(jsonToken["access_token"]);

            InsertOrUpdateToken(
                new Token
                {
                    Id = user["id"].Value<int>(),
                    Network = "facebook",
                    ScreenName = user["name"].Value<string>(),
                    AccessToken = jsonToken["access_token"],
                    Expires = DateTime.Now + TimeSpan.FromSeconds(int.Parse(jsonToken["expires_in"]))
                });

            Events.Publish(Token);

            return Token;
        }
Ejemplo n.º 15
0
        public ActionResult RequestAndAuthorize()
        {
            var baseUrl = "https://api.linkedin.com/uas/";
            var client = new RestClient(baseUrl);

            client.Authenticator = OAuth1Authenticator.ForRequestToken("abe1zbhwrjvc", "um8jHurIU5UPqURD", "http://localhost:4777/linkedin/oauthcallback");
            var request = new RestRequest("oauth/requestToken", Method.POST);

            var response = client.Execute(request);

            var qs = HttpUtility.ParseQueryString(response.Content);
            var oauth_token = qs["oauth_token"];
            var oauth_token_secret = qs["oauth_token_secret"];

            Session["oauth-secret"] = oauth_token_secret;

            request = new RestRequest("oauth/authorize");
            request.AddParameter("oauth_token", oauth_token);
            var url = client.BuildUri(request).ToString();

            return Redirect(url);

            //var credentials = new OAuthCredentials
            //{
            //    CallbackUrl = "http://127.0.0.1/oauth/callback/",
            //    ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
            //    ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
            //    Verifier = "123456",
            //    Type = OAuthType.RequestToken
            //};
            //var client = new RestClient { Authority = "https://api.linkedin.com/uas/oauth", Credentials = credentials };
            //var request = new RestRequest { Path = "requestToken" };
            //RestResponse response = client.Request(request);

            //string token = response.Content.Split('&amp;').Where(s =&gt; s.StartsWith("oauth_token=")).Single().Split('=')[1];
            //string token_secret = response.Content.Split('&amp;').Where(s =&gt; s.StartsWith("oauth_token_secret=")).Single().Split('=')[1];

            //Response.Redirect("https://api.linkedin.com/uas/oauth?oauth_token=" + token);
        }
    public HttpStatusCode CallLogin()
    {
      RestClient Client = new RestClient(BASE_OAUTH_URL);
      Client.Authenticator = OAuth1Authenticator.ForRequestToken(CONSUMER_KEY, CONSUMER_SECRET, CALLBACK_URL );

      var request = new RestRequest("OAuth/RequestToken", Method.POST);
      var response = Client.Execute(request);

      if (response.StatusCode != HttpStatusCode.OK)
      {
        Client = null;
        return response.StatusCode;
      }
      else
      {
        //get the request token successfully
        //Get the request token and associated parameters.
        var qs = HttpUtility.ParseQueryString(response.Content);
        OAuthReqToken = qs["oauth_token"];
        OAuthReqTokenSecret = qs["oauth_token_secret"];


        //build URL for Authorization HTTP request
        RestRequest authorizeRequest = new RestRequest
        {
          Resource = "OAuth/Authorize",
          Method = Method.GET  //must be GET, POST will cause "500 - Internal server error."
        };
        authorizeRequest.AddParameter("viewmode", "full");
        authorizeRequest.AddParameter("oauth_token", OAuthReqToken);

        Uri authorizeUri = Client.BuildUri(authorizeRequest);
        LoginURL = authorizeUri.ToString();
      }

      return response.StatusCode;
    }
Ejemplo n.º 17
0
        //
        // GET: /Twitter/
        public ActionResult Login()
        {
            //TODO: move all this logic outside the controller?

            var client = new RestClient(baseUrl);

            //get a token
            client.Authenticator = OAuth1Authenticator.ForRequestToken(TokenManager.ConsumerKey, TokenManager.ConsumerSecret);
            var request = new RestRequest("oauth/request_token", Method.POST);
            var response = client.Execute(request);

            //parse response.
            var qs = HttpUtility.ParseQueryString(response.Content);
            var oauth_token = qs["oauth_token"];
            var oauth_token_secret = qs["oauth_token_secret"];

            //store secret in memory
            TokenManager.StoreNewRequestToken(oauth_token, oauth_token_secret);

            //get authorize token
            request = new RestRequest("oauth/authenticate");
            request.AddParameter("oauth_token", oauth_token);
            var url = client.BuildUri(request).ToString();

            //redirect to Twitter
            return Redirect(url);

            //return View((object)response.Content);
        }
Ejemplo n.º 18
0
	    private void RequestToString(IRestRequest request, RestClient client)
	    {
            var testUri = string.Format("{0}?", client.BuildUri(request).ToString());
            request.Parameters.ForEach(parameter => testUri += parameter.ToString() + "&");
            Debug.WriteLine(testUri);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Constructs a SOAP envelope request, with a body that includes the operation as element and the W3C Document and saves the SDMX Part of the response to the specified ouput
        /// The W3C Document contains either a SDMX-ML Query or a SDMX-ML Registry Interface
        /// </summary>
        /// <param name="request">
        /// The W3C Document representation of a SDMX-ML Query or QueryStructureRequest
        /// </param>
        /// <param name="tempFileName">
        /// The temporary file name
        /// </param>
        /// <param name="requestType">
        /// The request type
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// request is null
        /// </exception>
        /// <exception cref="NsiClientException">
        /// Error in server response or communication
        /// </exception>
        private void SendRequest(string request, string tempFileName, RequestType requestType)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            NsiClientHelper.LogSdmx(this._config, request);
            var endpointUri = new Uri(this._config.EndPoint);

            try
            {
               using (var writer = File.OpenWrite(tempFileName))
               {
                   var client = new RestClient(endpointUri.ToString());

                   var restRequest = new RestRequest(request, Method.GET);
                   restRequest.AddHeader("Accept-Encoding", "gzip, deflate");
                   if (requestType == RequestType.Data)
                   {
                       restRequest.AddHeader("Accept", "application/vnd.sdmx.structurespecificdata+xml;version=2.1");
                        if (Logger.IsDebugEnabled)
                        {
                           var buildUri = client.BuildUri(restRequest);
                           Logger.DebugFormat("Requesting URI : {0}", buildUri);
                        }
                   }

                   this._config.SetupRestAuth(client, restRequest);
                   restRequest.Timeout = 1800 * 1000;

                   // the lambda is executed inside the using
                   // ReSharper disable AccessToDisposedClosure
                   restRequest.ResponseWriter = (responseStream) => responseStream.CopyTo(writer);

                   // ReSharper restore AccessToDisposedClosure
                   var response = client.Execute(restRequest);

                   var httpStatusCode = response.StatusCode;
                   var responseStatus = response.ResponseStatus;
                   var responseUri = response.ResponseUri;
                   Logger.DebugFormat("HTTP status {0}, Response Status {1}, ResponseUri {2}", httpStatusCode, responseStatus, responseUri);

                   // we need to check the status if it is OK or not. No exceptions are thrown.
                   if (httpStatusCode == HttpStatusCode.NotFound || httpStatusCode == HttpStatusCode.Unauthorized)
                   {
                       throw new DataflowException(Resources.NoResultsFound);
                   }
                   if (httpStatusCode != HttpStatusCode.OK)
                   {
                       Logger.ErrorFormat("HTTP status {0}, Response Status {1}, ResponseUri {2}", httpStatusCode, responseStatus, responseUri);
                       Logger.ErrorFormat("ContentType {0}, Content Length: \n{1}", response.ContentType, response.ContentLength);
                       throw new NsiClientException(response.StatusDescription);
                   }
               }

                NsiClientHelper.LogSdmx(this._config, tempFileName, Resources.InfoSoapResponse);

               }
               catch (Exception ex)
               {
               Logger.Error(ex.Message, ex);
               throw;
               }
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            OENEntities ctx = null;

            try
            {
                ctx = new OENEntities();
                log4net.Config.XmlConfigurator.Configure();

                Logger.Info("Starting the association process");

                var client = new RestClient();
                var request = new RestRequest { OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; } };

                //client.BaseUrl = string.Format("https://network.adsmarket.com/api/rest/decoder/publisher_by_group/?uid={0}&key={1}&publisher_id=0&publisher_group={2}&limit={3}",Config.MarketSuperUserId,Config.MarketSuperUserApiKey,Config.MarketApiPublisherGroup,Config.MarketApiPublishersPerRequest );
                client.BaseUrl = "https://network.adsmarket.com/api/rest/decoder/publisher_by_group//";

                request.AddParameter("uid", Config.MarketSuperUserId);
                request.AddParameter("key", Config.MarketSuperUserApiKey);
                request.AddParameter("publisher_id", "0");
                request.AddParameter("publisher_group", Config.MarketApiPublisherGroup);
                request.AddParameter("limit", Config.MarketApiPublishersPerRequest);

                var publiserResponse = client.Execute<List<Publisher>>(request);

                if (publiserResponse == null || publiserResponse.Data == null || publiserResponse.Content.ToLower()
                    .Contains("\"errors\""))
                {
                    Logger.Info(client.BuildUri(request));
                    throw new Exception("Response is invalid");
                }

                var publishers = publiserResponse.Data.Where(p => !Config.ExcludedPublisherIds.Contains(p.id)).ToArray();

                publiserResponse = null;

                var dbPublisherIDs = ctx.MarketCampaignAssociations.Select(c => c.MarketAffiliateId)
                    .Distinct()
                    .Union(ctx.MarketOfferAssociations.Select(o => o.MarketAffiliateId).Distinct());

                Logger.InfoFormat("Found {0} Publishers, {1} new", publishers.Count(), publishers.Select(p => p.id).Except(dbPublisherIDs).Count());

                client = new RestClient();
                request = new RestRequest();

                //client.BaseUrl = string.Format("https://network.adsmarket.com/site/API2?userid={0}&key={1}&fn=findcampaigns&relationship_status=3",Config.MarketDefaultUserId,Config.MarketDefaultKey);
                client.BaseUrl = "https://network.adsmarket.com/site/API2";

                request.AddParameter("userid", Config.MarketDefaultUserId);
                request.AddParameter("key", Config.MarketDefaultKey);
                request.AddParameter("fn", "findcampaigns");
                request.AddParameter("relationship_status", "3");

                var campaignsResponse = client.Execute<List<Campaign>>(request);

                if (campaignsResponse == null || campaignsResponse.Data == null || campaignsResponse.Content.ToLower()
                    .Contains("\"errors\""))
                {
                    Logger.Info(client.BuildUri(request));
                    throw new Exception("Response is invalid");
                }

                var dbCampaignIDs = ctx.MarketCampaignAssociations.Select(c => c.CampaignId).Distinct();

                Logger.InfoFormat("Found {0} Campaigns, {1} new", campaignsResponse.Data.Count(), campaignsResponse.Data.Select(c => c.Id).Except(dbCampaignIDs).Count());

                var programs = campaignsResponse.Data.Select(c => c.ProgramId).Distinct().ToArray();

                //foreach (var campaign in campaignsResponse.Data)
                //{
                //    if (!programs.Contains(campaign.ProgramId))
                //    {
                //        programs.Add(campaign.ProgramId);
                //    }
                //}

                var dbProgramIDs = ctx.MarketOfferAssociations.Select(o => o.OfferId).Distinct();

                Logger.InfoFormat("Found {0} Programs, {1} new", programs.Count(), programs.Except(dbProgramIDs).Count());

                var existingProgramAssociations = ctx.MarketOfferAssociations.ToArray();

                var missingAPIKey = publishers.Where(p => string.IsNullOrWhiteSpace(p.api_key)).Select(p => p.id);

                // Associate Programs
                Logger.InfoFormat("Associating Programs");
                foreach (var publisher in publishers)
                {
                    if (string.IsNullOrWhiteSpace(publisher.api_key))
                    {
                        Logger.WarnFormat("Publisher {0} missing api_key", publisher.id);
                    }
                    else
                    {
                        var programsToAssociate =
                            programs.Where(p => p != 0 && !existingProgramAssociations.Any(mp => mp.MarketAffiliateId == publisher.id && mp.OfferId == p));

                        foreach (var program in programsToAssociate)
                        {
                            try
                            {
                                client = new RestClient();
                                client.BaseUrl = "https://network.adsmarket.com/api/rest/decoder/request_association//";

                                request = new RestRequest();

                                request.AddParameter("id", program);
                                request.AddParameter("fapprove", 1);
                                request.AddParameter("uid", publisher.id);
                                request.AddParameter("key", publisher.api_key);
                                request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

                                var programResponse = client.Execute(request);

                                if (programResponse == null || programResponse.Content == null)
                                {
                                    Logger.ErrorFormat("Program Association failed Program {0} for Publisher:{1} apiKey:{2}", program, publisher.id,
                                        publisher.api_key);
                                    continue;
                                }

                                if (programResponse.Content.ToLower()
                                    .Contains("error") && !programResponse.Content.ToLower()
                                        .Contains("association already exists"))
                                {
                                    Logger.ErrorFormat("Program Association failed Program {0} for Publisher:{1} apiKey:{2} response:{3}", program,
                                        publisher.id, publisher.api_key, programResponse.Content);
                                    continue;
                                }

                                Logger.InfoFormat("Associated Program {0} to Publisher {1}", program, publisher.id);

                                ctx.MarketOfferAssociations.Add(new MarketOfferAssociation()
                                {
                                    MarketAPIKey = publisher.api_key,
                                    MarketAffiliateId = publisher.id,
                                    OfferId = program
                                });

                                ctx.SaveChanges();
                            }
                            catch (DbEntityValidationException)
                            {
                                Logger.Error(GetEntityValidationErrors(ctx));
                                ctx = new OENEntities();
                            }
                            catch (Exception ex)
                            {
                                Logger.Error(ex.ToString());
                            }
                        }
                    }
                }

                var existingCampaignAssociations = ctx.MarketCampaignAssociations.ToArray();

                // Associate Campaigns
                foreach (var publisher in publishers)
                {
                    var campaignsToAssociate = campaignsResponse.Data.Where(c => c.Id != 0 && !existingCampaignAssociations.Any(mc => mc.MarketAffiliateId == publisher.id && mc.CampaignId == c.Id));

                    foreach (var campaign in campaignsToAssociate)
                    {
                        try
                        {
                            client = new RestClient();
                            client.BaseUrl = "https://network.adsmarket.com/api/rest/decoder/publisher_campaign_association//";

                            request = new RestRequest();

                            request.AddParameter("campaign_id", campaign.Id);
                            request.AddParameter("publisher_id", publisher.id);
                            request.AddParameter("uid", "1");
                            request.AddParameter("key", "a4f0703e44e032caa51fbb092eb6e821");
                            request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

                            var campaignResponse = client.Execute(request);

                            if (campaignResponse == null || campaignResponse.Content == null)
                            {
                                Logger.ErrorFormat("Campaign Association failed Campaign {0} for Publisher:{1} apiKey:{2}", campaign.Id,
                                    publisher.id, publisher.api_key);
                                continue;
                            }

                            if (campaignResponse.Content.ToLower()
                                .Contains("error") && !campaignResponse.Content.ToLower()
                                    .Contains("association already exists"))
                            {
                                Logger.ErrorFormat("Campaign Association failed Campaign {0} for Publisher:{1} apiKey:{2} response:{3}",
                                    campaign.Id, publisher.id, publisher.api_key, campaignResponse.Content);
                                continue;
                            }

                            Logger.InfoFormat("Associated Campaign {0} to Publisher {1}", campaign.Id, publisher.id);

                            ctx.MarketCampaignAssociations.Add(new MarketCampaignAssociation()
                            {
                                MarketAffiliateId = publisher.id,
                                CampaignId = campaign.Id
                            });

                            ctx.SaveChanges();
                        }
                        catch (DbEntityValidationException)
                        {
                            Logger.Error(GetEntityValidationErrors(ctx));
                            ctx = new OENEntities();
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex.ToString());
                        }
                    }
                }

                Logger.Info("Ending the association process.");
            }
            catch (DbEntityValidationException ex)
            {
                if (ctx != null)
                {
                    Logger.Error(GetEntityValidationErrors(ctx));
                }
                else
                {
                    Logger.Error(ex.ToString());
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
            }
        }
Ejemplo n.º 21
0
        private void SkyDriveLogIn()
        {
            RestClient client = new RestClient("https://login.live.com/");

            RestRequest request = new RestRequest(Method.GET);
            request.Resource = "oauth20_authorize.srf";
            request.AddParameter("client_id", SkyDrive.Properties.SkyDriveClientID);
            request.AddParameter("scope", "wl.signin wl.offline_access wl.skydrive wl.skydrive_update wl.photos");
            request.AddParameter("response_type", "code");
            request.AddParameter("redirect_uri", "https://login.live.com/oauth20_desktop.srf");

            IRestResponse response = client.Execute(request);
            LoginBrowser.Navigate(client.BuildUri(request));
        }
Ejemplo n.º 22
0
        private void GoogleDriveLogIn()
        {
            RestClient client = new RestClient("https://accounts.google.com");
            string scopes = "https://www.googleapis.com/auth/drive";
            scopes += " https://www.googleapis.com/auth/drive.file";
            scopes += " https://www.googleapis.com/auth/drive.metadata.readonly";
            scopes += " https://www.googleapis.com/auth/drive.readonly";
            scopes += " https://www.googleapis.com/auth/userinfo.profile";

            RestRequest request = new RestRequest(Method.GET);
            request.Resource = "/o/oauth2/auth";
            request.AddParameter("client_id", DriveLogIn.ClientID);
            request.AddParameter("scope", scopes);
            request.AddParameter("response_type", "code");
            request.AddParameter("redirect_uri", "urn:ietf:wg:oauth:2.0:oob");
            request.AddParameter("access_type", "offline");
            request.AddParameter("state", "");

            IRestResponse response = client.Execute(request);
            LoginBrowser.Navigate(client.BuildUri(request));
        }
Ejemplo n.º 23
0
        private RestSharp.RestClient CreateRestClient(IRestRequest request)
        {
            var client = new RestSharp.RestClient(this._requestCredentials.BaseUrl);

            client.FollowRedirects = false;

            request.AddQueryParameter("api_sig", this._requestCredentials.CreateSignature(client.BuildUri(request).AbsoluteUri));
            return(client);
        }
Ejemplo n.º 24
0
Archivo: OAuth.cs Proyecto: Gloor/lma
        /// <summary>
        /// Requests authorization of your application by first sending the RequestToken request and then generate an LinkedIN URL to which users can be redirected. This is the first stage of OAuth.
        /// </summary>
        /// <param name="callbackUri">The <see cref="Uri"/> to which the user is redirected when returning from the LinkedIN authorization screen.</param>
        /// <param name="token">The <see cref="RequestToken"/>. Keep this somewhere safely stored with the user's session. You will need the provide this later in method <see cref="ExchangeCodeForAccessToken"/>.</param>
        /// <returns>Returns the LinkedIN authorization <see cref="Uri"/> to which users must be redirected in order give access to your application.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="callbackUri"/> is null.</exception>
        /// <exception cref="LinkedINHttpResponseException">Thrown when LinkedIN did not respond properly while requesting the request token.</exception>
        public Uri RequestAuthorizationToken( Uri callbackUri, out RequestToken token )
        {
            // validate arguments
            if ( callbackUri == null )
                throw new ArgumentNullException( "callbackUri" );

            // create the client
            var client = new RestClient
                         	{
                         		BaseUrl = OAuthBaseUrl,
                         		Authenticator = OAuth1Authenticator.ForRequestToken( consumerKey, consumerSecret, callbackUri.ToString() )
                         	};

            // create the request
            var requestTokenRequest = new RestRequest( "requestToken" );
              requestTokenRequest.AddParameter("scope", "r_fullprofile rw_nus rw_groups");

            // execute the request
            var requestTokenResponse = ExecuteRequest( client, requestTokenRequest );

            // extract the token from the query string
            var requestTokenResponseParameters = HttpUtility.ParseQueryString( requestTokenResponse.Content );
            var requestToken = requestTokenResponseParameters[ "oauth_token" ];
            var requestSecret = requestTokenResponseParameters[ "oauth_token_secret" ];
            token = new RequestToken( requestToken, requestSecret );

            // build the redirect uri
            requestTokenRequest = new RestRequest( "authenticate?oauth_token=" + requestToken );
            return client.BuildUri( requestTokenRequest );
        }
Ejemplo n.º 25
0
 private static IRestResponse GetTile(GetTile request)
 {
     var client = new RestClient(new AppSettings().Get(BaseUrl, "http://localhost:8080"));
       var tileRequest = new RestRequest(RestParams(request));
       var log = typeof(TileFactory).Log();
       var msg = new
       {
     Common = request.ToGetUrl(),
     NonStandard = client.BuildUri(tileRequest)
       };
       log.DebugFormat("Tile request {0}", msg.Dump());
       IRestResponse tileResponse;
       try
       {
     tileResponse = client.ExecuteAsGet(tileRequest, HttpMethods.Get);
       }
       catch (Exception exc)
       {
     log.ErrorFormat("Issue: {0} at {1}", exc.Message, exc.StackTrace);
     throw;
       }
       return tileResponse;
 }
        private string GetTwitterAccount()
        {
            var baseUrl = "http://api.twitter.com";
            var client = new RestClient(baseUrl);
            client.Authenticator = OAuth1Authenticator.ForRequestToken(this.TwitterConsumerKey,
                                                                       this.TwitterConsumerSecret);

            var request = new RestRequest("oauth/request_token", Method.POST);
            var response = client.Execute(request);

            var qs = HttpUtility.ParseQueryString(response.Content);
            var oauth_token = this.Session["oauth_token"] = qs["oauth_token"];
            var oauth_token_secret = this.Session["oauth_token_secret"] = qs["oauth_token_secret"];

            request = new RestRequest("oauth/authorize");
            request.AddParameter("oauth_token", oauth_token);
            request.AddParameter("oauth_callback", this.TwitterCallbackUrl);

            var url = client.BuildUri(request).ToString();

            return url;
        }
Ejemplo n.º 27
0
        private void GetAccessTokenUrl()
        {
            this.GetOAuthToken();

            var sslClient = new RestClient(_baseUrl);
            var request = new RestRequest("/1/OAuthAuthorizeToken");
            request.AddParameter("oauth_token", this._oauth_token);
            request.AddParameter("oauth_consumer_key", consumerKey);
            request.AddParameter("application_name", "trello for android");
            request.AddParameter("oauth_callback", "http://desarrollomobile.net");
            this.Url = sslClient.BuildUri(request);

            if (UrlReady != null)
            {
                UrlReady();
            }
        }