I am looking to integrate a gmail widget - web

This is for a internal portal , and I am looking for a widget that allows user to login to their gmail account and view their account. I tried the Google gadget but it shows the following error
"this is a builtin module, so the UserPrefs and Content are ignored."
also since gadgets are gonna be discontinued I am uncomfortable using that as a long term solution.
Even widget from widgetbox, netvibes etc. don't seem to be working.
Is it because there has been some policy change by Google preventing these widgets from working ? or am i doing something wrong.

I also tried to use the Google widgets in a my site, but unfortunalitly it doesn't work.
It gives the Content are ignored.
No widgets haven't work for my code.
I think there is a policy change in it. But i didn't have any clew about it.

When you say 'login to their account' and what you want to do. You can use OAuth where a user grants your application permission to access their account.
Google have their own library written in a number of languages - some examples using Java, Python and PHP can be found here: https://developers.google.com/google-apps/gmail/xoauth2_libraries
When you use OAuth you register with Google and they give you a ConsumerKey and ConsumerSecret - this is what identifies you application to Google.
Once you do that provide a link to allow them to login - this will take them to a Google login, they login with their account - then they grant permission.
I've had problems using OAuth with GMail but successfully managed it with say their Contacts. For example this is the code I am using to retrieve all a users contacts
public List<Person> GetContacts()
{
OAuthParameters parameters = null;
GOAuthRequestFactory requestFactory = null;
ContactsService service = null;
ContactsQuery feedQuery = null;
ContactsFeed feed = null;
List<Person> contacts = null;
try
{
if (ConsumerKey == String.Empty) throw new ValueIsEmptyOrNullException("ConsumerKey");
if (ConsumerSecret == String.Empty) throw new ValueIsEmptyOrNullException("ConsumerSecret");
if (OAuthCallback == String.Empty) throw new ValueIsEmptyOrNullException("OAuthCallback");
if (SignatureMethod == String.Empty) throw new ValueIsEmptyOrNullException("SignatureMethod");
if (ApplicationName == String.Empty) throw new ValueIsEmptyOrNullException("ApplicationName");
if (Token == String.Empty) throw new ValueIsEmptyOrNullException("Token");
if (Nonce == String.Empty) throw new ValueIsEmptyOrNullException("Nonce");
if (Verifier == String.Empty) throw new ValueIsEmptyOrNullException("Verifier");
if (Scope == String.Empty)
Scope = "https://www.google.com/m8/feeds";
parameters = new OAuthParameters();
parameters.ConsumerKey = ConsumerKey;
parameters.ConsumerSecret = ConsumerSecret;
parameters.Scope = Scope;
parameters.Callback = OAuthCallback;
parameters.SignatureMethod = SignatureMethod;
parameters.Timestamp = Toolbox.GenerateTimeStamp();
parameters.Token = Token;
parameters.TokenSecret = TokenSecret;
parameters.Nonce = Nonce;
parameters.Verifier = Verifier;
requestFactory = new GOAuthRequestFactory("c1", ApplicationName, parameters);
service = new ContactsService(ApplicationName);
service.RequestFactory = requestFactory;
feedQuery = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
feed = service.Query(feedQuery);
if (feed.Entries.Count > 0)
{
contacts = new List<Person>();
foreach (ContactEntry contact in feed.Entries)
{
try
{
if (contact.Name != null)
{
Person person = new Person();
int idStart = contact.Id.Uri.ToString().LastIndexOf('/');
if (idStart > 0)
{
person.PersonId = contact.Id.Uri.ToString().Substring(contact.Id.Uri.ToString().LastIndexOf('/') + 1);
}
else
{
person.PersonId = contact.Id.Uri.ToString();
}
person.GivenName = contact.Name.GivenName;
person.Surname = contact.Name.FamilyName;
person.Birthday = contact.Birthday;
person.Initials = contact.Initials;
person.Location = contact.Location;
person.MaidenName = contact.MaidenName;
person.Occupation = contact.Occupation;
person.Photograph = contact.PhotoUri.ToString();
person.Surname = contact.Name.FamilyName;
if (contact.Emails.Count > 0)
person.Email = contact.Emails[0].Address;
contacts.Add(person);
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return contacts;
}

Related

Is it possible to call wcf webservice on adf mobile?

I tried to consume a wcf webservice method on adf mobile by using java api as seen as below code snippet.
I tried to run on classical adf generic application by creating webservice proxy. Then i could get response properly. But when i consume webservice method on adfmobile i get http 501 error response. I have tried using drag and drop into amx page and execute binding action, result is same.
What might be the reason?
brgds
private boolean validateClient()
{
List pnames = new ArrayList();
List pvals = new ArrayList();
List ptypes = new ArrayList();
pnames.add("UserName");
pvals.add("test");
ptypes.add(String.class);
pnames.add("Password");
pvals.add("123");
ptypes.add(String.class);
pnames.add("DeviceID");
pvals.add("123456");
ptypes.add(String.class);
GenericType result = null;
try
{
ClientDetail clientDetail = null;
result = (GenericType)AdfmfJavaUtilities.invokeDataControlMethod("mlService", null, "ValidateClient", pnames, pvals, ptypes);
for (int i = 0; i < result.getAttributeCount(); i++)
{
// Get each individual GenericType instance that holds the attribute key-value pairs
GenericType entityGenericType = (GenericType)result.getAttribute(i);
clientDetail = (ClientDetail)GenericTypeBeanSerializationHelper.fromGenericType(ClientDetail.class, entityGenericType);
}
if (clientDetail != null)
{
if (clientDetail.getIsValidate().booleanValue())
return true;
else
AdfmfContainerUtilities.invokeContainerJavaScriptFunction("com.accmee.menu", "navigator.notification.alert",
new Object[] { "No access",
"No access: ", "Ok" });
} else
{
AdfmfContainerUtilities.invokeContainerJavaScriptFunction("com.accmee.menu", "navigator.notification.alert",
new Object[] { "No access",
"No access: ", "Ok" });
return false;
}
}
catch (AdfInvocationException aie)
{
if (AdfInvocationException.CATEGORY_WEBSERVICE.compareTo(aie.getErrorCategory()) == 0)
{
throw new AdfException("Error with the server. Please try later.", AdfException.ERROR);
}
aie.printStackTrace();
throw new AdfException("Uzak veri sağlayısı çağrılırken hata oluştu", AdfException.ERROR);
}
return false;
}
make sure the WSDL URL is accessible from inside the test environment of the app ( emulator or mobile device)

How to get last login details/time for all users?

I am trying to remove the user accounts which are inactive from last 30 days.
I tried fetching User Information List. Checked all of it's properties and fields but coudn't find anything related to last login time.
You can do something like this
public DateTime Get(string attr, string UserName)
{
DomainConfiguration domainConfig = new DomainConfiguration();
using (new SPMonitoredScope("AD Properties"))
{
using (DirectoryEntry domain = new DirectoryEntry("LDAP://" + domainConfig.DomainName, domainConfig.UserName, domainConfig.Password))
{
//DirectorySearcher searcher = new DirectorySearcher(domain, "(|(objectClass=organizationalUnit)(objectClass=container)(objectClass=builtinDomain)(objectClass=domainDNS))");
DirectorySearcher searcher = new DirectorySearcher(domain);
searcher.PageSize = 1000;
searcher.Filter = "(SAMAccountName='" + UserName + "')";
//searcher.Filter = "(|(objectCategory=group)(objectCategory=person))";
searcher.Filter = "(&(objectClass=user) (cn=" + UserName + "))";
var user = searcher.FindOne();
DateTime LastLogon = DateTime.FromFileTime((Int64)user.Properties["lastLogon"].Value);
return LastLogon;
}
}
}
Hope this Helps you.
I do not know why it does gives me the some older dates than i expected.
but at least it will compile and run.
using System.DirectoryServices.AccountManagement;
private static DateTime? GetUserIdFromDisplayName(string displayName)
{
// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find user by display name
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, displayName);
if (user != null)
{
return user.LastLogon;
}
else
{
return null;
}
}
}

Return newly created TFS work item ID using TFS API?

Using the TFS API, I am able to create a TFS item, no problem.
What would be the best way for me to know what the Item ID is for the newly created Item?
Thank you,
George
try
{
// Authenticate User Account
NetworkCredential account = new NetworkCredential(USERNAME, PASSWORD, DOMAIN);
// for user stories from the team project where the user story will be created.
Uri collectionUri = new Uri(tfsURI);
//TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(collectionUri);
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(collectionUri, account);
WorkItemStore workItemStore = tpc.GetService<WorkItemStore>();
Project teamProject = workItemStore.Projects[info.TFSProjectName];
WorkItemType workItemType = teamProject.WorkItemTypes[info.ItemType];
// Create the work item.
WorkItem userStory = new WorkItem(workItemType);
userStory.Title = info.Title;
userStory.Description = info.Description;
userStory.AreaPath = info.AreaPath;
userStory.IterationPath = info.IterationPath;
userStory.Fields["Assigned To"].Value = info.AssignedTo;
if (info.ItemType == "Task")
{
userStory.Fields["Discipline"].Value = info.Discipline;
}
else if (info.ItemType == "Bug")
{
userStory.Fields["Symptom"].Value = info.Symptom;
userStory.Fields["Steps To Reproduce"].Value = info.StepsToReproduce;
}
else if (info.ItemType == "Change Request")
{
userStory.Fields["Justification"].Value = info.Justification;
}
// Save the new user story.
userStory.Save();
return true;
}
catch (Exception ex)
{
log.Error("Error Creating TFS Task.", ex);
return false;
}
finally
{
}
}
As soon as you save userStory, the ID field will be populated. You should be able to just return userStory.Id.

Check if MOSS resource exists generating unexpected 401's

I have a webdav function listed below:
The behavior is completely unexpected....
When I first run the function and pass a URL to a resource (folder in sharepoint) that does not exist, I get a 404 which is expected. I then use another function to create the resource using THE SAME credentials as in this method. No problems yet...
However on 2nd run, after the resource has been created - when I check if resource exists, now I get a 401.
Whats important to note here is that the same credentials are used to check for 401 and create folder, so clearly the credentials are fine...
So it must be something else.... All I want to do is check if a resource exists in SharePoint.... any ideas how to improve this function? Or any theory as to why its giving this 401...
private bool MossResourceExists(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
// Create a new CredentialCache object and fill it with the network
// credentials required to access the server.
var myCredentialCache = new CredentialCache();
if (!string.IsNullOrEmpty(this.Domain ))
{
myCredentialCache.Add(new Uri(url),
"NTLM",
new NetworkCredential(this.Username , this.Password , this.Domain )
);
}
else
{
myCredentialCache.Add(new Uri(url),
"NTLM",
new NetworkCredential(this.Username , this.Password )
);
}
request.Credentials = myCredentialCache;
try
{
request.GetResponse();
return true;
}
catch (WebException ex)
{
var errorResponse = ex.Response as HttpWebResponse;
if (errorResponse != null)
if (errorResponse.StatusCode == HttpStatusCode.NotFound)
{
return false;
}
else
{
throw new Exception("Error checking if URL exists:" + url + ";Status Code:" + errorResponse.StatusCode + ";Error Message:" + ex.Message ) ;
}
}
return true;
}
The only clue I have is that when using http://mysite.com/mydoclib/mytoplevelfolder it works.... any sub folders automatically give 401's....
The thing is that you can't pass the whole url that includes folders to the CredentialCache.Add() method.
For example:
http://MyHost/DocumentLibrary/folder1/folder2 will not work as an Uri to the Add() method, but
http://MyHost/DocumentLibrary/ will work.
I would guess that the lack of permissioning capabilities on folder level in SharePoint is the reason for this. Or the way that otherwise SharePoint handles folders.
What you can do is to separate the parameters in your method to accept a base url (including document libraries / lists) and a folder name parameter.
The CredentialCache gets the base url and the request object gets the full url.
Another way is to use the
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
credentials instead. And, if necessary, do an impersonation if you want to use another account than the executing one.
A third variation is to try with authentication type set to Kerberos instead of NTLM.
Here is my test code. I am able to reproduce the problem if I replace the problem with your code, and this code works for me.
static void Main(string[] args)
{
bool result = MossResourceExists("http://intranet/subtest/content_documents/", "testfolder/testfolder2");
}
private static bool MossResourceExists(string baseUrl, string folder)
{
string completeUrl = baseUrl + folder;
var request = (HttpWebRequest)WebRequest.Create(completeUrl);
request.Method = "HEAD";
// Create a new CredentialCache object and fill it with the network
// credentials required to access the server.
var myCredentialCache = new CredentialCache();
if (!string.IsNullOrEmpty(Domain))
{
myCredentialCache.Add(new Uri(baseUrl),
"NTLM",
new NetworkCredential(Username, Password, Domain)
);
}
else
{
myCredentialCache.Add(new Uri(baseUrl),
"NTLM",
new NetworkCredential(Username, Password)
);
}
request.Credentials = myCredentialCache;
//request.Credentials = System.Net.CredentialCache.DefaultCredentials;
try
{
WebResponse response = request.GetResponse();
return true;
}
catch (WebException ex)
{
var errorResponse = ex.Response as HttpWebResponse;
if (errorResponse != null)
if (errorResponse.StatusCode == HttpStatusCode.NotFound)
{
return false;
}
else
{
throw new Exception("Error checking if URL exists:" + completeUrl + ";Status Code:" + errorResponse.StatusCode + ";Error Message:" + ex.Message);
}
}
return true;
}
Hope this helps.

Check Active directory Group membership

How do i go about iterating a group to find out if a given user is a member of a group?
I know i can use IsInRole on WindowsPrincipal object but for some reason it don't always work for me, it doesn't error out or throw exception but just return false.
i have put together following code from web, can some help me improve it in terms of reliability, it hasn't gave any wrong result in 3 weeks of testing.
Side notes: 1: I don't have access to AD username and password hence using GC. 2: Groups can be created in any domain but with in same forest. 3: Group can have users from various domains as well as groups.
thanks
KA
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
static extern int CheckTokenMembership(int TokenHandle, byte[] PSID, out bool IsMember);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
static extern bool IsValidSid(byte[] PSID);
private bool Authenticate(XmlNodeList XmlNodeGroups)
{
bool result = false;
try
{
Dictionary<string, List<string>> Groups = GetGroups(XmlNodeGroups);
//search global catalog and get SID of the group
Byte[] sid = null;
foreach (string groupName in Groups.Keys)
{
using (DirectoryEntry entry = new DirectoryEntry("GC:"))
{
IEnumerator ie = entry.Children.GetEnumerator();
ie.MoveNext();
using (DirectorySearcher ds = new DirectorySearcher((DirectoryEntry)ie.Current))
{
ds.Filter = string.Format("(&(|(sAMAccountName={0}))(objectClass=group))", groupName);
using (SearchResultCollection resColl = ds.FindAll())
{
if (resColl.Count > 0)
{
ResultPropertyCollection resultPropColl = resColl[0].Properties;
sid = (byte[])resultPropColl["objectsid"][0];
if (sid == null || !IsValidSid(sid))
{
// log message and continue to next group continue;
}
}
else
{
// log message and continue to next group continue;
}
}
bool bIsMember = false;
if (CheckTokenMembership(0, sid, out bIsMember) == 0)
{
// log message and initiate fall back....... use Legacy
result = CheckMemberOf(XmlNodeGroups, _CurrentIdentity);
break;
}
else
{
result = bIsMember ? true : false;
if (result)
{
// debug message break;
}
else
{
// debug message
}
}
}
}
}
}
catch (Exception ex)
{
// log exception message and initiate fall back....... use Legacy
result = CheckMemberOf(XmlNodeGroups, _CurrentIdentity);
}
return result;
}</code>
Are you on .NET 3.5 ? If so, check out the MSDN magazine article Managing Directory Security Principals in the .NET Framework 3.5. It shows just how much easier things have become when it comes to users and groups in AD.
As for your requirement - you could
find the group in question
enumerate all its members
find if your given user is a member in that group
and all this can be done quite easily with the help of the System.DirectoryServices.AccountManagement namespace:
// establish a context - define a domain (NetBIOS style name),
// or use the current one, when not specifying a specific domain
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find the group in question
GroupPrincipal theGroup = GroupPrincipal.FindByIdentity(ctx, "nameOfGroup");
// recursively enumerate the members of the group; making the search
// recursive will also enumerate the members of any nested groups
PrincipalSearchResult<Principal> result = theGroup.GetMembers(true);
// find the user in the list of group members
UserPrincipal user = (result.FirstOrDefault(p => p.DisplayName == "Some Name") as UserPrincipal);
// if found --> user is member of this group, either directly or recursively
if(user != null)
{
// do something with the user
}
I tried to use your code snippet above for the 3.5 framework and this line my compiler says it's incorrect:
// find the user in the list of group members
UserPrincipal user = (result.FirstOrDefault(p => p.DisplayName == adUser) as UserPrincipal);
Specifically the result.FirstOfDefault, it says that's not a valid option.
Thanks!

Resources