Dynamics CRM code popping up dialog in service - c#

Given the following connection code:
var serviceUri = "http://machine.co.za/CRM/XRMServices/2011/Organization.svc";
var clientCredentials = new ClientCredentials
{
Windows =
{
ClientCredential = new System.Net.NetworkCredential("SOMEUSER", "SOMEPASS", "DOMAIN")
}
};
var organizationServiceProxy = new OrganizationServiceProxy(new Uri(serviceUri), null, clientCredentials, null);
// This line of code pops up a dialog?
var user = (WhoAmIResponse)organizationServiceProxy.Execute(new WhoAmIRequest());
if (user.UserId == Guid.Empty)
throw new InvalidOperationException(string.Format(#"connection to {0} cannot be established.", crmConnection.ServiceUri));
user.Dump();
If the supplied password is incorrect, the code pops up a credentials dialog.
Since the service does not have rights to interact with the desktop, the service halts as it cannot actually show a dialog.
How do I suppress the dialog, and have an exception get thrown instead. I am using dynamics 2011.

I am going to take it as a given that the CRM dynamics OrganizationServiceProxy is hardwired to pop up a dialog.
There are no configuration options or flags that turn this behavior off.

You may be mixing up usage of CrmConnection. It boils down to:
var conn = new ConnectionStringSettings("CRM", "Url=http://machine.co.za/CRM; Username=SOMEUSER; Password=SOMEPASS; Domain=SOMEDOMAIN")
var crmConnection = new CrmConnection(conn);
var crmService = new OrganizationService(crmConnection);
try
{
// connection will actually happen here. anything goes wrong, exceptions will be thrown
var user = crmService.Execute<WhoAmIResponse>(new WhoAmIRequest());
user.Dump();
}
catch (Exception ex)
{
// just a proof of concept
// ex is of type MessageSecurityException if credentials are invalid
throw new InvalidOperationException(string.Format(#"connection to {0} cannot be established.", crmConnection.ServiceUri), ex);
}

Related

Unable to create Hotspot connection using NEHotspotConfigurationManager

when I try to create a hotspot connection in my Xamarin.IOS project I get the following error returned in the description when using NEHotspotConfigurationManager :
Error Domain=NEHotspotConfigurationErrorDomain Code=8 \"internal error.\" UserInfo={NSLocalizedDescription=internal error.}
I have tried to connect to both the network in the office and my phone's wifi hotspot and both return the same message. I have enabled both the options "Accept WiFi Information" and "Hotspot" on both the App ID on the developer portal and also the same in the Entitlements.plist and still the same error. I'm using the code shown below.
public async void JoinNetwork()
{
NEHotspotConfiguration config = new NEHotspotConfiguration("CTIP");
config.JoinOnce = false;
var tcs = new TaskCompletionSource<NSError>();
NEHotspotConfigurationManager.SharedManager.ApplyConfiguration(config, err => tcs.SetResult(err));
var error = await tcs.Task;
if (error != null)
{
PAGE.IOSErrorAlert(error.Description, this);
return;
}
}
Try you code as below
NEHotspotConfiguration config = new NEHotspotConfiguration("CTIP" ,passphrase , false);
config.JoinOnce = true;
var tcs = new TaskCompletionSource<NSError>();
NEHotspotConfigurationManager.SharedManager.ApplyConfiguration(config, err =>
tcs.SetResult(err));
and try to restart your device ,this seems like a known issue on apple side .
Refer to
https://stackoverflow.com/a/47769497/8187800
https://developer.apple.com/forums/thread/107851

Login Validation Against Active Directory C# - Visual Studio for Mac

I'm trying to validate credentials in Active Directory for an MVC Web App (C#) I'm writing on Visual Studio for Mac. In searching for answers, I've noticed a lot of NotImplementedExceptions and other strange occurrences.
Here is a (non-comprehensive) list of things I've tried and things that have failed.
First, this code:
string domainAndUsername = domain + #"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
try
{
//Bind to the native AdsObject to force authentication.
// This line throws a not implemented exception
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry)
{
Filter = "(SAMAccountName=" + username + ")"
};
search.PropertiesToLoad.Add("cn");
Console.WriteLine(search.ToString());
SearchResult result = search.FindOne();
//Debug.WriteLine(result.ToString());
if (null == result)
{
return false;
}
//Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (string)result.Properties["cn"][0];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
}
return true;
The line object obj = entry.NativeObject throws a NotImplementedException I've tried commenting out the line (since obj is never used elsewhere) but to no avail. I have tried other variations of very similar code as well.
The other route I attempted was this code:
var creds = new NetworkCredential(username, password);
var srvid = new LdapDirectoryIdentifier(adPath);
// This line throws a NotImplementedException
var conn = new LdapConnection(srvid, creds);
try
{
conn.Bind();
}
catch (Exception)
{
return false;
}
conn.Dispose();
return true;
And other variations of the same idea. The line var conn = new LdapConnection(srvid, creds); throws a NotImplementedException
Finally, I went a simpler route and used
Membership.ValidateUser(model.username, model.password)
Since this is a Web Api and I am using a controller. This requires some code in the Web.config available here. It, too, throws a NotImplementedException.
So do these three common methods all rely on the same underlying function that hasn't been implemented in VS for Mac yet? Or is there something I'm missing? Also if there is any workaround someone could offer, it would be very well appreciated.
Thanks!
First of all you need to reference Microsoft.DirectoryServices.dll
System.DirectoryServices
Second, you need to run this queries with a domain account with grant access. Take care when you publish in server (iis) or other because the service run this code and it had to have permission on it.
check this
Sorry for my English :D
Thanks to the kind efforts of Javier Jimenez Matilla, bnem, and Lexi Li, I got it to work. Part of the issue was a configuration problem that I unfortunately can't disclose (confidentiality and whatnot), but here's the final code:
using Novell.Directory.Ldap;
try
{
var conn = new LdapConnection();
conn.Connect(domain, 389);
conn.Bind(LdapConnection.Ldap_V3, $"{subDomain}\\{username}", password);
return true;
}
catch (LdapException ex)
{
Console.WriteLine(ex.Message);
return false;
}
A few things to note. First, that LdapConnection is actually Novell.Directory.Ldap.LdapConnection. Secondly, the hard-coded 389 is the port which LDAP likes to communicate over. Thirdly, the parameter $"{subDomain}\\{username}" is the way the username appears to AD. For my particular case, the domain is of the form "corporation.mycompany.com", and in AD the username appears corporation\username. So in this example, string subDomain = "corporation"

WMI Win32_Share.Create method on localhost via WMI on Server OSes gives Error Code 24

I am detecting whether or not I'm attempting a connection against localhost, and creating (or not) the WMI connection options as follows:
if (NetworkUtils.IsLocalIpAddress(machineName))
{
_scope = new ManagementScope(string.Format(#"\\{0}\root\cimv2", machineName));
}
else
{
_connectionOptions = new ConnectionOptions
{
Username = username,
Password = password,
Impersonation = ImpersonationLevel.Impersonate
};
_scope = new ManagementScope(string.Format(#"\\{0}\root\cimv2", machineName), _connectionOptions);
}
When I call _scope.Connect() in either case, it works. That is, no exception and IsConnected is true.
However, when I attempt to invoke a method in the local case, such as Win32_Share.Create I get errors. The following code always works for remote connections for me:
var winSharePath = new ManagementPath("Win32_Share");
var winShareClass = new ManagementClass(_scope, winSharePath, null);
var shareParams = winShareClass.GetMethodParameters("Create");
shareParams["Path"] = pathName.TrimEnd('\\');
shareParams["Name"] = shareName;
shareParams["Type"] = 0;
shareParams["Description"] = "CMC Bootstrap Share";
var outParams = winShareClass.InvokeMethod("Create", shareParams, null);
if ((uint) (outParams.Properties["ReturnValue"].Value) != 0)
{
throw new Exception("Unable to share directory. Error code: " +
outParams.Properties["ReturnValue"].Value);
}
I create the pathName directory just prior to invoking this method, so I guarantee pathName exists in all cases.
When executing locally ONLY on Windows Server 2008 & 2012, the above code throws the exception with error code 24. Executing against localhost on Windows 8 works just fine.
What is the correct way to specify "blank credentials" when invoking WMI methods against localhost, as I believe this is the underlying issue?
I tried the code below on my local PC and this works (shares my temp folder). Could you try the same please? Also, which is the patch & share name you're using?
string pathName = #"c:\temp\";
string shareName = "tempFolder";
var scope = new ManagementScope(string.Format(#"\\{0}\root\cimv2", "localhost"));
// your code below
var winSharePath = new ManagementPath("Win32_Share");
var winShareClass = new ManagementClass(scope, winSharePath, null);
var shareParams = winShareClass.GetMethodParameters("Create");
shareParams["Path"] = pathName.TrimEnd('\\');
shareParams["Name"] = shareName;
shareParams["Type"] = 0;
shareParams["Description"] = "CMC Bootstrap Share";
var outParams = winShareClass.InvokeMethod("Create", shareParams, null);
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
{
throw new Exception("Unable to share directory. Error code: " +
outParams.Properties["ReturnValue"].Value);
}
the above code throws the exception with error code 24
That doesn't have anything to do with the error you mention in the title of your question. Error codes for Win32_Share.Create method are documented in this MSDN article. Return value 24 means "Unknown Device or Directory".
In other words, your pathName variable is wrong.

Authenticate with SSPI to vSphere using C# API

I am using the C# library for connecting to vSphere (VimClient). I use this method to log in:
VimClient client = new VimClient();
client.Connect("https://vSphereMachine/sdk");
client.Login("userName", "password");
The user I'm logging in as is the current user used by the process. Is there a way I can use the current logged in user for authentication?
This thread seems to offer suggestions but nothing I tried there works: http://communities.vmware.com/message/1125103
That may be because I'm not familiar with the SSPI implementation in .NET.
As VMWare.Vim.dll just wraps the generated WCF Service client, I was ble to adapt this sample project to using the dll directly. This is my adaptation of his LoginBySspiPackage method.
private UserSession LoginBySspiPackage(SspiPackageType sspiPackage, string serviceSpn)
{
Log($"Logging in to VSphere instance {VimClient.ServiceUrl} using SSPI.");
var sspiClient = new SspiClient(serviceSpn, sspiPackage);
var sessionManager = new SessionManager(VimClient, VimClient.ServiceContent.SessionManager);
var serverNotReady = true;
UserSession session = null;
while (serverNotReady)
{
try
{
var base64String = Convert.ToBase64String(sspiClient.Token);
session = sessionManager.LoginBySSPI(base64String, "en");
serverNotReady = false; // Connected!
}
catch (VMware.Vim.VimException e)
{
if (e.MethodFault is SSPIChallenge)
{
var sspiChallenge = e.MethodFault as SSPIChallenge;
var base64String = Convert.FromBase64String(sspiChallenge.Base64Token);
sspiClient.Initialize(base64String);
}
else if (e.MethodFault is InvalidLogin)
{
throw new InvalidLoginException(e.Message);
}
else
{
throw;
}
}
}
return session;
}

Uploading Any File To Google Docs Using GData

I'm trying to use the Google Docs GData API (.NET) to upload a file to my docs, but I keep getting errors thrown. I can't find any example that uses this method, so I'm not even sure that I am usign it correctly.
DocumentsService docService = new DocumentsService("MyDocsTest");
docService.setUserCredentials("w****", "*****");
DocumentsListQuery docQuery = new DocumentsListQuery();
DocumentsFeed docFeed = docService.Query(docQuery);
foreach (DocumentEntry entry in docFeed.Entries)
{
Console.WriteLine(entry.Title.Text);
}
Console.ReadKey();
Console.WriteLine();
if (File.Exists(#"testDoc.txt") == false)
{
File.WriteAllText(#"testDoc.txt", "test");
}
docService.UploadDocument(#"testDoc.txt", null); // Works Fine
docService.UploadFile(#"testDoc.txt", null, #"text/plain", false); // Throws Error
The above code will throw a GDataRequestException:
Execution of request failed: https://docs.google.com/feeds/default/private/full?convert=false
This is kind of aggrivating, seeing as this API could be so insanely helpful. Does anyone know what I am doing wrong?
After a lot of experimentation and research, I got it to work. Gonna leave this here for others in my predicament. I will leave in the using shorthands for reference.
// Start the service and set credentials
Docs.DocumentsService service = new Docs.DocumentsService("GoogleApiTest");
service.setUserCredentials("username", "password");
// Initialize the DocumentEntry
Docs.DocumentEntry newEntry = new Docs.DocumentEntry();
newEntry.Title = new Client.AtomTextConstruct(Client.AtomTextConstructElementType.Title, "Test Upload"); // Set the title
newEntry.Summary = new Client.AtomTextConstruct(Client.AtomTextConstructElementType.Summary ,"A summary goes here."); // Set the summary
newEntry.Authors.Add(new Client.AtomPerson(Client.AtomPersonType.Author, "A Person")); // Add a main author
newEntry.Contributors.Add(new Client.AtomPerson(Client.AtomPersonType.Contributor, "Another Person")); // Add a contributor
newEntry.MediaSource = new Client.MediaFileSource("testDoc.txt", "text/plain"); // The actual file to be uploading
// Create an authenticator
Client.ClientLoginAuthenticator authenticator = new Client.ClientLoginAuthenticator("GoogleApiTest", Client.ServiceNames.Documents, service.Credentials);
// Setup the uploader
Client.ResumableUpload.ResumableUploader uploader = new Client.ResumableUpload.ResumableUploader(512);
uploader.AsyncOperationProgress += (object sender, Client.AsyncOperationProgressEventArgs e) =>
{
Console.WriteLine(e.ProgressPercentage + "%"); // Progress updates
};
uploader.AsyncOperationCompleted += (object sender, Client.AsyncOperationCompletedEventArgs e) =>
{
Console.WriteLine("Upload Complete!"); // Progress Completion Notification
};
Uri uploadUri = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full?convert=false"); // "?convert=false" makes the doc be just a file
Client.AtomLink link = new Client.AtomLink(uploadUri.AbsoluteUri);
link.Rel = Client.ResumableUpload.ResumableUploader.CreateMediaRelation;
newEntry.Links.Add(link);
uploader.InsertAsync(authenticator, newEntry, new object()); // Finally upload the bloody thing
Can you check the ResponseString property of the GDataRequestException that is being thrown in order to get a detailed error message?
Capturing your requests with a tool like Fiddler will also help you a lot when trying to debug this kind of issues.

Categories

Resources