Hi Guys,
Today i am going to tell you how you can get the Git user details in Wep API.
Step 1. Go to global .asax file and add the following lines after the built in class i.e it should look like
namespace TestGit
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
Database.SetInitializer(new MigrateDatabaseToLatestVersion<TestGitContext, MyConfiguration>());
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
public class MyConfiguration : System.Data.Entity.Migrations.DbMigrationsConfiguration<TestGitContext>
{
public MyConfiguration()
{
this.AutomaticMigrationsEnabled = true;
}
}
}
Step 2: In App_start folder open the file WebApiConfig.cs and add the following lines after routes i.e it should look like
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
config.Routes.MapHttpRoute(
name: "DefaultApi1",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var json = config.Formatters.JsonFormatter;
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
Step 3: Create a model class User, i.e
public class User
{
[Key]
public int Id {get;set;}
public string UserName { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Location { get; set; }
public string Photo { get; set; }
public string Languages { get; set; }
public bool IsAvailableForHiring { get; set; }
}
Step 4: Create a web api controller using the model class "User" and add a get action, It should look like
[ActionName("GetUser")]
// GET api/CodeVitae/5
public User GetUser(string id)
{
id = RemoveSpecialCharacters(id);
//User user = db.Users.Find(id);
User user = (from u in db.Users where u.UserName == id select u).FirstOrDefault();
if (user == null)
{
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
//throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
string url = "https://api.github.com/users/" + id + "?client_id=xxxxxxxxxx&client_secret=xxxxxxxxxxxxxxxx";
WebResponse webResponse = GetAPIData(url);
User u=ReadFrom(webResponse,false);
url = "https://api.github.com/users/" + id + "/repos" + "?client_id=xxxxxxxxx&client_secret=xxxxxxxxxx";
WebResponse webResponse1 = GetAPIData(url);
User u1 = ReadFrom(webResponse1,true);
u.Languages = u1.Languages;
db.Users.Add(u);
db.SaveChanges();
user = u;
}
return user;
}
public static string RemoveSpecialCharacters(string str)
{
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '-' || c == '_')
{
sb.Append(c);
}
}
return sb.ToString();
}
public User ReadFrom(WebResponse twitpicResponse,bool isMultiple)
{
User newUser = new User();
using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objects = js.Deserialize<dynamic>(reader.ReadToEnd());
String languages = "";
foreach (var o in objects)
{
if (isMultiple)
{
try
{
foreach (var g in o)
{
if (g.Key != null)
{
if (g.Key == "language")
{
if (g.Value != null)
{
string t = g.Value;
Technology tech = (from u in db.Technologies where u.Name == t select u).FirstOrDefault();
if (tech == null)
{
Technology te= new Technology();
te.Name = t;
db.Technologies.Add(te);
}
if (!(languages.Contains(g.Value)))
languages = (string.IsNullOrEmpty(languages)) ? g.Value : languages + "," + g.Value;
}
}
}
}
}
catch (Exception ex)
{
}
}
else
{
//Console.WriteLine(o["title"]);
if (o.Key == "login")
{
if (o.Value != null)
newUser.UserName = o.Value;
}
else if (o.Key == "name")
{
if (o.Value != null)
newUser.Name = o.Value;
}
else if (o.Key == "location")
{
if (o.Value != null)
newUser.Location = o.Value;
}
else if (o.Key == "email")
{
if (o.Value != null)
newUser.Email = o.Value;
}
else if (o.Key == "avatar_url")
{
if (o.Value != null)
newUser.Photo = o.Value;
}
else if(o.Key=="hireable")
{
if (o.Value != null)
newUser.IsAvailableForHiring = o.Value;
}
}
}
newUser.Languages = languages;
}
return newUser;
}
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
Thats it folks enjoy!!
No comments:
Post a Comment
Comments are welcome, Please join me on my Linked In account
http://in.linkedin.com/pub/ritesh-tandon/21/644/33b