How to Retrieve Contact from Google mail by asp.net - asp.net

I have been using this code because there is an error:
Execution of authentication request returned unexpected result: 404
DataSet ds = new DataSet();
ds.Tables.Add("GmailContact");
ds.Tables[0].Columns.Add("EmailId");
RequestSettings rs = new RequestSettings("GetGmailContact", txtUsername.Text, txtPassword.Text);
rs.AutoPaging = true;
ContactsRequest cr = new ContactsRequest(rs);
Feed<Contact> f = cr.GetContacts();
foreach (Contact t in f.Entries)
{
foreach (EMail email in t.Emails)
{
DataRow row = ds.Tables[0].NewRow();
row["EmailId"] = email.Address.ToString();
ds.Tables[0].Rows.Add(row);
}
}
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
lblStatus.Text = "Total Contact For" + txtUsername.Text + ":" + ds.Tables[0].Rows.Count.ToString();

Step
1 Go to https://console.developers.google.com/project and create project.
2 Select project, select APIs & auth from top left corner menu.
3 Select Credentials
4 Create OAuth with button Create new Client ID (Application type - Installed Aplication.
5 Fill field Product Name
6 Save
After that you got Client ID for native application with: Client ID, Client secret, Redirect URIs
Install Google.Apis.Auth from NuGet
Code
string clientId = null; // https://console.developers.google.com/project/xxx
string clientSecret = null; // https://console.developers.google.com/project/xxx
string accessCode = null; // You will get this code after GetAccessToken method
string redirectUri = null; // https://console.developers.google.com/project/xxx
string applicationName = null; // https://console.developers.google.com/project/xxx
// Scopes https://support.google.com/a/answer/162106?hl=en
string scopes = null; // put your scope like https://www.google.com/m8/feeds/
string accessType = "offline";
string tokenType = "refresh";
OAuth2Parameters parameters = new OAuth2Parameters
{
ClientId = clientId,
ClientSecret = clientSecret,
RedirectUri = redirectUri,
Scope = scopes,
AccessType = accessType,
TokenType = tokenType
};
if (accessCode == null)
{
string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
// Start webbrowser
Process.Start(url);
// Load code from web via popup, etc.
parameters.AccessCode = accessCodeFromWeb;
}
// Check accessToken and refreshToken
// After first acceess with GetAccessToken you will get that information
if (accessToken == null || refreshToken == null)
{
OAuthUtil.GetAccessToken(parameters);
// Save yours accessToken and refreshToken for next connection
accessToken = parameters.AccessToken;
refreshToken = parameters.RefreshToken;
}
else
{
// Restore your token from config file, etc.
parameters.AccessToken = accessToken;
parameters.RefreshToken = refreshToken;
}
RequestSettings rs = new RequestSettings(applicationName, parameters);
return new ContactsRequest(rs);

Related

Getting Java.lang.nullpointexcepton when I press back button from facebook login page in xamarin.android

In my app, I am including login in my application with face book login. I am using 'OAuth' for social login. When user press face book login in login page, then we will navigate to the face book login page. Here is the problem is occur. After getting face book login page, When I press back button in my mobile getting fallowing exception. Can you please suggest what the cause of this issue. This type of exception is getting only in my xamarin android application.
Error :
sample code:
var activity = this.Context as Activity;
var auth = new OAuth2Authenticator("ClientId", "email", new Uri("http://m.facebook.com/dialog/oauth/"), new Uri("http://appname/Account/LoginComplete"));
auth.Completed += async (sender, eventArgs) =>
{
try
{
if (eventArgs.IsAuthenticated)
{
string emailAddress = string.Empty;
var token = eventArgs.Account.Properties["access_token"].ToString();
var expiresIn = Convert.ToDouble(eventArgs.Account.Properties["expires_in"]);
var expireDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn);
var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me"), null, eventArgs.Account);
var response = await request.GetResponseAsync();
var obj = JObject.Parse(response.GetResponseText());
var id = obj["id"].ToString().Replace("\"", "");
var name = obj["name"].ToString().Replace("\"", "");
var emailRequest = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?access_token=" + token + "xxx&fields=email"), null, eventArgs.Account);
var emailResponse = await emailRequest.GetResponseAsync();
var jsonString = JObject.Parse(emailResponse.GetResponseText());
string finalString = jsonString.ToString();
if (finalString.Contains("email"))
{
emailAddress = jsonString["email"].ToString();
}
else
{
var emailRequest2 = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?access_token=" + token + "&fields=first_name,last_name,gender,email,timezone,age_range,verified"), null, eventArgs.Account);
var emailResponse2 = await emailRequest2.GetResponseAsync();
var jsonString2 = JObject.Parse(emailResponse2.GetResponseText());
finalString = jsonString2.ToString();
if(finalString.Contains("email"))
emailAddress = jsonString2["email"].ToString();
}
var password = string.Empty;
await LoadUser(emailAddress, password, name, token, id, expireDate);
//await FbUserContrloller.LoadFbUserDetails(emailAddress, password, name, token, id, expireDate);
AccountStore.Create(Context).Save(eventArgs.Account, App.AppName);
activity.StartActivity(auth.GetUI(activity));

Save data and send email to the user with their password and email

I am developping a Asp.Net MVC 5 project. I have this controller that save data from a user.Now i wanna sedn an email to that user after i have saved the data notifying him/her with the password we auto-generated.
Here is my create action
[HttpPost]
public ActionResult Create(TeacherViewModel viewModel)
{
if (!ModelState.IsValid)
{
return View("Create", viewModel);
}
var teacher = new Teacher
{
Identifier = viewModel.Identifier,
Name = viewModel.Name,
Surname = viewModel.Surname,
Email = viewModel.Email,
PhoneNumber = viewModel.PhoneNumber,
Ville = viewModel.Ville,
Block = viewModel.Block,
Password = viewModel.Password
};
_context.Teachers.Add(teacher);
_context.SaveChanges();
return RedireToAction("Index","Home");
Save data and send email to the user with their password and email
As you need to send an email and password in email after save the data, please refere below mentioned code as per your requirement, Hope it helps you.
[HttpPost]
public ActionResult Create(TeacherViewModel viewModel)
{
if (!ModelState.IsValid)
{
return View("Create", viewModel);
}
var teacher = new Teacher
{
Identifier = viewModel.Identifier,
Name = viewModel.Name,
Surname = viewModel.Surname,
Email = viewModel.Email,
PhoneNumber = viewModel.PhoneNumber,
Ville = viewModel.Ville,
Block = viewModel.Block,
Password = viewModel.Password
};
_context.Teachers.Add(teacher);
_context.SaveChanges();
// For send an email
string mailfrom = "sender mail", mailTo = teacher.Email, //"receiver mail",
subject = "Subject Line", filepath = "", htmlbody = "";
filepath = Server.MapPath("~/path_for_email_template/template.html");
htmlbody = System.IO.File.ReadAllText(filepath);
/* you can replace some dynamic contents from body as per your requirements like as name, email but for that you need to all the variable with unique pattern so you can easily replace them, ex: %name% */
htmlbody = htmlbody.Replace("%name%", teacher.Name)
.Replace("%password%", teacher.Password) // as you want to send a password inside mail.
.Replace("%email%", teacher.Email);
try
{
// you need to include
// using System.Net;
// using System.Net.Mail;
SmtpClient client = new SmtpClient("host");
client.Port = 25;// int port number
client.Credentials = new NetworkCredential("Sender_UserName", "Sender_password");
client.EnableSsl = false;//true if ssl required
MailMessage msg = new MailMessage();
msg.To.Add(mailTo);
msg.From = new MailAddress(mailfrom.Trim());
msg.Subject = subject;
msg.Body = htmlbody;
msg.IsBodyHtml = true;
client.Send(msg);
}
catch (SmtpException ex) { throw (ex); }
return RedireToAction("Index", "Home");
}

How to check the logged user info?

I had my code to check the current logged user , it is worked well on local host but when I deployed on server it doesn't work .
private void checkUser()
{
DirectorySearcher searcher = new DirectorySearcher();
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = string.Format(CultureInfo.InvariantCulture, "(sAMAccountName={0})", Page.User.Identity.Name);
SearchResult findUser = searcher.FindOne();
if (findUser != null)
{
DirectoryEntry user = findUser.GetDirectoryEntry();
string Mobile = user.Properties["Mobile"].Value.ToString();
string Login = user.Properties["sAMAccountName"].Value.ToString();
if (user.Properties["Department"].Value != null)
LoggedDepartement = user.Properties["Department"].Value.ToString();
string title = user.Properties["title"].Value.ToString();
data = user.Properties["thumbnailPhoto"].Value as byte[];
}
}

How to validate windows user?

I use the following code to validate the users who belong to our company domain. This works fine.
using (var entry = new DirectoryEntry(""))
{
DirectorySearcher ds = new DirectorySearcher(entry);
ds.Filter = "(|(&(objectCategory=user)(name=domainuser)))";
ds.PropertyNamesOnly = true;
ds.PropertiesToLoad.Add("name");
ds.ReferralChasing = ReferralChasingOption.None;
SearchResultCollection src = ds.FindAll();
bool isValid = false;
try
{
foreach (SearchResult sr in src)
{
DirectoryEntry de = sr.GetDirectoryEntry();
de.Password = "domainpassword";
object nativeObject = de.NativeObject;
if (nativeObject != null)
isValid = true;
break;
}
}
catch (DirectoryServicesCOMException ex) {}
return isValid;
}
The actual problem is that I need to create an LDAP instance in my laptop (MYINSTANCE) and then I need to create users programmatically. I'm able to create users and iterate through them.
Now for such users I'm not able to validate the user name and password.
The change I made was as below.
using (var entry = new DirectoryEntry("LDAP://MYPC:389/CN=MYINSTANCE,DC=COMPANYDOMAIN,DC=com", "domainuser", "domainpassword", AuthenticationTypes.Secure))
{
DirectorySearcher ds = new DirectorySearcher(entry);
ds.Filter = "(|(&(objectCategory=user)(name=instanceuser)))";
ds.PropertyNamesOnly = true;
ds.PropertiesToLoad.Add("name");
ds.ReferralChasing = ReferralChasingOption.None;
SearchResultCollection src = ds.FindAll();
bool isValid = false;
try
{
foreach (SearchResult sr in src)
{
DirectoryEntry de = sr.GetDirectoryEntry();
de.Password = "instancepassword";
object nativeObject = de.NativeObject;
if (nativeObject != null)
isValid = true;
break;
}
}
catch (DirectoryServicesCOMException ex) {}
return isValid;
}
If you work on .NET 3.5 or higher, you can use the System.DirectoryServices.AccountManagement namespace and easily verify your credentials:
// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "MYINSTANCE",
"CN=MYINSTANCE,DC=COMPANYDOMAIN,DC=com",
ContextType.SecureSocketLayer,
"domainuser", "domainpassword")
{
// validate the credentials
bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}
It's simple, it's reliable, it's 100% C# managed code on your end - what more can you ask for? :-)
Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement

The distinguished name contains invalid syntax error

I'm trying using LDAP to authenticate user, but I have a problem with LDAP.
This is my code:
string hostOrDomainName = "MrHand-PC";
string targetOu = "cn=Huy Pham,ou=people,dc=example,dc=com";
// create a search filter to find all objects
string ldapSearchFilter = "uid=pdhuy";
// establish a connection to the directory
LdapConnection connection = new LdapConnection(hostOrDomainName);
Console.WriteLine("\r\nPerforming a simple search ...");
SearchRequest searchRequest = new SearchRequest(targetOu, ldapSearchFilter,
System.DirectoryServices.Protocols.SearchScope.OneLevel, null);
// cast the returned directory response as a SearchResponse object
SearchResponse searchResponse =
(SearchResponse)connection.SendRequest(searchRequest);
The last line throws an exception: The distinguished name contains invalid syntax.
Can anyone help my solve this problem?
To authenticate against LDAP, you can try the following (domain, username and password are arguments):
bool IsAuthenticated = false;
string domainAndUsername = domain + #"\" + username;
string dirContext = GetAuthenticatingDirectory(domain);
using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + dirContext, domainAndUsername, password))
{
try
{
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (result != null)
{
IsAuthenticated = true;
}
}
catch (Exception e)
{
//handle appropriately according to your requirements
}
}
return IsAuthenticated;
where GetAuthenticatingDirectory() is defined as
private string GetAuthenticatingDirectory(string domain)
{
string authenticatingDirectory = string.Empty;
string dotComDomain = domain + #".com";
// Connect to RootDSE
using (DirectoryEntry RootDSE = new DirectoryEntry("LDAP://rootDSE"))
{
// Retrieve the Configuration Naming Context from RootDSE
string configNC = RootDSE.Properties["configurationNamingContext"].Value.ToString();
// Connect to the Configuration Naming Context
using (DirectoryEntry configSearchRoot = new DirectoryEntry("LDAP://" + configNC))
{
// Search for all partitions where the NetBIOSName is set.
using (DirectorySearcher configSearch = new DirectorySearcher(configSearchRoot))
{
configSearch.Filter = ("(NETBIOSName=*)");
// Configure search to return dnsroot and ncname attributes
configSearch.PropertiesToLoad.Add("dnsroot");
configSearch.PropertiesToLoad.Add("ncname");
using (SearchResultCollection forestPartitionList = configSearch.FindAll())
{
// Loop through each returned domain in the result collection
foreach (SearchResult domainPartition in forestPartitionList)
{
// domainName like "domain.com". ncName like "DC=domain,DC=com"
string domainName = domainPartition.Properties["dnsroot"][0].ToString();
string ncName = domainPartition.Properties["ncname"][0].ToString();
if (dotComDomain.Equals(domainName, StringComparison.OrdinalIgnoreCase))
{
authenticatingDirectory = ncName;
break;
}
}
}
}
}
}
return authenticatingDirectory;
}

Resources