Giter Site home page Giter Site logo

sparklenetworks / linkedinnet Goto Github PK

View Code? Open in Web Editor NEW
35.0 11.0 50.0 695 KB

Sparkle.LinkedInNET will help you query the LinkedIn API with C# :)

Home Page: https://www.nuget.org/packages/Sparkle.LinkedInNET/

License: GNU Lesser General Public License v3.0

C# 92.69% CSS 0.45% ASP 0.02% Batchfile 0.54% HTML 6.31%
linkedin-api c-sharp dotnet linkedin

linkedinnet's Introduction

LinkedInNET -- DEPRECATED

Before you start - Forks of this project (2018-2019)

🚫 This project will not support the V2 API for the reason described below.
🚫 Support for the V1 API has ended.

Consider the following forks instead:

247GradLabs/LinkedInNET is making support for V2 (nuget LinkedInNET.ApiV2) ✌

Before you start - About the new LinkedIn's V2 API (2018)

As discussed in issue 23, this project might not be able to implement the new API specifications. Too much stuff needs to change.

Please Join the chat to organize a new project or discuss the future of this project in the issue 23.

It has been a cool adventure to make this library. Is it not the time to have a new one? I will continue to support the V1 API so that those who will create the V2 code/SDK won't have to support V1 and V2.

Before you start - About LinkedIn API recent changes (2015)

LinkedIn recently changed a lot of things in its developer program. When using this API, your applications might break on May 12, 2015.

Many documented URLs in this project are broken because LinkedIn changed the documentation pages. Here is the old documentation via the WaybackMachine.

Starting on May 12, 2015, we will be limiting the open APIs to only support the following uses:

  • Allowing members to represent their professional identity via their LinkedIn profile using our Profile API.
  • Enabling members to post certifications directly to their LinkedIn profile with our Add to Profile tools.
  • Enabling members to share professional content to their LinkedIn network from across the Web leveraging our Share API.
  • Enabling companies to share professional content to LinkedIn with our Company API.

All other APIs will require developers to become a member of one of our partnership programs.

For many developers, we understand that today’s changes may be disappointing and disruptive, but we believe these changes will provide further clarity and focus on which types of integrations will be supported by LinkedIn.

-- Changes to our Developer Program, February 12, 2015

See also Transition FAQ, D-Day's changes.

Before you start - Notice

By using the LinkedIn APIs you agree to the LinkedIn APIs Terms of Use.
This project is released under the LGPL v3 license.
This is NOT an official client library.

Project description

Sparkle.LinkedInNET (NuGet) will help you query the LinkedIn API :)

Have any question? You may reach the authors on the dedicated chat room: Join the chat at https://gitter.im/SparkleNetworks/LinkedInNET

Motivation (2015-2016)

Bring the .NET world a nice LinkedIn client library.

Usage

If you still think this project may help you, here is how to start.

1. Installation

Via NuGet

PM> Install-Package Sparkle.LinkedInNET

Or build the sources... You have to create your own .snk file.

Supported frameworks: 3.5 (sync), 4.0 (sync), 4.5 (sync and task async).

2. Create API client with configuration

The LinkedInApi class is the entry point for all API calls. You must instantiate it with a configuration object. The minimum configuration is the API key and secret. Get a LinkedIn API key.

// create a configuration object
var config = new LinkedInApiConfiguration("•api•key•••", "•api•secret•key••••••");

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

3. Create OAuth2 authorize url -- deprecated

The OAuth2 authentication process is fully supported. The GetAuthorizationUrl method will generate the OAuth2 url to navigate the user to.

var scope = AuthorizationScope.ReadBasicProfile | AuthorizationScope.ReadEmailAddress;
var state = Guid.NewGuid().ToString();
var redirectUrl = "http://mywebsite/LinkedIn/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

4. Get access token -- deprecated

When the user is redirected back to your website, you can get an access code.

// http://mywebsite/LinkedIn/OAuth2?code=...&state=...
public async Task<ActionResult> OAuth2(string code, string state, string error, string error_description)
{
    if (!string.IsNullOrEmpty(error) || !string.IsNullOrEmpty(error_description))
    {
        // handle error and error_description
    }
    else
    {
        var redirectUrl = "http://mywebsite/LinkedIn/OAuth2";
        var userToken = await api.OAuth2.GetAccessTokenAsync(code, redirectUrl);
        // keep this token for your API requests
    }

    // ...
}

You will find in the source codes a nicer way to build the redirect url.

var redirectUrl = this.Request.Compose() + this.Url.Action("OAuth2");

5. Example call: fetch user profile -- deprecated

var user = new UserAuthorization(userToken.AccessToken);
var profile = api.Profiles.GetMyProfile(user);

Yes, you have to pass the token for each call. This might seem redundant for some but we prefer stateless objects for multi-threaded contexts.

6. Field selectors

The API uses field lists to fetch the desired data. Simple extension methods will allow you to make strongly-typed field selection.

var profile = api.Profiles.GetMyProfile(
    user,
    FieldSelector.For<Person>().WithFirstname().WithLastname().WithLocationName());
// https://api.linkedin.com/v1/people/~:(first-name,last-name,location:(name))

The .WithAllFields() method will generate the list of all available fields. It is not recommended to do that.

var profile = api.Profiles.GetMyProfile(
    user,
    FieldSelector.For<Person>().WithAllFields());
// https://api.linkedin.com/v1/people/~:(all available fields here)
// however it is not recommended to specify all fields

You can create your own extension methods when you desire many fields. Check the source code to see how it works.

7. Errors

API error results throw LinkedInApiExceptions. You can find extra info in the Data collection.

try
{
    var profile = this.api.Profiles.GetMyProfile(user);
}
catch (LinkedInApiException ex) // one exception type to handle
{
    // ex.Message
    // ex.InnerException // WebException
    // ex.Data["ResponseStream"]
    // ex.Data["HttpStatusCode"]
    // ex.Data["Method"]
    // ex.Data["UrlPath"]
    // ex.Data["ResponseText"]
}
////catch (Exception ex) { } //  bad, don't do that

Library internal errors throw LinkedInNetExceptions. You should not catch them as they do not represent a normal behavior. This may be usefull when waiting for a fix.

You should not catch WebExceptions as they are wrapped into LinkedInApiExceptions.

8. Explore

Code documentation is quite present. Use the auto-completion to discover stuff.

The MVC demo app has a /Explore page that demonstrates most API calls. Have a look at it.

9. Raw queries

A method is missing in the library? You may contribute to create it... Or you may use the raw query methods RawGetJsonQuery, RawPostJsonQuery or RawQuery.

This example shows how to fetch a company share.

string shareAsJson = this.api.RawGetJsonQuery("/v1/companies/" + CompanyId + "/updates/key=" + Uri.EscapeDataString(ShareId) + "?format=json", user);

More details here.

Contribute

This project is no more maintained. There is no need to contribute. Look at the available forks.

We are generating code based on a XML file.
This XML file is manually filled to represent the API.
The API coverage should be implemented by modifying the XML file and enhancing code generation.

To generate the API code, build the "ServiceDefinition" project in Debug mode, edit LinkedInApi.xml, then use "Run custom tool" on the Service.tt file. The XML file will be read and most of the code will be updated automagically.

To alter code generation, search for CSharpGenerator.cs. Different methods are responsible of generating different parts of C# code (return types, api groups, selectors).

To add/alter API methods and return types, search for LinkedInApi.xml. This file describes the API in a human-readable and machine-readable way. Don't forget to re-generate the code (Service.tt).

References

https://developer.linkedin.com/apis
https://developer.linkedin.com/documents/authentication

.NET version

Supported .NET Framework versions:

  • .NET 4.5 (dependencies: Newtonsoft.Json ≥ 6.0.8, Microsoft.Net.Http ≥ 2.2.29)
  • .NET 4.0 (dependencies: Newtonsoft.Json ≥ 6.0.8)
  • .NET 3.5 (dependencies: Newtonsoft.Json ≥ 6.0.8)

We are using a lot of code generation so it won't be difficult to target any other framework.

Status -- deprecated

Because of the API policy changes, most API calls are now reserved to the partners LinkedIn chose. The core team will try to keep up using basic API key.

Check our internal to-do list to track missing/done things.

linkedinnet's People

Contributors

aclark09 avatar dependabot[bot] avatar gitter-badger avatar sandrock avatar tazacban avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

linkedinnet's Issues

Examples would be nice

For those of us that are struggling with the readme markdown a set of examples would be great.

Post a message on LinkedIn with LinkedInNet

Hi, and thank you for this client !

i have a question : how can i post a message using LinkedInNet ?
I tried to do something like this :

try
{
    Sparkle.LinkedInNET.Common.PostShare post = new Sparkle.LinkedInNET.Common.PostShare();
    post.Content = new Sparkle.LinkedInNET.Common.PostShareContent();
    post.Comment = "Check out developer.linkedin.com!";
    
    post.Content.Title = "test api";
    post.Content.Description = "ok";
    post.Content.SubmittedUrl = "https://developer.linkedin.com";
    
    post.Visibility = new Sparkle.LinkedInNET.Common.Visibility();
    post.Visibility.Code = "anyone";
    api.Social.Post(user, post);
}
catch (LinkedInApiException e)
{
}

but it's said me the access is denied... however, i succeed to connect myself with OAuth, and i have already access to my personnal info !

Thanks for your help :)

Léo

Profille Info api throws an exception while submitting all fields

Hi, I'm getting exception in retrieving people profile info api with all fields.

Here is my code.
var profile = api.Profiles.GetMyProfile(user, acceptLanguages, FieldSelector.For<Person>().WithAllFields());

Exception details:

API error (400) Duplicate field {Position.id} 
in inline filter {(id,title,start-date,end-date,is-current,company,id,title,summary,start-date,end-date,is-current,company),picture-url,api-standard-profile-request:(url,headers),public-profile-url,email-address,last-modified-timestamp,proposal-comments,associations,interests,publications,patents:(id,title,summary,number,status:(id,name),office:(name),inventors:(id,name,person),date,url),languages:(id,language,proficiency),skills,certifications:(id,name,authority:(name),number,start-date,end-date),educations,courses,volunteer:(volunteer-experiences:(id,role,organization:(name),cause:(name))),three-current-positions,three-past-positions,num-recommenders,recommendations-received:(id,recommendation-type:(code),recommendation-text,recommender:(id,first-name,last-name,num-connections,headline)),following,job-bookmarks,suggestions,date-of-birth,member-url-resources,related-profile-views,honors-awards,phone-numbers,bound-account-types,im-accounts,main-address,twitter-accounts,primary-twitter-account,connections,group-memberships,network)} 
at https://api.linkedin.com/v1/people/~:(first-name,last-name,headline,site-standard-profile-request,id,maiden-name,formatted-name,phonetic-first-name,phonetic-last-name,formatted-phonetic-name,location:(name,country:(code)),industry,distance,relation-to-viewer,current-status-timestamp,current-share,num-connections,num-connections-capped,summary,specialties,positions:(id,title,start-date,end-date,is-current,company,id,title,summary,start-date,end-date,is-current,company),picture-url,api-standard-profile-request:(url,headers),public-profile-url,email-address,last-modified-timestamp,proposal-comments,associations,interests,publications,patents:(id,title,summary,number,status:(id,name),office:(name),inventors:(id,name,person),date,url),languages:(id,language,proficiency),skills,certifications:(id,name,authority:(name),number,start-date,end-date),educations,courses,volunteer:(volunteer-experiences:(id,role,organization:(name),cause:(name))),three-current-positions,three-past-positions,num-recommenders,recommendations-received:(id,recommendation-type:(code),recommendation-text,recommender:(id,first-name,last-name,num-connections,headline)),following,job-bookmarks,suggestions,date-of-birth,member-url-resources,related-profile-views,honors-awards,phone-numbers,bound-account-types,im-accounts,main-address,twitter-accounts,primary-twitter-account,connections,group-memberships,network)

Please help me with this problem.

Thank you.
Manan

Hi guys

Hi I have implemented quickly Messaging part of the API, where one can send messages to connections.

I would be very happy to commit it here in a branch to have a review, and merge it to the master :)

Asyc support?

Hello,

Any plans to add async support for API operations?:

GetMyConnectionsAsync()
GetMyProfileAsync()
...

.Net standard

Can you please add multi-target .netstandards as well

I.0.11 has a big problem

I.0.11 has a big problem

var config = LinkedInApiConfiguration.FromAppSettings("MyDemo.LinkedInConnect");
// OR
var config = LinkedInApiConfiguration("api key", "api secret key");
Both ways will popup error message in VS2015

The first method will get-----Severity Code Description Project File Line Suppression State
Error CS0117 'LinkedInApiConfiguration' does not contain a definition for 'FromAppSettings' SocialMediaData

The second will get --=-Severity Code Description Project File Line Suppression State
Error CS1955 Non-invocable member 'LinkedInApiConfiguration' cannot be used like a method.

Getting Access Token

Hi I am using the example in the read me but the task to get the access token never evaluates:

  var redirectUrl = "http://localhost:1900/Pages/Content/LinkedIn.aspx";
  var userToken = await ApiClient.OAuth2.GetAccessTokenAsync(code, redirectUrl);
  return userToken.AccessToken;

image
Any help is greatly appreciated

GetAccessToken - System.InvalidOperationException: "Failed to read API response"

Hi everybody,

I'm trying to get an access token using the GetAccessToken function. I keep getting the error
XmlException: Unexpected character '<'.
Can someone help me?

Best, Daniel


System.InvalidOperationException
HResult=0x80131509
Nachricht = Failed to read API response
Quelle = Sparkle.LinkedInNET
Stapelüberwachung:
bei Sparkle.LinkedInNET.OAuth2.OAuth2Api.GetAccessToken(String authorizationCode, String redirectUri)
bei LinkedInWebScrapper.WebForm1.Page_Load(Object sender, EventArgs e) in C:\VS_Local\LinkedInScrapper\LinkedInWebScrapper\WebForm1.aspx.vb: Zeile13

Innere Ausnahme 1:
SerializationException: Fehler beim Deserialisieren des Objekts "vom Typ Sparkle.LinkedInNET.OAuth2.OAuth2Error". Unerwartetes Zeichen '<'.

Innere Ausnahme 2:
XmlException: Unerwartetes Zeichen '<'.

Missing URL escape in FormatUrl calls

URLs composed internally with the FormatUrl method are sometimes invalid. URL escaping is not done.

Example: calling GetPublicProfile(..., "http://www.linkedin.com/in/jeffweiner08", ..., ...) fails:

[LinkedInApiException: API error (400) Unknown field {www.linkedin.com} in resource {Person} at https://api.linkedin.com/v1/people/url=http://www.linkedin.com/in/jeffweiner08:(id,positions:(id,title,start-date,end-date,is-current,company),picture-url,first-name,last-name,headline,languages:(id,language,proficiency),connections)]
   Sparkle.LinkedInNET.Internals.BaseApi.ThrowJsonErrorResult(RequestContext context, ApiError errorResult, String json) in src\NET35.Sparkle.LinkedInNET\Internals\BaseApi.cs:589
   Sparkle.LinkedInNET.Internals.BaseApi.HandleJsonResponse(RequestContext context) in src\NET35.Sparkle.LinkedInNET\Internals\BaseApi.cs:438
   Sparkle.LinkedInNET.Internals.BaseApi.HandleJsonErrorResponse(RequestContext context) in src\NET35.Sparkle.LinkedInNET\Internals\BaseApi.cs:265
   Sparkle.LinkedInNET.Profiles.ProfilesApi.GetPublicProfile(UserAuthorization user, String publicProfileUrl, String[] acceptLanguages, FieldSelector`1 fields) in src\NET35.Sparkle.LinkedInNET\Services.tt.cs:5737
   Sparkle.LinkedInNET.DemoMvc5.Controllers.ExploreController.PublicProfile(String url, String culture) in src\NET45.Sparkle.LinkedInNET.DemoMvc5\Controllers\ExploreController.cs:402
   lambda_method(Closure , ControllerBase , Object[] ) +147

CompanyUpdate Field Selector

Hi,

I am looking at getting basic information for a company's update, I had to manually add likes as a field to get specifically as there is no WithAllFields extension, but I still am unable to see this information which seems available in the documentation: https://developer.linkedin.com/docs/company-pages#company_updates

Code:
image

Trying to get the user id of the person who likes the update and how many connections they have? Any thoughts are appreciated

Getting "Authentication failed because the remote party has closed the transport stream"

Hi,

Thanks for the client we are using it for more than 1 year, it was working till last week.
suddenly we are getting "Authentication failed because the remote party has closed the transport stream" while getting the token, do we need to change any thing on this front.

this is the line where we are getting issue.
await api.OAuth2.GetAccessTokenAsync(code, redirectUrl)

Linkedin api v2 implementation

Hi SandRock,

I would like to contribute on implementing Linkedin api v2. Do you have any concept on your mind how we should start it?

As i saw in Linkedin documentation there are quite major changes on return types too (e.g. check firstName field on Profile) not just on endpoints.

I was thinking to change/ add the xml. Maybe we will need to add an extra xml level to support for return types. And also need some modification how to generate the code.
For dynamic fields like firsName (on Profile) we could simply use JObject (or this needs more rethinking).

Cheers,
Levente

Connections

What is the way to get all connections..
I have created a small asp.net application,

var fir = profile.Connections;
foreach (var item in fir.Person)
{
var gg = item.Firstname;
}

Here connections is always coming null,even though i get access token.
Is there any other way to get connections

GetMyProfile Parameter Problem

Hi,

What should I pass for "acceptLanguage" parameter inside "GetMyProfile" method?

Dim loUser As UserAuthorization = New UserAuthorization(userToken.AccessToken)
Dim profile As Person = api.Profiles.GetMyProfile(loUser, "**[acceptLanguage]**", FieldSelector.For(Of Person).WithAllFields())

Please assist!

GetApi().OAuth2.GetAccessToken(code, state) fails

I am called on this url:

http://www.cvpanda.com/LinkedIn/Index?code=AQTBkadYVh-JlI0TFeIAZsUToxZBpusyXk4QQFEXbKfyO2XDOgBH7NwlNKqPBplCjWZFsuIZiRAEWGOaQArubGNyrlXiuccjsU49lU0OhEJ5soTMPxU&state=be469fc2-b707-4413-9f14-353f69dc7e4e

Exception Type: System.InvalidOperationException
Exception Information: Failed to read API response
Stack trace
at Sparkle.LinkedInNET.OAuth2.OAuth2Api.GetAccessToken(String authorizationCode, String redirectUri)
at HrApp.Controllers.LinkedinController.Index(String id)

Exception Type: Sparkle.LinkedInNET.LinkedInApiException
Exception Information: OAuth2 error (invalid_request): missing required parameters, includes an invalid parameter value, parameter more than onc

Can I get any help on this is it library problem or a problem in my code?

Only the current position is retrieved when using WithPositions()

I'm using this code to retrieve LinkedIn user positions:

var api = new LinkedInApi(config); var user2 = new UserAuthorization(model.ExternalAccessToken); var profile = api.Profiles.GetMyProfile(user2, new[] { "en-US" }, FieldSelector.For().WithPositions());

However only the current position is retrieved instead of all positions, tried different config according to wiki, but it's seem that it's just not working - i'm missing something?

Also education return nothing and most of the configs , but in browser when using direct request everything works fine (same access token used):
https://api.linkedin.com/v1/people/~:(positions)?oauth2_access_token=TOKEN_HERE

Profile Info doesn't give past job positions

Hi, i'm facing an issue while getting past job positions in retrieve people profile info api.

Here is my code.

var profile = await api.Profiles.GetMyProfileAsync(user, acceptLanguages, FieldSelector.For<Person>() .WithId() .WithPositions() .WithThreePastPositions() .WithThreeCurrentPositions() );
After execution of above code, two properties of profile object ThreePastPositions and ThreeCurrentPositions returns null and Position array returns only one count. But when i have checked output from linked in rest console, it gives me 2 counts in position array and 1 count for both three past positions and three current positions.

Please help me for this problem.

Thank you.
Manan

Unable to find sparklepubliccode.pfx

Error Unable to get MD5 checksum for the key file "SparklePublicCode.pfx". Could not find file 'C:\Users\Martin\Downloads\LinkedInNET-master\src\NET35.Sparkle.LinkedInNET\SparklePublicCode.pfx'. NET35.Sparkle.LinkedInNET

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.