Esempio n. 1
0
 public static JObject GetSocialActionSummary(this LinkedInApi api, params string[] shareUrns)
 {
     return(JsonConvert.DeserializeObject <JObject>(api.RawGetJsonQuery(
                                                        path: $"/v2/socialActions?{String.Join("&", shareUrns.Select(y => $"ids={y}"))}",
                                                        user: LinkedInApiFactory.GetUserAuthorization()
                                                        )));
 }
Esempio n. 2
0
        public static List <ProfileElement> GetProfilesByIds(this LinkedInApi api, IEnumerable <string> personIds)
        {
            if (personIds.Count() == 0)
            {
                return(new List <ProfileElement>());
            }

            List <ProfileElement> result      = new List <ProfileElement>();
            const int             batchAmount = 50;

            do
            {
                IEnumerable <string> batch = personIds.Take(batchAmount);

                string     personIdsConcat = String.Join(",", batch.Select(y => $"(id:{y.Split(':').Last()})"));
                PersonList profiles        = api.Profiles.GetProfilesByIds(LinkedInApiFactory.GetUserAuthorization(), personIdsConcat);

                foreach (var p in profiles.Results)
                {
                    JProperty      jProperty = p as JProperty;
                    ProfileElement profile   = jProperty.First.ToObject <ProfileElement>();

                    if (profile.ProfileId == "private")
                    {
                        continue;
                    }

                    result.Add(profile);
                }

                personIds = personIds.Skip(batchAmount);
            } while (personIds.Any());

            return(result);
        }
Esempio n. 3
0
        public static LinkedInApiPaginatedResult <AdAccountElement> GetAdAccounts(this LinkedInApi api)
        {
            string adAccountsJson = api.RawGetJsonQuery("/v2/adAccountsV2?q=search", LinkedInApiFactory.GetUserAuthorization());
            LinkedInApiPaginatedResult <AdAccountElement> adAccounts = JsonConvert.DeserializeObject <LinkedInApiPaginatedResult <AdAccountElement> >(adAccountsJson);

            return(adAccounts);
        }
Esempio n. 4
0
        // http://davideguida.altervista.org/mvc-reading-linkedin-user-profile-data/
        // https://github.com/SparkleNetworks/LinkedInNET

        //public RedirectResult Profile()
        //{
        //    var redirectUrl = "http://mydomain/linkedin/profilereturn/";
        //    var url = GetAuthorizationUrl(redirectUrl);
        //    return Redirect(url.ToString());
        //}

        private static LinkedInApi CreateAPI()
        {
            var config = new LinkedInApiConfiguration("77ck1ulnz4e5yh", "olqES8j6K3uXJMNg");
            var api    = new LinkedInApi(config);

            return(api);
        }
Esempio n. 5
0
        public async Task <ActionResult> OAuth2(string code, string state, string error, string error_description)
        {
            if (!string.IsNullOrEmpty(error))
            {
                this.ViewBag.Error            = error;
                this.ViewBag.ErrorDescription = error_description;
                return(View());
            }
            else
            {
                try
                {
                    api = new LinkedInApi(config);
                    var redirectUrl = "http://localhost:55840/Home/OAuth2"; // Url.Action("OAuth2");
                    var userToken   = await api.OAuth2.GetAccessTokenAsync(code, redirectUrl);

                    var      user        = new UserAuthorization(userToken.AccessToken);
                    string[] acceptlangs = { "en-US" };
                    var      profile     = api.Profiles.GetMyProfile(user, acceptlangs);//, acceptlangs, FieldSelector.For<Person>().WithAllFields());
                    code = string.Empty;
                    userToken.AccessToken = string.Empty;
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                    // throw new HttpRequestException("Request to linkedin Service failed.");
                }
            }

            return(View());
        }
Esempio n. 6
0
        private static readonly long VIDEO_MAX_BYTE_SIZE = 52428800; // 209715200;

        #region Video upload
        public static async Task <string> UploadVideoAsync(LinkedInApi api, UserAuthorization user, string ownerURN, byte[] videoData)
        {
            var requestVideoUpload = await RequestVideoUpload(api, user, ownerURN, videoData.Length);

            if (videoData.Length > VIDEO_MAX_BYTE_SIZE)
            {
                var upload = await UploadLongVideoPartsAsync(api, requestVideoUpload, videoData);


                var complete = await CompletMultiPartVideoAsync(user, api, requestVideoUpload, upload);
            }
            else
            {
                var shortVideoUp = await ShortUploadVideoAsync(api, requestVideoUpload, videoData);
            }

            // check video upload status before upload
            var assetMatch = Regex.Match(requestVideoUpload.Value.Asset, @"^.+?:([^:]+?)$");
            var assetId    = assetMatch.Groups[1].ToString();

            while (true)
            {
                var video = await api.Asset.GetAssetAsync(user, assetId);

                // no null error check needed, cuz if it would be null we would thow an exception
                if (video.Recipes.FirstOrDefault().Status != "PROCESSING")
                {
                    break;
                }
                await Task.Delay(1000 * 5);
            }

            return(requestVideoUpload.Value.Asset);
        }
Esempio n. 7
0
        /// <summary>
        /// Authenitcate API from
        /// </summary>
        /// <param name="LinkedInClientId"></param>
        /// <param name="LinkedInClientSecret"></param>
        /// <returns></returns>
        public LinkedInApi ConfigLinkedInAPI(string linkedInClientId, string linkedInClientSecret)
        {
            var config = new LinkedInApiConfiguration(linkedInClientId, linkedInClientSecret);
            var api    = new LinkedInApi(config);

            return(api);
        }
Esempio n. 8
0
        public async Task Post(MessageOptions messageOptions, Dictionary <string, string> providerParams)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                                   | SecurityProtocolType.Tls11
                                                   | SecurityProtocolType.Tls12;
            string authCode = null;

            foreach (var param in providerParams)
            {
                if (param.Key == Name)
                {
                    authCode = param.Value;
                }
            }

            var config = new LinkedInApiConfiguration(_options.AppId, _options.AppSecret);
            var api    = new LinkedInApi(config);

            if (authCode != null)
            {
                var accessTokenResult = await api.OAuth2.GetAccessTokenAsync(authCode, _options.RedirectUrl);

                var accessToken = accessTokenResult.AccessToken;
                var requestUrl  = $"https://api.linkedin.com/v2/shares?oauth2_access_token={accessToken}";
                PostToLinkedIn(requestUrl, messageOptions);
            }
        }
Esempio n. 9
0
        public LinkedInService()
        {
            // create a configuration object
            var config = new LinkedInApiConfiguration("811365ndnikk36", "hpqB5j5i6HAnZ93Y");

            // get the APIs client
            linkedInAPI = new LinkedInApi(config);
        }
Esempio n. 10
0
        public static LinkedInApiPaginatedResult <LikeElement> GetLikesForActivity(this LinkedInApi api, string activityUrn, int count = 500, int start = 0)
        {
            string apiPath = $"/v2/socialActions/{activityUrn}/likes?count={count}&start={start}";

            string likesJson = api.RawGetJsonQuery(apiPath, LinkedInApiFactory.GetUserAuthorization());
            LinkedInApiPaginatedResult <LikeElement> result = JsonConvert.DeserializeObject <LinkedInApiPaginatedResult <LikeElement> >(likesJson);

            return(result);
        }
Esempio n. 11
0
        public static CampaignElement GetAdCampaign(this LinkedInApi api, string campaignId)
        {
            string campaignJson = api.RawGetJsonQuery(
                path: $"/v2/adCampaignsV2/{campaignId}",
                user: LinkedInApiFactory.GetUserAuthorization()
                );

            CampaignElement campaign = JsonConvert.DeserializeObject <CampaignElement>(campaignJson);

            return(campaign);
        }
Esempio n. 12
0
        public ActionResult Index()
        {
            api = new LinkedInApi(config);
            var scope       = (AuthorizationScope)"r_fullprofile%20r_emailaddress%20w_share";// AuthorizationScope.ReadBasicProfile | AuthorizationScope.ReadEmailAddress;
            var state       = Guid.NewGuid().ToString();
            var redirectUrl = "http://localhost:55840/Home/OAuth2";
            var url         = api.OAuth2.GetAuthorizationUrl(scope, state, redirectUrl);

            // now redirect your user there
            return(Redirect(url.ToString()));
        }
Esempio n. 13
0
        public ActionResult Index()
        {
            api = new LinkedInApi(config);
            var scope       = AuthorizationScope.ReadBasicProfile | AuthorizationScope.ReadEmailAddress;
            var state       = Guid.NewGuid().ToString();
            var redirectUrl = "http://localhost:55840/Home/OAuth2";
            var url         = api.OAuth2.GetAuthorizationUrl(scope, state, redirectUrl);

            // https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=...
            // now redirect your user there
            return(Redirect(url.ToString()));
        }
Esempio n. 14
0
            public void Works()
            {
                AuthorizationScope scope = AuthorizationScope.ReadBasicProfile | AuthorizationScope.ReadEmailAddress;
                string state = "AZERTYUIOP";
                string redirectUri = "http://localhost/Callbacks/LinkedIN?Redirect=" + Uri.EscapeDataString("/Profile?LinkedIN");

                var config = new LinkedInApiConfiguration { ApiKey = "HELLOAPI", BaseOAuthUrl = "https://linkedin.com", };
                var api = new LinkedInApi(config);

                var result = api.OAuth2.GetAuthorizationUrl(scope, state, redirectUri);
                Assert.AreEqual("https://linkedin.com/uas/oauth2/authorization?response_type=code&client_id=HELLOAPI&scope=r_basicprofile%20r_emailaddress&state=AZERTYUIOP&redirect_uri=http%3A%2F%2Flocalhost%2FCallbacks%2FLinkedIN%3FRedirect%3D%252FProfile%253FLinkedIN", result.OriginalString);
            }
Esempio n. 15
0
        private static async Task <string> ShortUploadVideoAsync(LinkedInApi api, RegisterUploadResult registerUpload, byte[] videoData)
        {
            var postAssetResult = await api.Asset.UploadAssetAsync(registerUpload.Value.UploadMechanism.ComLinkedinDigitalmediaUploadingMediaUploadHttpRequest.UploadUrl, new Asset.UploadAssetRequest()
            {
                RequestHeaders = new Asset.ComLinkedinDigitalmediaUploadingMediaUploadHttpRequest()
                {
                    Headers   = registerUpload.Value.UploadMechanism.ComLinkedinDigitalmediaUploadingMediaUploadHttpRequest.Headers,
                    UploadUrl = registerUpload.Value.UploadMechanism.ComLinkedinDigitalmediaUploadingMediaUploadHttpRequest.UploadUrl,
                },
                Data = videoData
            });

            return(postAssetResult);
        }
Esempio n. 16
0
            public void Works()
            {
                AuthorizationScope scope       = AuthorizationScope.ReadBasicProfile | AuthorizationScope.ReadEmailAddress;
                string             state       = "AZERTYUIOP";
                string             redirectUri = "http://localhost/Callbacks/LinkedIN?Redirect=" + Uri.EscapeDataString("/Profile?LinkedIN");

                var config = new LinkedInApiConfiguration {
                    ApiKey = "HELLOAPI", BaseOAuthUrl = "https://linkedin.com",
                };
                var api = new LinkedInApi(config);

                var result = api.OAuth2.GetAuthorizationUrl(scope, state, redirectUri);

                Assert.AreEqual("https://linkedin.com/uas/oauth2/authorization?response_type=code&client_id=HELLOAPI&scope=r_basicprofile%20r_emailaddress&state=AZERTYUIOP&redirect_uri=http%3A%2F%2Flocalhost%2FCallbacks%2FLinkedIN%3FRedirect%3D%252FProfile%253FLinkedIN", result.OriginalString);
            }
    protected void cbLinkedIn_CheckedChanged(object sender, EventArgs e)
    {
        bool isChecked = cbLinkedIn.Checked;

        if (isChecked)
        {
            string requestCode = string.Empty;
            if (Session[LinkedInCodeSessionKey] == null)
            {
                Session[MessageKey] = txtFeedContent.Text.Trim();
                //Session[TitleKey] = txtTitle.Text.Trim();
                Session[ShareCodeType]   = "LinkedIn";
                Session[CurrentResultID] = hdnSelectedMessageID.Value;
                Session[CurrentMessage]  = lblPostTitle.Text.Trim();

                var config = new LinkedInApiConfiguration(LinkedInAppID, LinkedInSecret);

                // get the APIs client
                var api = new LinkedInApi(config);

                string queryString = Request.Url.Query;

                string redirectUrl = Request.Url.AbsoluteUri;
                if (queryString.Trim() != string.Empty)
                {
                    redirectUrl = redirectUrl.Replace(queryString, string.Empty);
                }

                var scope = AuthorizationScope.ReadBasicProfile | AuthorizationScope.ReadEmailAddress | AuthorizationScope.WriteShare | AuthorizationScope.ReadWriteCompanyPage;
                var state = Guid.NewGuid().ToString();
                var url   = api.OAuth2.GetAuthorizationUrl(scope, state, redirectUrl);

                Response.Redirect(url.AbsoluteUri, false);
            }
        }
        else
        {
            Session.Remove(LinkedInCodeSessionKey);
            string queryString = Request.Url.Query;

            string redirectUrl = Request.Url.AbsoluteUri;
            if (queryString.Trim() != string.Empty)
            {
                redirectUrl = redirectUrl.Replace(queryString, string.Empty);
                Response.Redirect(redirectUrl);
            }
        }
    }
Esempio n. 18
0
        public static async Task PublishMessage(string text, string imageUrl = null)
        {
            var config = new LinkedInApiConfiguration(SendTweet.Configuration["linkedInApiKey"], SendTweet.Configuration["linkedInApiKeySecret"]);
            var api    = new LinkedInApi(config);

            var user = new UserAuthorization(accessToken);

            try
            {
                await api.Shares.PostAsync(user, new PostShare()
                {
                    Owner   = $"urn:li:person:{SendTweet.Configuration["linkedInUserId"]}",
                    Subject = "Azure Lowlands",
                    Text    = new PostShareText()
                    {
                        Text = "Remember, the full line-up for #AzureLowlands is available now, so check https://azurelowlands.com for all details and get your FREE tickets today!"
                    }
                });
            }
            catch (Exception exception)
            {
                var temp = exception;
            }

            /*await api.UGCPost.PostAsync(user, new UGCPostData()
             * {
             *  Author = $"urn:li:person:{SendTweet.Configuration["linkedInUserId"]}",
             *  LifecycleState = "PUBLISHED",
             *  Visibility = new UGCPostvisibility()
             *  {
             *      comLinkedinUgcMemberNetworkVisibility = "PUBLIC"
             *  },
             *  SpecificContent = new SpecificContent()
             *  {
             *      ComLinkedinUgcShareContent = new ComLinkedinUgcShareContent()
             *      {
             *          ShareCommentary = new UGCText()
             *          {
             *              Text = "Remember, the full line-up for #AzureLowlands is available now, so check https://azurelowlands.com for all details and get your FREE tickets today!"
             *          },
             *          ShareMediaCategory = "NONE"
             *      }
             *  }
             * });*/
        }
Esempio n. 19
0
        public static async Task <List <string> > UploadLongVideoPartsAsync(LinkedInApi api, RegisterUploadResult registerUpload, byte[] videoData)
        {
            try
            {
                if (registerUpload.Value.UploadMechanism.ComLinkedinDigitalmediaUploadingMultipartUpload.PartUploadRequests == null)
                {
                    throw new NullReferenceException("UploadLongVideoAsync param is null");
                }
            }
            catch (Exception e)
            {
                throw new NullReferenceException("UploadLongVideoAsync param is null", e);
            }

            // maybe in a later version we should return the status code as well
            List <string> partsResult = new List <string>();

            foreach (var part in registerUpload.Value.UploadMechanism.ComLinkedinDigitalmediaUploadingMultipartUpload.PartUploadRequests)
            {
                int length = (int)((part.ByteRange.LastByte + 1) - part.ByteRange.FirstByte);

                byte[] destinationArray = new byte[] { };
                Array.Resize(ref destinationArray, length);
                Array.Copy(videoData, part.ByteRange.FirstByte, destinationArray, 0, length);


                var postAssetResult = await api.Asset.UploadAssetAsync(part.Url, new Asset.UploadAssetRequest()
                {
                    RequestHeaders = new Asset.ComLinkedinDigitalmediaUploadingMediaUploadHttpRequest()
                    {
                        Headers   = part.Headers,
                        UploadUrl = part.Url,
                    },
                    Data = destinationArray
                });

                partsResult.Add(postAssetResult);
            }

            return(partsResult);
        }
Esempio n. 20
0
        private static async Task <RegisterUploadResult> RequestVideoUpload(LinkedInApi api, UserAuthorization user, string ownerURN, long fileSize)
        {
            var asset = new Asset.RegisterUploadRequest()
            {
                RegisterUploadRequestData = new Asset.RegisterUploadRequestData()
                {
                    SupportedUploadMechanism = new List <string>()
                    {
                        "SINGLE_REQUEST_UPLOAD"
                    },
                    Owner   = ownerURN,
                    Recipes = new List <string>()
                    {
                        "urn:li:digitalmediaRecipe:feedshare-video"
                    },
                    ServiceRelationships = new List <Asset.ServiceRelationship>()
                    {
                        new Asset.ServiceRelationship()
                        {
                            Identifier       = "urn:li:userGeneratedContent",
                            RelationshipType = "OWNER"
                        }
                    }
                }
            };

            if (fileSize > VIDEO_MAX_BYTE_SIZE)
            {
                asset.RegisterUploadRequestData.FileSize = fileSize;
                asset.RegisterUploadRequestData.SupportedUploadMechanism = new List <string>()
                {
                    "MULTIPART_UPLOAD"
                };
            }

            var requestAsset = await api.Asset.RegisterUploadAsync(user, asset);

            return(requestAsset);
        }
Esempio n. 21
0
        public static IEnumerable <PostShareResult> GetAllSharesForOrganization(this LinkedInApi api, string organizationUrn)
        {
            PostShares       sharesPage;
            HashSet <string> activities = new HashSet <string>();
            int currentRecordIndex      = 0;

            do
            {
                sharesPage = api.Shares.GetShares(
                    user: LinkedInApiFactory.GetUserAuthorization(),
                    urn: organizationUrn,
                    sharesPerOwner: 1000,
                    count: 50,
                    start: currentRecordIndex
                    );

                if (sharesPage.Elements.Count == 0)
                {
                    yield break;
                }

                foreach (PostShareResult share in sharesPage.Elements)
                {
                    if (activities.Contains(share.Activity))
                    {
                        continue;
                    }

                    yield return(share);

                    activities.Add(share.Activity);
                }

                currentRecordIndex += sharesPage.Elements.Count;
            } while (sharesPage.Paging.Total > 0);
        }
Esempio n. 22
0
 internal protected BaseApi(LinkedInApi linkedInApi)
 {
     this.linkedInApi = linkedInApi;
 }
Esempio n. 23
0
 internal JobsApi(LinkedInApi linkedInApi)
     : base(linkedInApi)
 {
 }
Esempio n. 24
0
 public void Arg2Empty()
 {
     var api = new LinkedInApi(new LinkedInApiConfiguration());
     api.OAuth2.GetAuthorizationUrl(AuthorizationScope.ReadEmailAddress, "hello", string.Empty);
 }
Esempio n. 25
0
 internal CommonApi(LinkedInApi linkedInApi)
     : base(linkedInApi)
 {
 }
Esempio n. 26
0
 public void ChecksConfiguration()
 {
     var api = new LinkedInApi(new LinkedInApiConfiguration());
     api.OAuth2.GetAuthorizationUrl(AuthorizationScope.ReadEmailAddress, "hello", "world");
 }
Esempio n. 27
0
        public async Task <ActionResult> OAuth2(string code, string state, string error, string error_description)
        {
            if (!string.IsNullOrEmpty(error))
            {
                this.ViewBag.Error            = error;
                this.ViewBag.ErrorDescription = error_description;
                return(View());
            }
            api = new LinkedInApi(config);
            var redirectUrl = "http://localhost:55840/Home/OAuth2"; // Url.Action("OAuth2");
            ////replacing below code to get accesstoken instead of **B
            //var client = new RestClient("https://www.linkedin.com/oauth/v2/accessToken") { };
            //var authRequest = new RestRequest("", Method.GET) { };
            //authRequest.AddHeader("Content-Type", "x-www-form-urlencoded");
            //authRequest.AddParameter("grant_type", "authorization_code");
            //authRequest.AddParameter("code", code);
            //authRequest.AddParameter("redirect_uri", redirectUrl);
            //authRequest.AddParameter("client_id", "81u03um2b7wur4");
            //authRequest.AddParameter("client_secret", "oS1GvGtBruhC4s75");
            //authRequest.AddParameter("scope", "r_liteprofile%20r_emailaddress%20w_member_social");
            //authRequest.AddParameter("state", Guid.NewGuid().ToString());

            var userToken = await api.OAuth2.GetAccessTokenAsync(code, redirectUrl);

            try
            {
                var response = userToken;// client.Execute(authRequest);

                //if call failed ErrorResponse created...simple class with response properties
                //if (!response.IsSuccessful)
                //{
                //    var errorData =  response.Content.ToString();
                //    //    ErrorResponse errResp = JsonConvert.DeserializeObject<ErrorResponse>(error);
                //    //    throw new PayPalException { error_name = errResp.name, details = errResp.details, message = errResp.message };
                //}

                //var success =  response.Content.ToString();
                //  var result = JsonConvert.DeserializeObject<Models.LinkedInTokenResponseModel>(success);

                //**B// var user = new UserAuthorization(response.ToString());
                var      user        = new UserAuthorization(userToken.AccessToken);
                string[] acceptlangs = { "en-US" };
                var      profile     = api.Profiles.GetMyProfile(user, acceptlangs);//, acceptlangs, FieldSelector.For<Person>().WithAllFields());

                //for our own desired fieldsets
                try
                {
                    // var profile = this.api.Profiles.GetMyProfile(user , acceptlangs, FieldSelector.For<Person>().WithAllFields());
                    var Profileclient = new RestClient("https://api.linkedin.com/v2/me")
                    {
                    };
                    var ProfileAuthRequest = new RestRequest("", Method.GET)
                    {
                    };
                    ProfileAuthRequest.AddHeader("Authorization", "Bearer " + userToken.AccessToken);
                    ProfileAuthRequest.AddParameter("scope", "r_liteprofile%20r_emailaddress%20w_member_social");
                    var Profileresponse = Profileclient.Execute(ProfileAuthRequest);
                }
                catch (LinkedInApiException ex) // one exception type to handle
                {
                    Response.Write(ex.Message);
                    // ex.InnerException // WebException
                    // however it is not recommended to specify all fields
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                throw new HttpRequestException("Request to linkedin Service failed.");
            }

            //**B   //var result = await this.api.OAuth2.GetAccessTokenAsync(code, redirectUrl); Commenting because giving me error
            //this.ViewBag.Code = code;
            //this.ViewBag.Token = authResponse;  //**B   //result.AccessToken;
            //this.data.SaveAccessToken(result.AccessToken);
            //**B   var user = new UserAuthorization(result.AccessToken);



            ////var profile = this.api.Profiles.GetMyProfile(user);
            ////this.data.SaveAccessToken();
            return(View());
        }
Esempio n. 28
0
 public static LinkedInApiPaginatedResult <LikeElement> GetLikesForShare(this LinkedInApi api, PostShareResult share, int count = 500, int start = 0)
 => GetLikesForActivity(api, share.Activity, count, start);
Esempio n. 29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OAuth2Api"/> class.
 /// </summary>
 /// <param name="linkedInApi">The linked information API.</param>
 public OAuth2Api(LinkedInApi linkedInApi)
     : base(linkedInApi)
 {
 }
Esempio n. 30
0
 internal CompaniesApi(LinkedInApi linkedInApi)
     : base(linkedInApi)
 {
 }
Esempio n. 31
0
 internal SocialApi(LinkedInApi linkedInApi)
     : base(linkedInApi)
 {
 }
Esempio n. 32
0
        private static async Task <int> CompletMultiPartVideoAsync(UserAuthorization user, LinkedInApi api, RegisterUploadResult registerUploadResult, List <string> uploadResult)
        {
            var partUploadResponses = new List <PartUploadResponse>();

            foreach (var uploadRes in uploadResult)
            {
                partUploadResponses.Add(new PartUploadResponse()
                {
                    HttpStatusCode = 200,
                    Headers        = new PartUploadResponseHeaders()
                    {
                        ETag = uploadRes
                    }
                });
            }

            var completeMultiPartUploadRequest = new CompleteMultipartUploadRequest()
            {
                CompleteMultipartUploadRequestData = new CompleteMultipartUploadRequestData()
                {
                    MediaArtifact       = registerUploadResult.Value.MediaArtifact,
                    Metadata            = registerUploadResult.Value.UploadMechanism.ComLinkedinDigitalmediaUploadingMultipartUpload.Metadata,
                    PartUploadResponses = partUploadResponses
                }
            };

            var complete = await api.Asset.CompleteMultiPartUploadAsync(user, completeMultiPartUploadRequest);


            return(complete);
        }
Esempio n. 33
0
 public Api(LinkedInApi linkedInApi)
     : base(linkedInApi)
 {
 }
Esempio n. 34
0
 public void Arg2Empty()
 {
     var api = new LinkedInApi(new LinkedInApiConfiguration());
     api.OAuth2.GetAccessToken("hello", string.Empty);
 }
Esempio n. 35
0
 internal GroupsApi(LinkedInApi linkedInApi)
     : base(linkedInApi)
 {
 }
Esempio n. 36
0
 internal ProfilesApi(LinkedInApi linkedInApi)
     : base(linkedInApi)
 {
 }
    private bool PostLinkedIn()
    {
        string requestCode = Session[LinkedInCodeSessionKey].ToString();

        if (requestCode == null)
        {
            Session[MessageKey] = txtFeedContent.Text.Trim();
            //Session[TitleKey] = txtTitle.Text.Trim();

            var config = new LinkedInApiConfiguration(LinkedInAppID, LinkedInSecret);
            var api    = new LinkedInApi(config);

            string queryString = Request.Url.Query;

            string redirectUrl = Request.Url.AbsoluteUri;
            if (queryString.Trim() != string.Empty)
            {
                redirectUrl = redirectUrl.Replace(queryString, string.Empty);
            }

            var scope = AuthorizationScope.ReadBasicProfile | AuthorizationScope.ReadEmailAddress | AuthorizationScope.WriteShare | AuthorizationScope.ReadWriteCompanyPage;
            var state = Guid.NewGuid().ToString();
            var url   = api.OAuth2.GetAuthorizationUrl(scope, state, redirectUrl);

            Response.Redirect(url.AbsoluteUri, false);
        }
        else
        {
            int linkedInCompanyID = int.Parse(LinkedInCompanyID);

            string queryString = Request.Url.Query;

            string redirectUrl = Request.Url.AbsoluteUri;
            if (queryString.Trim() != string.Empty)
            {
                redirectUrl = redirectUrl.Replace(queryString, string.Empty);
            }

            try
            {
                string message = txtFeedContent.Text.Trim();

                var config = new LinkedInApiConfiguration(LinkedInAppID, LinkedInSecret);
                // get the APIs client
                var api = new LinkedInApi(config);
                AuthorizationAccessToken userToken = api.OAuth2.GetAccessToken(requestCode, redirectUrl);

                if (userToken != null)
                {
                    string   acessToken           = userToken.AccessToken;
                    DateTime authorizationDateUTC = userToken.AuthorizationDateUtc;
                    int?     expiresIn            = userToken.ExpiresIn;

                    AccessTokenController accessTokenController = new AccessTokenController();
                    int addUpdateResult = accessTokenController.AddLinkedInAccessToken(acessToken, authorizationDateUTC, expiresIn);
                }

                UserAuthorization user = new UserAuthorization(userToken.AccessToken);

                PostShareResult postShareResult = api.Companies.Share(
                    user,
                    linkedInCompanyID, new PostShare()
                {
                    Visibility = new Visibility()
                    {
                        Code = "anyone"
                    },
                    Comment = message
                });

                string resultID = hdnSelectedMessageID.Value;
                SocialFeedController feedController = new SocialFeedController();
                UserChoiceInfo       userChoiceInfo = feedController.ConvertToUserChoice(postShareResult.Location, postShareResult.UpdateKey, postShareResult.UpdateUrl, message, resultID);

                int output = feedController.SaveUserChoice(userChoiceInfo);

                if (output == 1)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                ProcessException(ex);
            }
        }

        return(false);
    }
Esempio n. 38
0
        public static LinkedInApiPaginatedResult <AdAnalyticsElement> GetAdsReporting(this LinkedInApi api, OrgEntElements company, DateTime startDate, DateTime?endDate = null)
        {
            StringBuilder apiQueryBuilder = new StringBuilder();

            apiQueryBuilder.Append("/v2/adAnalyticsV2?q=analytics&pivot=CAMPAIGN&timeGranularity=DAILY");

            // Build the startDate param into the query
            apiQueryBuilder.Append($"&dateRange.start.day={startDate.Day}&dateRange.start.month={startDate.Month}&dateRange.start.year={startDate.Year}");

            if (endDate.HasValue)
            {
                // Build the endDate param into the query
                apiQueryBuilder.Append($"&dateRange.end.day={endDate?.Day}&dateRange.end.month={endDate?.Month}&dateRange.end.year={endDate?.Year}");
            }

            apiQueryBuilder.Append($"&companies[0]={company.OrganizationalTarget}");

            string resultJson = api.RawGetJsonQuery(apiQueryBuilder.ToString(), LinkedInApiFactory.GetUserAuthorization());
            LinkedInApiPaginatedResult <AdAnalyticsElement> result = JsonConvert.DeserializeObject <LinkedInApiPaginatedResult <AdAnalyticsElement> >(resultJson);

            return(result);
        }
Esempio n. 39
0
 public void ChecksConfiguration()
 {
     var api = new LinkedInApi(new LinkedInApiConfiguration());
     api.OAuth2.GetAccessToken("hello", "world");
 }
Esempio n. 40
0
        public static LinkedInApiPaginatedResult <CampaignElement> GetAdCampaignsForCompany(this LinkedInApi api, OrgEntElements company)
        {
            string campaignsJson = api.RawGetJsonQuery(
                path: $"/v2/adCampaignsV2?q=search&search.associatedEntity.values[0]={company.OrganizationalTarget}",
                user: LinkedInApiFactory.GetUserAuthorization()
                );

            LinkedInApiPaginatedResult <CampaignElement> campaigns = JsonConvert.DeserializeObject <LinkedInApiPaginatedResult <CampaignElement> >(campaignsJson);

            return(campaigns);
        }
Esempio n. 41
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OAuth2Api"/> class.
 /// </summary>
 /// <param name="linkedInApi">The linked information API.</param>
 public OAuth2Api(LinkedInApi linkedInApi)
     : base(linkedInApi)
 {
 }
Esempio n. 42
0
 public ExploreController(LinkedInApi api, DataService data, LinkedInApiConfiguration apiConfig)
 {
     this.api = api;
     this.data = data;
     this.apiConfig = apiConfig;
 }
 public HomeController(LinkedInApi api, DataService data, LinkedInApiConfiguration apiConfig)
 {
     this.api       = api;
     this.data      = data;
     this.apiConfig = apiConfig;
 }
Esempio n. 44
0
        public async Task <ActionResult> OAuth2(string code, string state, string error, string error_description)
        {
            //2 Step:After logging in, linkedin will redirect back to our site, to the url that whe mentioned in reurn_uri, with Authorize Code or error
            Person          profile         = null;
            LinkedInProfile linkedInProfile = new LinkedInProfile();

            if (!string.IsNullOrEmpty(error) | !string.IsNullOrEmpty(error_description))
            {
                this.ViewBag.Error            = error;
                this.ViewBag.ErrorDescription = error_description;
                return(View());
            }
            else
            {
                //3rd step: If no errors, Get the AccessToken from the AuthorizeCode that linkedin sent back to us
                try
                {
                    // get the APIs client to get the accesstoken
                    LinkedInApi api       = new LinkedInApi(config);
                    var         userToken = await api.OAuth2.GetAccessTokenAsync(code, redirect_uri);

                    //4th step: Use this access token to get the loggedin Member details
                    if (userToken != null && !string.IsNullOrEmpty(userToken.AccessToken))
                    {
                        //1-way to get member profile details: Conventional way  // Not giving all the values for the specified scopes
                        //var Profileclient = new RestClient("https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,title,position,profilePicture,displayImage,profilePicture(displayImage~:playableStreams))") { };
                        //var ProfileAuthRequest = new RestRequest("", Method.GET) { };
                        //ProfileAuthRequest.AddHeader("Authorization", "Bearer " + userToken.AccessToken);
                        //var Profileresponse = Profileclient.Execute(ProfileAuthRequest);

                        //2-way to get member profile details: Through  Sparkle.LinkedInNET plugin
                        var      user        = new UserAuthorization(userToken.AccessToken);
                        string[] acceptlangs = { "en-US" };// need to pass the accepting languages
                        profile = api.Profiles.GetMyProfile(user, acceptlangs, FieldSelector.For <Person>().WithEmailAddress().WithId().WithPictureUrl().WithPositionsTitle().WithSummary().WithFirstName().WithLastName().WithMaidenName().WithPhoneNumbers().WithPublicProfileUrl());


                        //5th step: After getting the profile details, map to our own model
                        if (profile != null)
                        {
                            //Map return values to our own model
                            linkedInProfile.Firstname        = profile.Firstname;
                            linkedInProfile.Lastname         = profile.Lastname;
                            linkedInProfile.MaidenName       = profile.MaidenName;
                            linkedInProfile.EmailAddress     = profile.EmailAddress;
                            linkedInProfile.PictureUrl       = profile.PictureUrl;
                            linkedInProfile.PublicProfileUrl = profile.PublicProfileUrl;
                            linkedInProfile.Summary          = profile.Summary;
                            if (profile.Positions != null)
                            {
                                PersonPosition personpos = profile.Positions.Position.FirstOrDefault() != null?profile.Positions.Position.SingleOrDefault() : new PersonPosition();

                                linkedInProfile.PositionTitle = personpos.Title ?? string.Empty;
                            }
                            if (profile.PhoneNumbers != null)
                            {
                                PhoneNumber phonenum = profile.PhoneNumbers.PhoneNumber.Count > 0 ? profile.PhoneNumbers.PhoneNumber.SingleOrDefault() : new PhoneNumber();
                                linkedInProfile.PhoneNumber = phonenum.Number ?? string.Empty;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                    // throw new HttpRequestException("Request to linkedin Service failed.");
                }
            }

            return(View(linkedInProfile));
        }