Exemplo n.º 1
0
        public void GetUserInfo(params string[] fields)
        {
            string baseUrl = "https://api.linkedin.com/v1/people/~:(" + string.Join(",", fields) + ")";
            Dictionary <string, string> headers = new Dictionary <string, string> ();

            headers.Add("Authorization", "Bearer " + AccessToken);
            headers.Add("x-li-format", "json");

            WebRequest.Get(baseUrl, (res) => {
                if (res.isDone)
                {
                    LinkedInUser user = new LinkedInUser(res.text);
                    WebRequest.GetTexture(user.PictureUrl, (res2) => {
                        if (res2.isDone)
                        {
                            user.Picture = ((DownloadHandlerTexture)res2).texture;
                        }
                        else
                        {
                            //well, profile picture wasn't downloaded. no biggy.
                        }
                        Action <User> OnUserInfoHandler = OnUserInfo;
                        if (OnUserInfoHandler != null)
                        {
                            OnUserInfoHandler(user);
                        }
                    });
                }
                else
                {
                    //something went wrong here.
                }
            }, headers);
        }
Exemplo n.º 2
0
 public bool SaveAccountDeatils(OAuthTokens tokens, string userId, string Email)
 {
     try
     {
         AccessDetails accessToken = new AccessDetails()
         {
             AccessToken = tokens.access_token
         };
         LinkedInUser profile       = GetUserprofile(accessToken);
         SocialMedia  socialDetails = new SocialMedia()
         {
             UserId        = userId,
             Provider      = SocialMediaProviders.LinkedIn.ToString(),
             AccessDetails = new AccessDetails {
                 AccessToken = tokens.access_token
             },
             ProfilepicUrl = profile.pictureUrl,
             SMId          = profile.id,
             Status        = true,
             UserName      = profile.emailAddress,
             Followers     = profile.numConnections,
             AccSettings   = new AccSettings()
         };
         socialDetails.AccSettings.UserManagement.Add(new UserManagement {
             Email = Email, userId = userId, Role = "Owner"
         });
         _socialMedia.Add(socialDetails);
         _unitOfWork.Commit();
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Exemplo n.º 3
0
        public string CheckUserAlreadyCredits(int ProjectId, int userid)
        {
            LinkedInUser linkRequest = (from l in context.LinkedInUsers
                                        where l.id == ProjectId && l.userId == userid
                                        select l).FirstOrDefault();

            if (linkRequest != null)
            {
                return(linkRequest.userId.ToString());
            }
            return(string.Empty);
        }
Exemplo n.º 4
0
        public async Task <ActionResult> LoginLinkedIn(string state, string code)
        {
            if (!String.IsNullOrEmpty(Request.QueryString?["error"]))
            {
                string errorMessage = $"{Request.QueryString?["error"]} {Request.QueryString?["error_description"]}";
                Trace.TraceWarning($"Login failed: Invalid login request from LinkedIn sign in. {errorMessage}");
                return(RedirectToAction("ExternalLoginFailure"));
            }

            if (String.IsNullOrEmpty(state) || String.IsNullOrEmpty(code))
            {
                Trace.TraceWarning($"Login failed: Improper state or code provided. state: {state}, code: {code}");
                return(RedirectToAction("ExternalLoginFailure"));
            }
            string returnUrl = _stateCache.Value.Get(state) as string;

            if (returnUrl == null)
            {
                Trace.TraceWarning($"Login failed: Failed to retreive login state from database. state: {state}, code: {code}");
                return(RedirectToAction("ExternalLoginFailure"));
            }

            try
            {
                IncomingApiDataResponse <LinkedInTokenResponse> tokenResponse = await LinkedInApiService.GetToken(LocalRedirectUrl, code).ConfigureAwait(false);

                LinkedInUser user = await _userService.InitializeUserFromLinkedIn(tokenResponse.Data).ConfigureAwait(false);

                List <Claim> claims = new List <Claim>()
                {
                    new Claim(ClaimTypes.Name, $"{user.User.FirstName} {user.User.LastName}"),
                    new Claim(ClaimTypes.Email, user.User.Email),
                    new Claim(ClaimTypes.NameIdentifier, user.LinkedInId),
                    new Claim(AppConstants.CustomClaims.IsdUserId, user.Id.ToString())
                };
                if (!String.IsNullOrEmpty(user.ProfileImageUrl))
                {
                    claims.Add(new Claim(AppConstants.CustomClaims.UserImageUrl, user.ProfileImageUrl));
                }
                ClaimsIdentity identity    = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
                IOwinContext   authContext = Request.GetOwinContext();
                authContext.Authentication.SignIn(new AuthenticationProperties {
                    IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddSeconds(tokenResponse.Data.expires_in)
                }, identity);
                return(RedirectToLocal(returnUrl));
            }
            catch (LinkedInApiResponseException ex)
            {
                Trace.TraceError(ex.ToString(), ex);
                return(RedirectToAction("ExternalLoginFailure"));
            }
        }
Exemplo n.º 5
0
        public override void PostScheduleMessage(dynamic data)
        {
            try
            {
                LinkedInAccountRepository linkedinrepo = new LinkedInAccountRepository();

                LinkedInAccount linkedinaccount = linkedinrepo.getLinkedinAccountDetailsById(data.ProfileId);

                Console.WriteLine("=========================================================================");

                //   IEnumerable<LinkedInAccount> lstlinkedinaccount = linkedinrepo.getLinkedinAccountDetailsById(data.ProfileId);

                //foreach (LinkedInAccount item in lstlinkedinaccount)
                //{
                //    linkedinaccount = item;
                //    break;

                //}

                oAuthLinkedIn Linkedin_oauth = new oAuthLinkedIn();
                Linkedin_oauth.ConsumerKey    = System.Configuration.ConfigurationSettings.AppSettings["LiApiKey"].ToString();
                Linkedin_oauth.ConsumerSecret = System.Configuration.ConfigurationSettings.AppSettings["LiSecretKey"].ToString();
                Linkedin_oauth.FirstName      = linkedinaccount.LinkedinUserName;
                Linkedin_oauth.Token          = linkedinaccount.OAuthToken;
                Linkedin_oauth.TokenSecret    = linkedinaccount.OAuthSecret;
                Linkedin_oauth.Verifier       = linkedinaccount.OAuthVerifier;
                LinkedInUser linkeduser = new LinkedInUser();
                var          response   = linkeduser.SetStatusUpdate(Linkedin_oauth, data.ShareMessage);
                Console.WriteLine("Message post on linkedin for Id :" + linkedinaccount.LinkedinUserId + " and Message: " + data.ShareMessage);
                Console.WriteLine("=============================================================");
                ScheduledMessageRepository schrepo = new ScheduledMessageRepository();
                ScheduledMessage           schmsg  = new ScheduledMessage();
                schmsg.Id           = data.Id;
                schmsg.ProfileId    = data.ProfileId;
                schmsg.ProfileType  = "linkedin";
                schmsg.Status       = true;
                schmsg.UserId       = data.UserId;
                schmsg.ShareMessage = data.ShareMessage;
                schmsg.ScheduleTime = data.ScheduleTime;
                schmsg.ClientTime   = data.ClientTime;
                schmsg.CreateTime   = data.CreateTime;
                schmsg.PicUrl       = data.PicUrl;

                schrepo.updateMessage(data.Id);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
Exemplo n.º 6
0
        public async Task AddAsync(LInkedInUserAuth entity)
        {
            PasswordResult passwordResult = PasswordHash.Encrypt(entity.Password);
            LinkedInUser   linkedInUser   = new LinkedInUser();

            linkedInUser.Password           = passwordResult.Signature;
            linkedInUser.Salt               = passwordResult.Salt;
            linkedInUser.LIFirstName        = entity.LIFirstName;
            linkedInUser.LILastName         = entity.LILastName;
            linkedInUser.LIRegistrationDate = entity.LIRegistrationDate;
            linkedInUser.IsActive           = entity.IsActive;
            linkedInUser.LIMobileNumber     = entity.LIMobileNumber;
            linkedInUser.LIEmailId          = entity.LIEmailId;
            await Uow.RegisterNewAsync(linkedInUser);

            await Uow.CommitAsync();
        }
Exemplo n.º 7
0
        public LinkedInUser GetUserprofile(AccessDetails Token)
        {
            try
            {
                //var token = Session["FacebookAccessToken"];

                var request = new RestRequest("/v1/people/~:(id,num-connections,picture-url,public-profile-url,email-address)", Method.GET);
                request.AddParameter("format", "json");
                request.AddParameter("oauth2_access_token", Token.AccessToken);
                var response = WebServiceHelper.WebRequest(request, ApiURL);
                JsonDeserializer deserial = new JsonDeserializer();
                LinkedInUser     result   = deserial.Deserialize <LinkedInUser>(response);
                return(result);
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 8
0
        public async Task <LinkedInUser> InitializeUserFromLinkedIn(LinkedInTokenResponse token)
        {
            LinkedInApiService api = new LinkedInApiService(token.access_token);
            IncomingApiDataResponse <LinkedInPersonResponse> personResponse = await api.GetPerson(token.access_token).ConfigureAwait(false);

            LinkedInUser linkedInUser = (await _uow.LinkedInUserRepository.GetAsync(lu => lu.LinkedInId == personResponse.Data.id).ConfigureAwait(false)).FirstOrDefault();

            if (linkedInUser == null)
            {
                linkedInUser = new LinkedInUser
                {
                    LinkedInId = personResponse.Data.id,
                };
                User user = new User();
                _uow.UserRepository.Insert(user);
                linkedInUser.User = user;
                _uow.LinkedInUserRepository.Insert(linkedInUser);
            }

            linkedInUser.ProfileImageUrl   = personResponse.Data.pictureUrl;
            linkedInUser.ProfileRequestUrl = personResponse.Data.publicProfileUrl;
            linkedInUser.Token             = token.access_token;
            linkedInUser.TokenExpires      = DateTime.UtcNow.AddSeconds(token.expires_in);

            linkedInUser.User.Email     = personResponse.Data.emailAddress;
            linkedInUser.User.FirstName = personResponse.Data.firstName;
            linkedInUser.User.LastName  = personResponse.Data.lastname;
            linkedInUser.User.ImageUrl  = personResponse.Data.pictureUrl;
            if (String.IsNullOrEmpty(linkedInUser.User.Username) &&
                !String.IsNullOrEmpty(personResponse.Data.emailAddress) &&
                (await _uow.UserRepository.GetAsync(u => u.Username == personResponse.Data.emailAddress).ConfigureAwait(false)) == null)
            {
                linkedInUser.User.Username = personResponse.Data.emailAddress;
            }
            else
            {
                linkedInUser.User.Username = linkedInUser.LinkedInId;
            }

            await _uow.SaveChangesAsync().ConfigureAwait(false);

            return(linkedInUser);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Add credit
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="LikeOrDisLike"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        #region code for credit
        public string AddCreditRequest(int projectId, string LikeOrDisLike, string UserId)
        {
            string ReturnString = "Success";

            try
            {
                if (string.IsNullOrEmpty(CheckUserAlreadyCredits(projectId, Convert.ToInt32(UserId))))
                {
                    int userID = Convert.ToInt32(UserId);

                    var details = (from r in context.RegisterUsers
                                   where r.Id == userID
                                   select r).FirstOrDefault();
                    LinkedInUser l = new LinkedInUser();
                    l.id         = projectId;
                    l.userId     = userID;
                    l.FirstName  = details.UserFirstName;
                    l.LastName   = details.UserLastName;
                    l.Email      = details.Email;
                    l.CreditM    = false;
                    l.IsApproved = false;
                    context.LinkedInUsers.Add(l);
                    context.SaveChanges();
                    ReturnString = "submitted";
                    //SendEmailForLikeAndComment(projectId, Convert.ToInt32(UserId), string.Empty);
                }
                else
                {
                    ReturnString = "AlreadyRequested";
                }
            }
            catch
            {
                ReturnString = "Fail";
            }
            return(ReturnString);
        }
Exemplo n.º 10
0
        public string AddCreditRequest(int projectId, string LikeOrDisLike, string UserId)
        {
            string ReturnString = "Success";
            try
            {
                if (string.IsNullOrEmpty(CheckUserAlreadyCredits(projectId, Convert.ToInt32(UserId))))
                {

                    int userID = Convert.ToInt32(UserId);

                    var details = (from r in context.RegisterUsers
                                   where r.Id == userID
                                   select r).FirstOrDefault();
                    LinkedInUser l = new LinkedInUser();
                    l.id = projectId;
                    l.userId = userID;
                    l.FirstName = details.UserFirstName;
                    l.LastName = details.UserLastName;
                    l.Email = details.Email;
                    l.CreditM = false;
                    l.IsApproved = false;
                    context.LinkedInUsers.Add(l);
                    context.SaveChanges();
                    ReturnString = "submitted";
                    //SendEmailForLikeAndComment(projectId, Convert.ToInt32(UserId), string.Empty);

                }
                else
                {
                    ReturnString = "AlreadyRequested";
                }
            }
            catch
            {
                ReturnString = "Fail";
            }
            return ReturnString;
        }
Exemplo n.º 11
0
 private static LinkedInUser parseUser(JToken token)
 {
     LinkedInUser user = new LinkedInUser();
       return user;
 }