Get Google contacts via AuthSub c# - c#

Does any one have a working example of getting google contact via AuthSub in c#
I have tried this url , but i was not able to complete it.

Here is a piece of code from one of my projects:
public class GoogleContactsProvider : IContactProvider
{
#region IContactProvider Members
/// <summary>
/// Gets the contacts list form the contact provider.
/// </summary>
/// <returns></returns>
public EntityCollection<IContactItem> GetContactsList()
{
EntityCollection<IContactItem> collection = new EntityCollection<IContactItem>();
// Setup the contacts request (autopage true returns all contacts)
RequestSettings requestSettings = new RequestSettings("AgileMe", UserName, Password);
requestSettings.AutoPaging = true;
ContactsRequest contactsRequest = new ContactsRequest(requestSettings);
// Get the feed
Feed<Contact> feed = contactsRequest.GetContacts();
// create our collection by looping through the feed
foreach (Contact contact in feed.Entries)
{
GoogleContactItem newContact = new GoogleContactItem();
newContact.Name = contact.PrimaryEmail.Address;
newContact.Summary = contact.Summary;
collection.Add(newContact);
}
return collection;
}
/// <summary>
/// Gets or sets the name of the user for the contact provider.
/// </summary>
/// <value>The name of the user.</value>
public string UserName { get; set; }
/// <summary>
/// Gets or sets the password for the contact provider.
/// </summary>
/// <value>The password.</value>
public string Password { get; set; }
#endregion
}
EntityCollection is a wrapper around a simple List and GoogleContactItem is a wrapper around the retrieved information.

I found this example so simple. link
And it works great.

Related

Duplicate parameters output through Swashbuckle/Swagger

Code is further down in the post.
Question: I would like Swashbuckle to generate the following two "GET" requests:
1. mydomain.com/api/books?apikey=12345567891011121314151617181920
2. mydomain.com/api/books/1234?apikey=12345567891011121314151617181920
Swashbuckle does fine on #1 and it works great from the Swagger UI. But for #2, it ends up generating (and calling):
mydomain.com/api/books/{Id}?id=1234&apikey==12345567891011121314151617181920
Needless to say, that GET fails. Swashbuckle is picking up the literal "Id" from the route attribute as well as the BookDetail object. In fact, it shows both IDs in the UI, but I was able to solve that by de-duping by hooking up a custom IOperationFilter, but that obviously didn't help with correcting the actual GET request path.
I already looked at Duplicate parameter output in Swagger 2 but that answer does not work for me. I am looking for having Swashbuckle use the "Id" that's part of the BookDetail object so that Swagger UI shows the description (from the XML comment) while supporting route based ID rather than query string based: mydomain.com/api/books/1234.... What am I doing wrong? (I am on Swashbuckle 5.2.2).
Code:
/// <summary>
/// Books controller
/// </summary>
[RoutePrefix("api")]
public class BooksController : ApiController
{
/// <summary>
/// Returns books matching the search query
/// </summary>
/// <param name="searchRequest"></param>
/// <returns></returns>
[Route("books")]
public IHttpActionResult Get(BookSearch searchRequest)
{
//Do stuff with request
return Ok();
}
/// <summary>
/// Retruns a single book for the given ID
/// </summary>
/// <param name="detailRequest"></param>
/// <returns></returns>
[Route("books/{id:int}")]
public IHttpActionResult Get(BookDetail detailRequest)
{
//Do stuff with request
return Ok();
}
/// <summary>
/// Book search
/// </summary>
public class BookSearch
{
/// <summary>
/// API key
/// </summary>
[Required]
public string ApiKey { get; set; }
/// <summary>
/// Search terms
/// </summary>
public string Query { get; set; }
}
/// <summary>
/// Book detail
/// </summary>
public class BookDetail
{
/// <summary>
/// API key
/// </summary>
[Required]
public string ApiKey { get; set; }
/// <summary>
/// Book of the ID you want to retrieve
/// </summary>
[Required]
public int Id { get; set; }
/// <summary>
/// Boolean indicating whether to include photos or not
/// </summary>
public bool IncludePhotos { get; set; }
}
}

Documentation of a class property is returned as null when accessed from other projects

I am trying to create Web API documentation (which is a part of web-service) for our project. When I try to read the ResourceModal of an Object (http://localhost:56258/Help/ResourceModel?modelName=LoginInfo) that resides in the same project it gives me the Property Documentation correctly.
namespace SmartTouch.CRM.WebService.Models
{
/// <summary>
/// LoginInfo
/// </summary>
public class LoginInfo
{
/// <summary>
/// Email that is used to login to SmartTouch Web Application
/// </summary>
public string UserName { get; set; }
/// <summary>
/// Password that is used to login to SmartTouch Web Application
/// </summary>
public string Password { get; set; }
/// <summary>
/// Client ID that is provided by SmartTouch Administrator
/// </summary>
public string ApiKey { get; set; }
}
}
But, when i try to read the ResourceModal of another Object which resides in another project then the Description is being returned as null though I have generated the XMLDocumentation file. Any help?

NullReference exception when using List.Add<t>, would like to understand it [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I have a settings class that looks like the following:
/// <summary>
/// Class for pipeline settings
/// </summary>
public class PipelineSettings
{
/// <summary>
/// List of jobs to process
/// </summary>
[JsonProperty("jobs")]
public List<PipelineJob> Jobs;
// todo: make private and create FetchCredentials(id)
/// <summary>
/// List of credentials information cataloged by id
/// </summary>
[JsonProperty("credentials")]
public List<PipelineCredentials> Credentials;
}
And a credentials class that looks like the following:
/// <summary>
/// Class to hold credentials for pipeline jobs
/// </summary>
public class PipelineCredentials
{
/// <summary>
/// The id for the current credential to be used when referring to it within
/// other areas of json settings files
/// </summary>
[JsonProperty("id")]
public int Id;
/// <summary>
/// Username or login string for the current system
/// </summary>
[JsonProperty("username")]
public string Username;
// refine: AES auto encrypt?
/// <summary>
/// The password for the active authentication. If not encrypted then it
/// will be automatically converted into an AES encrypted string
/// </summary>
[JsonProperty("password")]
public string Password;
[JsonProperty("path")]
public string UNCPath;
}
I've built the following to try to add a new credential to my list:
var settings = new PipelineSettings();
// Build credentials for storage
var credentials = new PipelineCredentials();
credentials.Id = 1;
credentials.Username = "testUsername";
credentials.Password = "test_password";
credentials.UNCPath = null;
// Add credentials to the current settings class
settings.Credentials.Add(credentials);
var json = new JsonSerializeHelper();
Console.Write(json.Serialize(settings));
Console.ReadKey();
And when I do, I'm receiving a null reference exception on the following line:
settings.Credentials.Add(credentials);
I don't know what I don't know - how should I be adding new items into a list if they're prebuilt?
It looks like you need to instantiate the Credentials list.
settings.Credentials = new List<PipelineCredentials>
somewhere in the code. Or, to keep things tidy, you could do this in the constructor:
/// <summary>
/// Class for pipeline settings
/// </summary>
public class PipelineSettings
{
public PipelineSettings()
{
this.Credentials = new List<PipelineCredentials>();
}
/// <summary>
/// List of jobs to process
/// </summary>
[JsonProperty("jobs")]
public List<PipelineJob> Jobs;
// todo: make private and create FetchCredentials(id)
/// <summary>
/// List of credentials information cataloged by id
/// </summary>
[JsonProperty("credentials")]
public List<PipelineCredentials> Credentials;
}
That way, whenever a new PipelineSettings class is instantiated, it will automatically create a PipelineCredentials list.
Your Credentials list is not initialized, you could do that in the constructor:
public class PipelineSettings
{
/// <summary>
/// List of jobs to process
/// </summary>
[JsonProperty("jobs")]
public List<PipelineJob> Jobs;
// todo: make private and create FetchCredentials(id)
/// <summary>
/// List of credentials information cataloged by id
/// </summary>
[JsonProperty("credentials")]
public List<PipelineCredentials> Credentials;
public PipelineSettings()
{
Credentials = new List<PipelineCredentials>();
}
}

Generate model description in AspNet WebApi help pages

How do I generate a description for my model in Asp.Net Web Api help pages?
Example:
As you can see from the example, I can already generate Name, Type and Additional Information. But how do I generate Description?
I've tried nothing and I'm all out of ideas.
No, that's not true. I've tried adding comments to my TransactionDto class, but it does not work.
/// <summary>
/// A DTO (Data Transfer Object) for Transaction objects.
/// </summary>
public class TransactionDto
{
/// <summary>
/// The manager who registered the transaction.
/// </summary>
public string FromId { get; set; }
/// <summary>
/// The receiving manager.
/// </summary>
[Required]
public string ToId { get; set; }
/// <summary>
/// Optional expiration date.
/// </summary>
public DateTime? Expires { get; set; }
/// <summary>
/// Date the transaction was created.
/// </summary>
public DateTime Created { get; set; }
}
I have configured HelpPageConfig.cs to use an XmlDocumentationProvider like so:
config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
So how do I generate these descriptions for models?
I believe you have models in the separate project other than the Web API project?
If that is the case, the web API project is not aware of the help XML file generated for the models. you need to set the XML output path for both web API project and the models project and then combine both XML files in the register method of HelpPageConfig.cs file.
public static void Register(HttpConfiguration config)
{
XmlDocument apiDoc = new XmlDocument();
apiDoc.Load(HttpContext.Current.Server.MapPath("~/App_Data/WebApi.Orders.xml"));
XmlDocument contractsDoc = new XmlDocument();
contractsDoc.Load(HttpContext.Current.Server.MapPath("~/App_Data/Contracts.xml"));
if (contractsDoc.DocumentElement != null && apiDoc.DocumentElement!=null)
{
XmlNodeList nodes = contractsDoc.DocumentElement.ChildNodes;
foreach (XmlNode node in nodes)
{
XmlNode copiedNode = apiDoc.ImportNode(node, true);
apiDoc.DocumentElement.AppendChild(copiedNode);
}
apiDoc.Save(HttpContext.Current.Server.MapPath("~/App_Data/WebApi.Orders.xml"));
}
config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/WebApi.Orders.xml")));
......
}

Loading large amount of data in session after logging in

I have some data I need to store somewhere after a user logs in, what I need are:
1. A list of customers
2. US States list
for now that's all. Now Customer's list can continue to grow constantly and even after it has been loaded, obviously US States don't.
Currently what I do in my login.aspx page after the user logs in and everything is validated then I go to my SQL database and load all customers and US states into a Session variable. Right now this works although it does take a little bit of time but since there's only about 3 users at any time testing the site it doesn't affect. But as I understand this could be a problem when the company of about 50+ users start using it or even customers aswell.. So what would be the best way to work this and why? Thanks in advance.
ps. if this is not a valid question, please let me know and I'll take it down, I just didn't know where to ask this and get some useful feedback.
Andres,
Is it possible to (instead of using session) to cache the data. This can be done in multiple ways through various caching techniques (IE System.Web.Caching, MemoryCahce).
As your users grow \ shrink you can modify the DB and the cached instance at the same time. When the user requests the list of users (states) the cached list is evaluated. If the cached list isnt set then you re-build the cache list.
You could do something like. (Basic example)
public class UserCache : IEnumerable<User>
{
/// <summary>
/// const cache string
/// </summary>
const string userCacheString = "_userCacheList";
/// <summary>
/// current list of users
/// </summary>
public static UserCache Current
{
get
{
if (HttpContext.Current == null)
throw new Exception("NO CONTEXT");
var userList = HttpContext.Current.Cache[userCacheString] as UserCache;
if (userList == null)
{
userList = new UserCache();
HttpContext.Current.Cache[userCacheString] = new UserCache();
}
return userList;
}
}
/// <summary>
/// default constructor
/// </summary>
public UserCache()
{
}
/// <summary>
/// the list of users
/// </summary>
List<User> users;
/// <summary>
/// adds a user
/// </summary>
/// <param name="user"></param>
public void Add(User user)
{
if (this.Contains(user))
return;
this.users.Add(user);
}
/// <summary>
/// removes a user
/// </summary>
/// <param name="user"></param>
public void Remove(User user)
{
if (this.Contains(user))
return;
this.users.Remove(user);
}
/// <summary>
/// clears a user
/// </summary>
public void Clear()
{
this.users = null;
}
/// <summary>
/// fills the users from the database
/// </summary>
void fillUsers()
{
this.users = new List<User>();
//TODO: Get from DB
}
/// <summary>
/// gets the enumerator
/// </summary>
/// <returns></returns>
public IEnumerator<User> GetEnumerator()
{
if (this.users == null)
fillUsers();
foreach (var user in users)
yield return user;
}
/// <summary>
/// gets the enumerator
/// </summary>
/// <returns></returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
public class User
{
public string UserName { get; set; }
public Guid UserID { get; set; }
public string Email { get; set; }
}
From here you user management (where you add \ remove users) can call the UserCache to modify its collection accordinly. Such as (psudo code)
public class UserManager
{
public void Register(string userName, string email)
{
//TODO: Register in DB.
UserCache.Current.Add(new User
{
UserID = Guid.NewGuid(),
Email = email,
UserName = userName
});
}
}
From here you can always call UserCache.Current to get the current user list.
Just a thought.
EDIT: Response to Simon Halsey comment.
In the example I did inherit from the IEnumerable<> interface and not the List<> interface. This was a personal preference and to support "how" the class was defined. Now before I explain, this is not the only way but just a conceptual way of achieving the result.
In the example the method Clear() clears the inner list by setting the inner list user to null. In the IEnumerable<> implentation GetEnumerator() method the first check is if the inner list is null. If the inner list is null then the fillUsers() method is called to retrieve all users from the database.
If this example inherited from List<> then the Clear() method of List<> would be called and clears the list (removing all items) however the list is not null. Therefore enumerating the list after the Clear() method has been called will result in no users. Now this could be re-written using a List<> implentation as follows. Where the only thing you will have to do is override the Clear() method and the constructor to load the users. Such as.
public class UserListCache : List<User>
{
/// <summary>
/// const cache string
/// </summary>
const string userCacheString = "_userCacheList";
/// <summary>
/// current list of users
/// </summary>
public static UserListCache Current
{
get
{
if (HttpContext.Current == null)
throw new Exception("NO CONTEXT");
var userList = HttpContext.Current.Cache[userCacheString] as UserListCache;
if (userList == null)
{
userList = new UserListCache();
HttpContext.Current.Cache[userCacheString] = new UserListCache();
}
return userList;
}
}
/// <summary>
/// default constructor
/// </summary>
public UserListCache()
{
this.fillUsers();
}
/// <summary>
/// clear the list
/// </summary>
public new void Clear()
{
base.Clear();
this.fillUsers();
}
/// <summary>
/// fills the users from the database
/// </summary>
void fillUsers()
{
//TODO: Get from DB
}
}
Now neither method is better than the other (and the solution may not be adequate).

Categories