active directory with xamarin method - xamarin

I wrote the following code to find out if the user logging has an account at active directory so i may allow him to proceed and it's working fine:
public bool AuthenticateUser(string domain, string username, string password, string LdapPath)
{
string domainAndUsername = domain + #"\" + username;
DirectoryEntry entry = new DirectoryEntry(LdapPath, domainAndUsername, password);
try
{
// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
and it works great, the only problem is that i need to make the same thing using xamarin forms , how may I?

DirectorySearcher is a class that you would use from a server API/code.
I suggest you to create a Web API that would do the same job and that will be called by your Xamarin application.

Related

Automatically map a Contact to an Account

I want to add a field to Accounts which shows the email domain for that account e.g. #BT.com. I then have a spreadsheet which lists all the Accounts and their email domains. What I want to do is when a new Contact is added to Dynamics that it checks the spreadsheet for the same email domain (obviously without the contacts name in the email) and then assigned the Contact to the Account linked to that domain. Any idea how I would do this. Thanks
Probably best chance would be to develop CRM plugin. Register your plugin to be invoked when on after contact is created or updated (so called post-event phase). And in your plugin update the parentaccountid property of the contact entity to point to account of your choice.
Code-wise it goes something like (disclaimer: not tested):
// IPluginExecutionContext context = null;
// IOrganizationService organizationService = null;
var contact = (Entity)context.InputParameters["Target"];
var email = organizationService.Retrieve("contact", contact.Id, new ColumnSet("emailaddress1")).GetAttributeValue<string>("emailaddress1");
string host;
try
{
var address = new MailAddress(email);
host = address.Host;
}
catch
{
return;
}
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
contact["parentaccountid"] = entities[0].ToEntityReference();
}
organizationService.Update(contact);
I took Ondrej's code and cleaned it up a bit, re-factored for pre-operation. I also updated the logic to only match active account records and moved the query inside the try/catch. I am unfamiliar with the MailAddress object, I personally would just use string mapping logic.
var target = (Entity)context.InputParameters["Target"];
try
{
string host = new MailAddress(target.emailaddress1).Host;
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
query.Criteria.AddCondition("statecode", ConditionOperator.Equals, 0); //Active records only
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
target["parentaccountid"] = entities[0].ToEntityReference();
}
}
catch
{
//Log error
}

Yammer "Follow in Inbox" API support

My company has created a Yammer application that we use internally. Our app automatically subscribes people to various threads that have been created. We have found that there is a difference between "subscribing" someone to a thread and what happens when a user clicks the "follow in inbox" link on the site. When we automatically subscribe people, the only thing that we can see happening is that the thread will appear in the users "Following" section in the Home tab. Contrast this with what happens when a user clicks the "Follow in Inbox" link. From that point on any comments added to the thread will show up in the user's inbox and an email will be sent out to the user when this happens. We would really like for this to happen when we automatically subscribe someone to a thread, however, this feature seems to be missing from the REST API. Does anyone know of a way to accomplish this? The functionality provided by the subscription API endpoint is not sufficient for our purposes.
Thank you
P.S. I've sent the link to this question to several of my colleges they may respond before I get a chance to.
As a verified admin it is possible to create an impersonation token and then perform actions on behalf of the user such as join group/thread.
Note that for private groups, the group admin's are still required to approve the new member
https://developer.yammer.com/docs/impersonation
You can achieve your desired behaviour by adding users directly to the groups.
A C#.Net example I use:
// Impersonate user to join group
string ClientID = ConfigurationSettings.AppSettings["ClientID"]; // ClientID of custom app.
string userid = XMLDoc.Root.Element("response").Element("id").Value; // Yammer user id (in this case retreived from a previous API query)
string YammerGroupID = "123456"; // set group id.
string url = "https://www.yammer.com/api/v1/oauth/tokens.json?user_id=" + userid + "&consumer_key=" + ClientID; // impersonation end-point
HttpWebRequest request;
request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Authorization", "Bearer " + bearer); // Bearer token of verified admin running the custom app.
request.Timeout = 90000;
request.Method = "GET";
request.ContentType = "application/json";
request.Proxy = new WebProxy() { UseDefaultCredentials = true };
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
string UserTokenJSON = reader.ReadToEnd(); // UserOAuth token as a JSON string.
string UserToken = UserTokenJSON.Substring(UserTokenJSON.IndexOf("token") + 8, 22); // Find 'token' in json string.
string temp = UserToken.Substring(UserToken.Length); // there is likely a much better way to parse out the token value, although this works.
temp = UserToken.Substring(UserToken.Length - 1);
temp = UserToken.Substring(UserToken.Length - 2);
if (UserToken.Substring(UserToken.Length) == "\\")
{ UserToken = UserToken.Substring(0, UserToken.Length); }
if (UserToken.Substring(UserToken.Length - 1) == "\"")
{ UserToken = UserToken.Substring(0, UserToken.Length - 1); }
if (UserToken.Substring(UserToken.Length - 2) == "\",")
{ UserToken = UserToken.Substring(0, UserToken.Length - 2); }
string url2 = "https://www.yammer.com/api/v1/group_memberships.json?group_id=" + YammerGroupID; // group membership endpoint,
HttpWebRequest request2;
request2 = (HttpWebRequest)WebRequest.Create(url2);
request2.Headers.Add("Authorization", "Bearer " + UserToken); // Impersonation Token
request2.Timeout = 90000;
request2.Method = "POST";
request2.ContentType = "application/json";
request2.Proxy = new WebProxy() { UseDefaultCredentials = true };
try
{
using (WebResponse response2 = (HttpWebResponse)request2.GetResponse())
{
confirmedstring += " New member: " + Email + "\\r\\n"; // This is used for posting summary back to a Yammer group in further code.
confirmedadditions++;
}
}
catch
{
Errorstring += "Error in adding " + Email + " to group " + YammerGroupID + "\\r\\n";
errors++;
}
}
}

Upload a image in a porltet Liferay

I am doing a portlet to create banners. I preferences I made the form with: input type="file" and the form nctype='multipart/form-data'
In the processAction I get the image, but I don't know how save it in the server, because I only get save in temporal instance portlet, but if I restart the server I lose the image.
This is my code to save the image:
private boolean uploadFile( ActionRequest request, ActionResponse response) throws ValidatorException, IOException, ReadOnlyException {
try {
// Si la request es del tipo multipart ...
if (PortletFileUpload.isMultipartContent(request)) {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
PortletFileUpload servletFileUpload = new PortletFileUpload(diskFileItemFactory);
servletFileUpload.setSizeMax(81920); // bytes
List fileItemsList = servletFileUpload.parseRequest(request);
Iterator it = fileItemsList.iterator();
while (it.hasNext()){
FileItem fileItem = (FileItem)it.next();
if (fileItem.isFormField()){
}
else{
String nombreCampo = fileItem.getFieldName();
String nombreArchivo = fileItem.getName();
String extension = nombreArchivo.substring(nombreArchivo.indexOf("."));
PortletContext context = request.getPortletSession().getPortletContext();
String path = context.getRealPath("/images");
File archivo = new File(path + "/" + nombreArchivo);
PortletContext pc = request.getPortletSession().getPortletContext();
fileItem.write(archivo);
}
}
}
} catch (Exception e) {}
return true;
}
I don't know if I am doing something wrong or this isn't the correct way.
Any idea?
Thanks in advance
EDIT:
Finally I tried do it with DLFolderLocalServiceUtil and DLFileEntryLocalServiceUtil, but it doesn't work correctly. When I load the page you can see the image, but after, when the page is load completely, the image disappears.
I don't know if it is because I don't create fine the fileEntry or the url is wrong.
This is my code:
long folderId = CounterLocalServiceUtil.increment(DLFolder.class.getName());
DLFolder folder = DLFolderLocalServiceUtil.createDLFolder(folderId);
long userId = themeDisplay.getUserId();
long groupId = themeDisplay.getScopeGroupId();
folder.setUserId(userId);
folder.setGroupId(groupId);
folder.setName("Banner image " + nombreArchivo+String.valueOf(folderId));
DLFolderLocalServiceUtil.updateDLFolder(folder);
ServiceContext serviceContext= ServiceContextFactory.getInstance(DLFileEntry.class.getName(), request);
File myfile = new File(nombreArchivo);
fileItem.write(myfile);
List<DLFileEntryType> tip = DLFileEntryTypeLocalServiceUtil.getFileEntryTypes(DLUtil.getGroupIds(themeDisplay));
DLFileEntry DLfileEntry = DLFileEntryLocalServiceUtil.addFileEntry(userId, groupId, 0, folderId, null, MimeTypesUtil.getContentType(myfile), nombreArchivo, "Image banner_"+nombreArchivo, "", tip.get(0).getFileEntryTypeId(), null, myfile, fileItem.getInputStream(), myfile.getTotalSpace(), serviceContext);
FileVersion fileVersion = null;
//FileEntry fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, nombreArchivo);
//String path = DLUtil.getPreviewURL(fileEntry, fileVersion, themeDisplay, "&imagePreview=1");
String path1 = themeDisplay.getPortalURL()+"/c/document_library/get_file?uuid="+DLfileEntry.getUuid()+"&groupId="+themeDisplay.getScopeGroupId();
String path = "/documents/" + DLfileEntry.getGroupId() + "/" + DLfileEntry.getFolderId() + "/" + DLfileEntry.getTitle()+"/"+DLfileEntry.getUuid();
System.out.println("path " + path);
System.out.println("path " + path1);
prefs.setValue(nombreCampo, path);
And this is the output:
path /documents/10180/0/cinesa888.png/f24e6da2-0be8-47ad-a3b5-a4ab0d41d17f
path http://localhost:8080/c/document_library/get_file?uuid=f24e6da2-0be8-47ad-a3b5-a4ab0d41d17f&groupId=10180
I tried to get the url like lpratlong said (DLUtil) but when I tried to get the FileEntry with DLAppServiceUtil.getFileEntry(..) I have an error that says no exist FileEntry.
I don't know what I am doing wrong.. Any idea?
Thanks.
You can use Liferay API to store the file in the Document Library : take a look in DLFolder and DLFileEntry API (for exemple, DLFileEntryLocalServiceUtil will show you allowed local operations).
These API will allowed you to store your file in your file system (in the "data" folder of your Liferay installation) and to store reference of your file in Liferay database.

unable to parse the xml query using Linq

I am developing a sample Twitter app for Windows phone 7. In my code to display some details of user, used the following code.
void ShowProfile()
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Profile_DownloadCompleted);
client.DownloadStringAsync(new Uri("http://api.twitter.com/1/users/show.xml?user_id=" + this.id));
}
void Profile_DownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{ return; }
if (e.Result == null) MessageBox.Show("NUlllllllllll");
XElement Profile = XElement.Parse(e.Result);
var ProfileDetails = (from profile in Profile.Descendants("user")
select new UserProfile
{
UserName = profile.Element("screen_name").Value,
ImageSource = profile.Element("profile_image_url").Value,
Location = profile.Element("location").Value,
TweetsCount = profile.Element("statuses_count").Value,
}).FirstOrDefault();
LayoutRoot.DataContext = ProfileDetails;
}
Here, LayoutRoot is the Grid name. But the data binding doesn't work.
Infact, when kept a Break point it seems there is no data in the ProfileDetails object. But I could observe that e.Result contains the required data in the XML format.
Can any body figureout where I am going wrong??
Thanks in advance.
You have used XElement.Parse so Profile represents the single root <user> that API request would have returned. You are then trying to look for user elements inside it which of course makes no sense.
Try XDocument.Parse instead. Also does it really make any sense assigning a IEnumerable<UserProfile> to the data context when that list can only ever contain 1 entry?

Invoke Webservice with yield return on windows phone

i'm developing a Windows Phone 7 app and I use Windows Live authentication to access the user contacts. I have a webservice, with the following method:
public IEnumerable<LiveIDContact> GetContactsInformationYield(string LocationID, string DelegationToken)
{
string uriTemplate = "https://livecontacts.services.live.com/#L#{0}/rest/LiveContacts/Contacts";
var xdoc = WindowsLiveContactAPIRequest(LocationID, DelegationToken, uriTemplate);
var contacts = (from contact in xdoc.Descendants("Contact")
select contact).ToArray();
foreach (var con in contacts)
{
RetrieveCID(LocationID, DelegationToken, con);
LiveIDContact c = new LiveIDContact()
{
ID = con.Element("ID").Value,
DisplayName = con.Element("Profiles").Element("Personal").Element("DisplayName").Value,
CID = (con.Element("CID") != null ? con.Element("CID").Value : "")
};
yield return c;
}
}
How i invoke the methode in the app:
public void GetContactInformationAsync()
{
LiveIDClient.GetContactsInformationYieldAsync(LocationID, ConsentToken);
}
Here is the problem, when I invoke this methode and i wait on the complete event. It takes 4 to 5 minutes to update the list of contacts in my app.(Performance issue). Is there any way that an event occurs on every yield return ? So i can update my list from that event?
I couldn't find the answer anywhere so lets hope somebody knows the answer.
Is this making a separate HTTP call for every single contact? If so, then I think you simply need to redesign the webservice so that it makes a call for, say, every hundred contacts.

Resources