protected void AssertProfile(LinkedInProfile connection, String id, String headline, String firstName,
 String lastName, String industry, String standardUrl)
 {
     Assert.AreEqual(id, connection.ID);
     Assert.AreEqual(headline, connection.Headline);
     Assert.AreEqual(firstName, connection.FirstName);
     Assert.AreEqual(lastName, connection.LastName);
     if (!string.IsNullOrEmpty(industry))
         Assert.AreEqual(industry, connection.Industry);
     if (!string.IsNullOrEmpty(standardUrl))
         Assert.AreEqual(standardUrl, connection.StandardProfileUrl);
 }
 protected void AssertProfile(LinkedInProfile profile,
     string id, string headline, string firstName, string lastName, string industry, string pictureUrl,
     string summary, string publicProfileUrl, string standardProfileUrl, string authToken)
 {
     Assert.AreEqual(id, profile.ID);
     Assert.AreEqual(headline, profile.Headline);
     Assert.AreEqual(firstName, profile.FirstName);
     Assert.AreEqual(lastName, profile.LastName);
     Assert.AreEqual(industry, profile.Industry);
     Assert.AreEqual(pictureUrl, profile.PictureUrl);
     Assert.AreEqual(summary, profile.Summary);
     Assert.AreEqual(publicProfileUrl, profile.PublicProfileUrl);
     Assert.AreEqual(standardProfileUrl, profile.StandardProfileUrl);
     Assert.AreEqual(authToken, profile.AuthToken);
 }
 protected void AssertProfile(LinkedInProfile connection, String id, String headline, String firstName,
                              String lastName, String industry, String standardUrl)
 {
     Assert.AreEqual(id, connection.ID);
     Assert.AreEqual(headline, connection.Headline);
     Assert.AreEqual(firstName, connection.FirstName);
     Assert.AreEqual(lastName, connection.LastName);
     if (!string.IsNullOrEmpty(industry))
     {
         Assert.AreEqual(industry, connection.Industry);
     }
     if (!string.IsNullOrEmpty(standardUrl))
     {
         Assert.AreEqual(standardUrl, connection.StandardProfileUrl);
     }
 }
        public void GetUserProfileById()
        {
            mockServer.ExpectNewRequest()
            .AndExpect(UriStartsWith("https://api.linkedin.com/v1/people/id=xO3SEJSVZN:("))
            .AndExpectMethod(HttpMethod.GET)
            .AndRespondWith(JsonResource("Profile"), responseHeaders);

#if NET_4_0 || SILVERLIGHT_5
            LinkedInProfile profile = linkedIn.ProfileOperations.GetUserProfileByIdAsync("xO3SEJSVZN").Result;
#else
            LinkedInProfile profile = linkedIn.ProfileOperations.GetUserProfileById("xO3SEJSVZN");
#endif
            AssertProfile(profile, "xO3SEJSVZN", "Architecte en informatique spécialisé sur les technologies Microsoft .NET",
                          "Bruno", "Baia", "Information Technology and Services", "http://media.linkedin.com/pictureUrl",
                          "Consultant .NET indépendant", "http://www.linkedin.com/in/bbaia", "http://www.linkedin.com/profile", null);
        }
        public virtual object Deserialize(JsonValue json, JsonMapper mapper)
        {
            LinkedInProfile profile = CreateLinkedInProfile();

            profile.ID                 = json.GetValueOrDefault <string>("id"); //sometimes id is null (on posts)
            profile.FirstName          = json.GetValueOrDefault <string>("firstName", String.Empty);
            profile.LastName           = json.GetValueOrDefault <string>("lastName", String.Empty);
            profile.Headline           = json.GetValueOrDefault <string>("headline", String.Empty);
            profile.Industry           = json.GetValueOrDefault <string>("industry", String.Empty);
            profile.PictureUrl         = json.GetValueOrDefault <string>("pictureUrl");
            profile.Summary            = json.GetValueOrDefault <string>("summary", String.Empty);
            profile.PublicProfileUrl   = json.GetValueOrDefault <string>("publicProfileUrl");
            profile.StandardProfileUrl = GetSiteStandardProfileUrl(json);
            profile.AuthToken          = GetAuthToken(json);

            return(profile);
        }
Ejemplo n.º 6
0
        private async Task ShowProfessionalProfile(IDialogContext context, IAwaitable <GetTokenResponse> tokenResponse)
        {
            try
            {
                var token = await tokenResponse;

                List <string> fields = new List <string>()
                {
                    LinkedInConstants.ProfileFields.POSITIONS,
                    LinkedInConstants.ProfileFields.SPECIALTIES
                };

                LinkedInProfile linkedinProfile = await(new LinkedInService().GetProfile(token.Token, fields));

                IMessageActivity professionalProfileMessage = context.MakeMessage();
                professionalProfileMessage.Attachments = new List <Attachment>();

                ReceiptCard professionalProfileCard = new ReceiptCard
                {
                    Title = linkedinProfile.FirstName + " " + linkedinProfile.LastName
                };

                if (null != linkedinProfile.Positions && 0 < linkedinProfile.Positions.Total)
                {
                    professionalProfileCard.Items = new List <ReceiptItem>();

                    linkedinProfile.Positions.Values.ForEach(x =>
                    {
                        professionalProfileCard.Items.Add(new ReceiptItem()
                        {
                            Title    = x.Title + " @ " + x.Company.Name,
                            Subtitle = x.Summary
                        });
                    });
                }

                professionalProfileMessage.Attachments.Add(professionalProfileCard.ToAttachment());

                await context.PostAsync(professionalProfileMessage);
            }
            catch (Exception exception)
            {
                await context.PostAsync(exception.Message);
            }
            ShowOptions(context);
        }
Ejemplo n.º 7
0
        public void TestProfile()
        {
            var employer = _employerAccountsCommand.CreateTestEmployer(0, _organisationsCommand.CreateTestOrganisation(0));

            var profile = new LinkedInProfile
            {
                Id     = LinkedInId,
                UserId = employer.Id,
            };

            _linkedInCommand.UpdateProfile(profile);

            var result = _linkedInAuthenticationCommand.AuthenticateUser(LinkedInId);

            Assert.AreEqual(AuthenticationStatus.Authenticated, result.Status);
            Assert.AreEqual(employer.Id, result.User.Id);
        }
Ejemplo n.º 8
0
        public static LinkedInProfile GetAuthenticatedProfileForLinkedIn(HttpRequestBase request)
        {
            LinkedInProfile result = new LinkedInProfile();

            if (request.QueryString["oauth_verifier"] != null && request.QueryString["oauth_token"] != null)
            {
                string oauthVerifier = request.QueryString["oauth_verifier"];
                string oauthToken    = request.QueryString["oauth_token"];

                if (!string.IsNullOrEmpty(oauthToken) && !string.IsNullOrEmpty(oauthVerifier))
                {
                    IAuthenticator <LinkedInProfile> authenticator = AuthenticatorFactory.Create <LinkedInAuthenticator>(oauthToken);
                    result = authenticator.Authenticate();
                }
            }

            return(result);
        }
Ejemplo n.º 9
0
 public static void MapTo(this LinkedInProfile profile, LinkedInProfileEntity entity)
 {
     entity.userId           = profile.UserId;
     entity.lastUpdatedTime  = profile.LastUpdatedTime;
     entity.firstName        = profile.FirstName;
     entity.lastName         = profile.LastName;
     entity.organisationName = profile.OrganisationName;
     if (profile.Industries == null)
     {
         entity.LinkedInProfileIndustryEntities = new EntitySet <LinkedInProfileIndustryEntity>();
     }
     else
     {
         entity.LinkedInProfileIndustryEntities.AddRange((from i in profile.Industries select new LinkedInProfileIndustryEntity {
             linkedInId = entity.linkedInId, industryId = i.Id
         }));
     }
     ((IHaveLocation)profile).MapTo(entity);
 }
Ejemplo n.º 10
0
        public void TestCreateFullProfile()
        {
            var userId = Guid.NewGuid();

            var profile = new LinkedInProfile
            {
                Id               = LinkedInId,
                UserId           = userId,
                FirstName        = FirstName,
                LastName         = LastName,
                OrganisationName = OrganisationName,
                Industries       = new[] { _industriesQuery.GetIndustry(Industry) },
                Location         = _locationQuery.ResolveLocation(_locationQuery.GetCountry(Country), Location),
            };

            _linkedInCommand.UpdateProfile(profile);
            AssertProfile(profile, _linkedInQuery.GetProfile(LinkedInId));
            AssertProfile(profile, _linkedInQuery.GetProfile(profile.UserId));
        }
Ejemplo n.º 11
0
        public async Task <LinkedInProfile> GetProfile(string AuthorizationToken, List <string> Fields = null)
        {
            try
            {
                if (null == Fields || 0 == Fields.Count)
                {
                    Fields = new List <string>()
                    {
                        LinkedInConstants.ProfileFields.FIRST_NAME,
                        LinkedInConstants.ProfileFields.LAST_NAME,
                        LinkedInConstants.ProfileFields.PICTURE_URL,
                        LinkedInConstants.ProfileFields.NUM_CONNECTIONS,
                        LinkedInConstants.ProfileFields.NUM_CONNECTIONS_CAPPED
                    };
                }
                string basicProfileFields = $":({string.Join(",", Fields.Select(x => x))})";

                string link = $"/v1/people/~{basicProfileFields}?format=json";

                HttpResponseMessage data = null;
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(LinkedInConstants.BASE_API); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthorizationToken);
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    data = await client.GetAsync(link);
                }

                string dataString = await data.Content.ReadAsStringAsync();

                LinkedInProfile linkedInProfile = JsonConvert.DeserializeObject <LinkedInProfile>(dataString);

                return(linkedInProfile);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
Ejemplo n.º 12
0
        void ILinkedInRepository.UpdateProfile(LinkedInProfile profile)
        {
            using (var dc = CreateContext())
            {
                var entity = GetProfileEntity(dc, profile.Id);
                if (entity == null)
                {
                    dc.LinkedInProfileEntities.InsertOnSubmit(profile.Map());
                }
                else
                {
                    dc.CheckDeleteLocation(profile, entity);
                    if (entity.LinkedInProfileIndustryEntities != null && entity.LinkedInProfileIndustryEntities.Count > 0)
                    {
                        dc.LinkedInProfileIndustryEntities.DeleteAllOnSubmit(entity.LinkedInProfileIndustryEntities);
                    }
                    profile.MapTo(entity);
                }

                dc.SubmitChanges();
            }
        }
Ejemplo n.º 13
0
        public void TestUpdateFullProfile()
        {
            var profile = new LinkedInProfile
            {
                Id               = LinkedInId,
                UserId           = Guid.NewGuid(),
                FirstName        = FirstName,
                LastName         = LastName,
                OrganisationName = OrganisationName,
                Industries       = new[] { _industriesQuery.GetIndustry(Industry) },
                Location         = _locationQuery.ResolveLocation(_locationQuery.GetCountry(Country), Location),
            };

            _linkedInCommand.UpdateProfile(profile);
            AssertProfile(profile, _linkedInQuery.GetProfile(LinkedInId));
            AssertProfile(profile, _linkedInQuery.GetProfile(profile.UserId));

            profile.UserId           = Guid.NewGuid();
            profile.FirstName        = OtherFirstName;
            profile.LastName         = OtherLastName;
            profile.OrganisationName = OtherOrganisationName;
            profile.Industries       = new[] { _industriesQuery.GetIndustry(Industry), _industriesQuery.GetIndustry(OtherIndustry) };
            profile.Location         = _locationQuery.ResolveLocation(_locationQuery.GetCountry(Country), OtherLocation);

            _linkedInCommand.UpdateProfile(profile);
            AssertProfile(profile, _linkedInQuery.GetProfile(LinkedInId));
            AssertProfile(profile, _linkedInQuery.GetProfile(profile.UserId));

            profile.FirstName        = null;
            profile.LastName         = null;
            profile.OrganisationName = null;
            profile.Industries       = null;
            profile.Location         = null;

            _linkedInCommand.UpdateProfile(profile);
            AssertProfile(profile, _linkedInQuery.GetProfile(LinkedInId));
            AssertProfile(profile, _linkedInQuery.GetProfile(profile.UserId));
        }
Ejemplo n.º 14
0
        public void GetAccessToken()
        {
            LinkedInProfile objProfile = new LinkedInProfile();

            LinkedInProfile.UserProfile objUserProfile = new LinkedInProfile.UserProfile();
            LinkedInHelper liHelper       = new LinkedInHelper();
            User           user           = (User)Session["LoggedUser"];
            string         oauth_token    = Request.QueryString["oauth_token"];
            string         oauth_verifier = Request.QueryString["oauth_verifier"];

            try
            {
                if (oauth_token != null && oauth_verifier != null)
                {
                    try
                    {
                        _oauth.Token = oauth_token;
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.StackTrace);
                    }
                    try
                    {
                        _oauth.TokenSecret = Session["reuqestTokenSecret"].ToString();
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.StackTrace);
                    }
                    try
                    {
                        _oauth.Verifier = oauth_verifier;
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.StackTrace);
                    }
                    try
                    {
                        _oauth.AccessTokenGet(oauth_token);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.StackTrace);
                    }

                    // Update Access Token in DB
                    try
                    {
                        int res = UpdateLDToken(user.Id.ToString(), _oauth.Token);
                    }
                    catch { };
                    //***********************

                    Session.Remove("oauth_token");
                    Session.Remove("oauth_TokenSecret");

                    try
                    {
                        objUserProfile = objProfile.GetUserProfile(_oauth);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.StackTrace);
                    }
                    try
                    {
                        liHelper.GetLinkedInUserProfile(objUserProfile, _oauth, user);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.StackTrace);
                    }
                    try
                    {
                        // liHelper.getLinkedInNetworkUpdate(_oauth,user);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.StackTrace);
                    }
                    Session["LinkedInUser"] = _oauth;
                    Session["datatable"]    = null;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.StackTrace);
            }
        }
        public IHttpActionResult AddLinkedInAccount(LinkedInManager LinkedInManager)
        {
            string          ret        = "";
            string          UserId     = LinkedInManager.UserId;
            oAuthLinkedIn   _oauth     = new oAuthLinkedIn();
            LinkedInProfile objProfile = new LinkedInProfile();

            Domain.Socioboard.Domain.GroupProfile grpProfile = new Domain.Socioboard.Domain.GroupProfile();
            try
            {
                _oauth.ConsumerKey = ConfigurationManager.AppSettings["LinkedinApiKey"];
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                logger.Error(ex.Message);
            }

            try
            {
                _oauth.ConsumerSecret = ConfigurationManager.AppSettings["LinkedinSecretKey"];
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                logger.Error(ex.Message);
            }
            string access_token_Url      = "https://www.linkedin.com/uas/oauth2/accessToken";
            string access_token_postData = "grant_type=authorization_code&code=" + LinkedInManager.Code + "&redirect_uri=" + System.Web.HttpUtility.UrlEncode(ConfigurationManager.AppSettings["LinkedinCallBackURL"]) + "&client_id=" + ConfigurationManager.AppSettings["LinkedinApiKey"] + "&client_secret=" + ConfigurationManager.AppSettings["LinkedinSecretKey"];

            LinkedInProfile.UserProfile objUserProfile = new LinkedInProfile.UserProfile();
            string token     = _oauth.APIWebRequestAccessToken("POST", access_token_Url, access_token_postData);
            var    oathtoken = JObject.Parse(token);

            _oauth.Token = oathtoken["access_token"].ToString().TrimStart('"').TrimEnd('"');
            #region Get linkedin Profile data from Api
            try
            {
                _oauth.ConsumerKey = ConfigurationManager.AppSettings["LinkedinApiKey"];
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                logger.Error(ex.Message);
            }

            try
            {
                _oauth.ConsumerSecret = ConfigurationManager.AppSettings["LinkedinSecretKey"];
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                logger.Error(ex.Message);
            }
            try
            {
                objUserProfile = objProfile.GetUserProfile(_oauth);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                logger.Error(ex.Message);
            }
            #endregion
            dynamic data = objUserProfile;
            try
            {
                #region LinkedInAccount
                objLinkedInAccount.UserId         = Guid.Parse(UserId);
                objLinkedInAccount.LinkedinUserId = data.id.ToString();
                try
                {
                    objLinkedInAccount.EmailId = data.email.ToString();
                }
                catch (Exception ex)
                {
                    logger.Error(ex.StackTrace);
                }
                objLinkedInAccount.LinkedinUserName = data.first_name.ToString() + data.last_name.ToString();
                objLinkedInAccount.OAuthToken       = _oauth.Token;
                objLinkedInAccount.OAuthSecret      = _oauth.TokenSecret;
                objLinkedInAccount.OAuthVerifier    = _oauth.Verifier;
                try
                {
                    objLinkedInAccount.ProfileImageUrl = data.picture_url.ToString();
                }
                catch (Exception ex)
                {
                    logger.Error(ex.StackTrace);
                }
                try
                {
                    objLinkedInAccount.ProfileUrl = data.profile_url.ToString();
                }
                catch (Exception ex)
                {
                    logger.Error(ex.StackTrace);
                }
                #endregion
                #region SocialProfiles
                try
                {
                    objLinkedInAccount.Connections = data.connections;
                    objLinkedInAccount.IsActive    = true;
                    objSocialProfile.UserId        = Guid.Parse(UserId);
                    objSocialProfile.ProfileType   = "linkedin";
                    objSocialProfile.ProfileId     = data.id.ToString();
                    objSocialProfile.ProfileStatus = 1;
                    objSocialProfile.ProfileDate   = DateTime.Now;
                    objSocialProfile.Id            = Guid.NewGuid();
                }
                catch (Exception ex)
                {
                    logger.Error(ex.Message);
                }
                #endregion SocialProfiles
                #region Add TeamMemberProfile
                try
                {
                    //Domain.Socioboard.Domain.Team objTeam = objTeamRepository.GetTeamByGroupId(Guid.Parse(LinkedInManager.GroupId));
                    //objTeamMemberProfile = new Domain.Socioboard.Domain.TeamMemberProfile();
                    //objTeamMemberProfile.Id = Guid.NewGuid();
                    //objTeamMemberProfile.TeamId = objTeam.Id;
                    //objTeamMemberProfile.Status = 1;
                    //objTeamMemberProfile.ProfileType = "linkedin";
                    //objTeamMemberProfile.StatusUpdateDate = DateTime.Now;
                    //objTeamMemberProfile.ProfileId = objLinkedInAccount.LinkedinUserId;
                    //objTeamMemberProfile.ProfileName = objLinkedInAccount.LinkedinUserName;
                    //objTeamMemberProfile.ProfilePicUrl = objLinkedInAccount.ProfileImageUrl;

                    grpProfile.Id           = Guid.NewGuid();
                    grpProfile.GroupId      = Guid.Parse(LinkedInManager.GroupId);
                    grpProfile.GroupOwnerId = objLinkedInAccount.UserId;
                    grpProfile.ProfileId    = objLinkedInAccount.LinkedinUserId;
                    grpProfile.ProfileType  = "linkedin";
                    grpProfile.ProfileName  = objLinkedInAccount.LinkedinUserName;
                    grpProfile.EntryDate    = DateTime.UtcNow;
                    //grpProfileRepo.AddGroupProfile(grpProfile);
                }
                catch (Exception ex)
                {
                    logger.Error(ex.Message);
                }
                #endregion
            }
            catch (Exception ex)
            {
                logger.Error(ex.StackTrace);
            }
            try
            {
                if (!objLinkedInAccountRepository.checkLinkedinUserExists(objLinkedInAccount.LinkedinUserId, Guid.Parse(UserId)))
                {
                    objLinkedInAccountRepository.addLinkedinUser(objLinkedInAccount);
                    ret = "LinkedIn Account Added Successfully";
                }
                else
                {
                    ret = "LinkedIn Account Already Exist";
                }
                if (!objSocialProfilesRepository.checkUserProfileExist(objSocialProfile))
                {
                    objSocialProfilesRepository.addNewProfileForUser(objSocialProfile);
                    grpProfileRepo.AddGroupProfile(grpProfile);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.StackTrace);
            }
            return(Ok(ret));
        }
Ejemplo n.º 16
0
 void ILinkedInCommand.UpdateProfile(LinkedInProfile profile)
 {
     Prepare(profile);
     profile.Validate();
     _repository.UpdateProfile(profile);
 }
Ejemplo n.º 17
0
        public string AddLinkedinAccount(string oauth_token, string oauth_verifier, string reuqestTokenSecret, string consumerKey, string consumerSecret, string UserId, string GroupId)
        {
            try
            {
                logger.Error("AddLinkedinAccount()");

                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;

                string                      ret            = string.Empty;
                LinkedInProfile             objProfile     = new LinkedInProfile();
                LinkedInProfile.UserProfile objUserProfile = new LinkedInProfile.UserProfile();
                objSocialProfile = new Domain.Myfashion.Domain.SocialProfile();
                oAuthLinkedIn _oauth = new oAuthLinkedIn();
                objLinkedInAccount = new LinkedInAccount();
                #region Get linkedin Profile data from Api
                try
                {
                    _oauth.ConsumerKey = consumerKey;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    logger.Error(ex.Message);
                }
                try
                {
                    _oauth.ConsumerSecret = consumerSecret;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    logger.Error(ex.Message);
                }
                try
                {
                    _oauth.Token = oauth_token;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    logger.Error(ex.Message);
                }
                try
                {
                    _oauth.TokenSecret = reuqestTokenSecret;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    logger.Error(ex.Message);
                }
                try
                {
                    _oauth.Verifier = oauth_verifier;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    logger.Error(ex.Message);
                }
                try
                {
                    _oauth.AccessTokenGet(oauth_token);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    logger.Error(ex.Message);
                }
                try
                {
                    objUserProfile = objProfile.GetUserProfile(_oauth);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    logger.Error(ex.Message);
                }
                #endregion
                dynamic data = objUserProfile;
                try
                {
                    #region LinkedInAccount
                    objLinkedInAccount.UserId         = Guid.Parse(UserId);
                    objLinkedInAccount.LinkedinUserId = data.id.ToString();
                    try
                    {
                        objLinkedInAccount.EmailId = data.email.ToString();
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.StackTrace);
                    }
                    objLinkedInAccount.LinkedinUserName = data.first_name.ToString() + data.last_name.ToString();
                    objLinkedInAccount.OAuthToken       = _oauth.Token;
                    objLinkedInAccount.OAuthSecret      = _oauth.TokenSecret;
                    objLinkedInAccount.OAuthVerifier    = _oauth.Verifier;
                    try
                    {
                        objLinkedInAccount.ProfileImageUrl = data.picture_url.ToString();
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.StackTrace);
                    }
                    try
                    {
                        objLinkedInAccount.ProfileUrl = data.profile_url.ToString();
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.StackTrace);
                    }
                    #endregion
                    #region SocialProfiles
                    try
                    {
                        objLinkedInAccount.Connections = data.connections;
                        objLinkedInAccount.IsActive    = true;
                        objSocialProfile.UserId        = Guid.Parse(UserId);
                        objSocialProfile.ProfileType   = "linkedin";
                        objSocialProfile.ProfileId     = data.id.ToString();
                        objSocialProfile.ProfileStatus = 1;
                        objSocialProfile.ProfileDate   = DateTime.Now;
                        objSocialProfile.Id            = Guid.NewGuid();
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.Message);
                    }
                    #endregion SocialProfiles
                    #region Add TeamMemberProfile
                    try
                    {
                        Domain.Myfashion.Domain.Team objTeam = objTeamRepository.GetTeamByGroupId(Guid.Parse(GroupId));
                        objTeamMemberProfile                  = new Domain.Myfashion.Domain.TeamMemberProfile();
                        objTeamMemberProfile.Id               = Guid.NewGuid();
                        objTeamMemberProfile.TeamId           = objTeam.Id;
                        objTeamMemberProfile.Status           = 1;
                        objTeamMemberProfile.ProfileType      = "linkedin";
                        objTeamMemberProfile.StatusUpdateDate = DateTime.Now;
                        objTeamMemberProfile.ProfileId        = objLinkedInAccount.LinkedinUserId;
                        objTeamMemberProfile.ProfileName      = objLinkedInAccount.LinkedinUserName;
                        objTeamMemberProfile.ProfilePicUrl    = objLinkedInAccount.ProfileImageUrl;
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.Message);
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    logger.Error(ex.StackTrace);
                }
                try
                {
                    if (!objLinkedInAccountRepository.checkLinkedinUserExists(objLinkedInAccount.LinkedinUserId, Guid.Parse(UserId)))
                    {
                        objLinkedInAccountRepository.addLinkedinUser(objLinkedInAccount);
                        ret = "LinkedIn Account Added Successfully";
                    }
                    else
                    {
                        ret = "LinkedIn Account Already Exist";
                    }
                    if (!objSocialProfilesRepository.checkUserProfileExist(objSocialProfile))
                    {
                        objSocialProfilesRepository.addNewProfileForUser(objSocialProfile);
                    }
                    if (!objTeamMemberProfileRepository.checkTeamMemberProfile(objTeamMemberProfile.TeamId, objLinkedInAccount.LinkedinUserId))
                    {
                        objTeamMemberProfileRepository.addNewTeamMember(objTeamMemberProfile);
                    }

                    #region Add LinkedIn Feeds
                    LinkedInNetwork objln = new LinkedInNetwork();
                    List <LinkedInNetwork.Network_Updates> userUPdate = objln.GetNetworkUpdates(_oauth, 20);
                    foreach (var item in userUPdate)
                    {
                        try
                        {
                            objLinkedInFeed            = new Domain.Myfashion.Domain.LinkedInFeed();
                            objLinkedInFeed.Feeds      = item.Message;
                            objLinkedInFeed.FromId     = item.PersonId;
                            objLinkedInFeed.FromName   = item.PersonFirstName + " " + item.PersonLastName;
                            objLinkedInFeed.FeedsDate  = Convert.ToDateTime(item.DateTime);
                            objLinkedInFeed.EntryDate  = DateTime.Now;
                            objLinkedInFeed.ProfileId  = objLinkedInAccount.LinkedinUserId;
                            objLinkedInFeed.Type       = item.UpdateType;
                            objLinkedInFeed.UserId     = Guid.Parse(UserId);
                            objLinkedInFeed.FromPicUrl = item.PictureUrl;
                            objLinkedInFeed.ImageUrl   = item.ImageUrl;
                            objLinkedInFeed.FromUrl    = item.url;
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex.StackTrace);
                        }
                        if (!objLinkedInFeedRepository.checkLinkedInFeedExists(objLinkedInFeed.FeedId, Guid.Parse(UserId)))
                        {
                            objLinkedInFeedRepository.addLinkedInFeed(objLinkedInFeed);
                        }
                    }
                    #endregion


                    #region Add LinkedIn UserUpdates
                    GlobusLinkedinLib.App.Core.LinkedInUser l = new GlobusLinkedinLib.App.Core.LinkedInUser();
                    List <Domain.Myfashion.Domain.LinkedIn_Update_Messages> lst_Messages = l.GetUserUpdateNew(_oauth, objLinkedInAccount.LinkedinUserId, 10);
                    foreach (var item_Messages in lst_Messages)
                    {
                        try
                        {
                            objLinkedInMessage                 = new Domain.Myfashion.Domain.LinkedInMessage();
                            objLinkedInMessage.Id              = Guid.NewGuid();
                            objLinkedInMessage.Message         = item_Messages.Message;
                            objLinkedInMessage.ProfileId       = item_Messages.ProfileId;
                            objLinkedInMessage.ProfileName     = item_Messages.ProfileName;
                            objLinkedInMessage.CreatedDate     = Convert.ToDateTime(item_Messages.CreatedDate);
                            objLinkedInMessage.EntryDate       = DateTime.Now;
                            objLinkedInMessage.Type            = item_Messages.Type;
                            objLinkedInMessage.UserId          = Guid.Parse(UserId);
                            objLinkedInMessage.ImageUrl        = item_Messages.ImageUrl;
                            objLinkedInMessage.FeedId          = item_Messages.FeedId;
                            objLinkedInMessage.ProfileUrl      = item_Messages.ProfileUrl;
                            objLinkedInMessage.Comments        = item_Messages.Comments;
                            objLinkedInMessage.Likes           = item_Messages.Likes;
                            objLinkedInMessage.ProfileImageUrl = item_Messages.ProfileImageUrl;
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex.StackTrace);
                        }
                        if (!objLinkedInMessageRepository.checkLinkedInMessageExists(objLinkedInAccount.LinkedinUserId, objLinkedInMessage.FeedId, Guid.Parse(UserId)))
                        {
                            objLinkedInMessageRepository.addLinkedInMessage(objLinkedInMessage);
                        }
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    logger.Error(ex.StackTrace);
                }
                return("");
            }
            catch (Exception ex)
            {
                logger.Error(ex.StackTrace);
                return("");
            }
        }
Ejemplo n.º 18
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));
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            try
            {
                LinkedInServiceProvider linkedInServiceProvider = new LinkedInServiceProvider(LinkedInApiKey, LinkedInApiSecret);

#if NET_4_0
                /* OAuth 'dance' */

                // Authentication using Out-of-band/PIN Code Authentication
                Console.Write("Getting request token...");
                NameValueCollection parameters = new NameValueCollection();
                //parameters.Add("scope", "r_basicprofile r_emailaddress");
                OAuthToken oauthToken = linkedInServiceProvider.OAuthOperations.FetchRequestTokenAsync("oob", parameters).Result;
                Console.WriteLine("Done");

                string authenticateUrl = linkedInServiceProvider.OAuthOperations.BuildAuthorizeUrl(oauthToken.Value, null);
                Console.WriteLine("Redirect user for authentication: " + authenticateUrl);
                Process.Start(authenticateUrl);
                Console.WriteLine("Enter PIN Code from LinkedIn authorization page:");
                string pinCode = Console.ReadLine();

                Console.Write("Getting access token...");
                AuthorizedRequestToken requestToken     = new AuthorizedRequestToken(oauthToken, pinCode);
                OAuthToken             oauthAccessToken = linkedInServiceProvider.OAuthOperations.ExchangeForAccessTokenAsync(requestToken, null).Result;
                Console.WriteLine("Done");

                /* API */

                ILinkedIn linkedIn = linkedInServiceProvider.GetApi(oauthAccessToken.Value, oauthAccessToken.Secret);

                LinkedInProfile profile = linkedIn.ProfileOperations.GetUserProfileAsync().Result;
                Console.WriteLine("Authenticated user is " + profile.FirstName + " " + profile.LastName);

                // Use step by step debugging

/*
 *              LinkedInProfile profileById = linkedIn.ProfileOperations.GetUserProfileByIdAsync("x9HPDDi8DL").Result;
 *              LinkedInProfile profileByPublicUrl = linkedIn.ProfileOperations.GetUserProfileByPublicUrlAsync("http://www.linkedin.com/in/bbaia").Result;
 *              LinkedInProfiles connections = linkedIn.ConnectionOperations.GetConnectionsAsync().Result; // Requires 'r_network' permission
 *              NetworkStatistics statistics = linkedIn.ConnectionOperations.GetNetworkStatisticsAsync().Result; // Requires 'rw_nus' permission
 *              GroupMemberships groups = linkedIn.GroupOperations.GetGroupMembershipsAsync().Result; // Requires 'rw_groups' permission
 */
                // Consume LinkedIn endpoints that are not covered by the API binding

                string    stringResult = linkedIn.RestOperations.GetForObjectAsync <string>("company-search?keywords=SpringSource&format=json").Result;
                JsonValue jsonResult   = linkedIn.RestOperations.GetForObjectAsync <JsonValue>("job-search?job-title=LinkedIn&country-code=FR&format=json").Result;
            }
            catch (AggregateException ae)
            {
                ae.Handle(ex =>
                {
                    // TODO: Update after error handler implementation
                    if (ex is Spring.Rest.Client.HttpResponseException)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(((Spring.Rest.Client.HttpResponseException)ex).GetResponseBodyAsString());
                        return(true);
                    }
                    return(false);
                });
            }
#else
                /* OAuth 'dance' */

                // Authentication using Out-of-band/PIN Code Authentication
                Console.Write("Getting request token...");
                OAuthToken oauthToken = linkedInServiceProvider.OAuthOperations.FetchRequestToken("oob", null);
                Console.WriteLine("Done");

                string authenticateUrl = linkedInServiceProvider.OAuthOperations.BuildAuthorizeUrl(oauthToken.Value, null);
                Console.WriteLine("Redirect user for authentication: " + authenticateUrl);
                Process.Start(authenticateUrl);
                Console.WriteLine("Enter PIN Code from LinkedIn authorization page:");
                string pinCode = Console.ReadLine();

                Console.Write("Getting access token...");
                AuthorizedRequestToken requestToken = new AuthorizedRequestToken(oauthToken, pinCode);
                OAuthToken oauthAccessToken         = linkedInServiceProvider.OAuthOperations.ExchangeForAccessToken(requestToken, null);
                Console.WriteLine("Done");

                /* API */

                ILinkedIn linkedIn = linkedInServiceProvider.GetApi(oauthAccessToken.Value, oauthAccessToken.Secret);

                LinkedInProfile profile = linkedIn.ProfileOperations.GetUserProfile();
                Console.WriteLine("Authenticated user is " + profile.FirstName + " " + profile.LastName);

                // Use step by step debugging

/*
 *              LinkedInProfile profileById = linkedIn.ProfileOperations.GetUserProfileById("xO3SEJSVZN");
 *              LinkedInProfile profileByPublicUrl = linkedIn.ProfileOperations.GetUserProfileByPublicUrl("http://www.linkedin.com/in/bbaia");
 *              LinkedInProfiles connections = linkedIn.ConnectionOperations.GetConnections(); // Requires 'r_network' permission
 *              NetworkStatistics statistics = linkedIn.ConnectionOperations.GetNetworkStatistics(); // Requires 'rw_nus' permission
 */
                // Consume LinkedIn endpoints that are not covered by the API binding

/*
 *              string stringResult = linkedIn.RestOperations.GetForObject<string>("company-search?keywords=SpringSource&format=json");
 *              JsonValue jsonResult = linkedIn.RestOperations.GetForObject<JsonValue>("job-search?job-title=LinkedIn&country-code=FR&format=json");
 */
            }