Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // GET api/updateContact
- [HttpGet]
- public JsonResult Get(string apiKey = "", string user = "defaultUser", string pass = "defaultPass")
- {
- // Establish the connection credentials to exchage powershell
- string connectionUri = "https://outlook.office365.com/powershell-liveid/";
- string loginPassword = pass;
- SecureString secpassword = new SecureString();
- foreach (char c in loginPassword)
- {
- secpassword.AppendChar(c);
- }
- PSCredential credential = new PSCredential(user, secpassword);
- // Create a new PowerShell Instance to connect to exhange using our credentials
- PowerShell powershell = PowerShell.Create();
- PSCommand command = new PSCommand();
- command.AddCommand("New-PSSession");
- command.AddParameter("ConfigurationName", "Microsoft.Exchange");
- command.AddParameter("ConnectionUri", new Uri(connectionUri));
- command.AddParameter("Credential", credential);
- command.AddParameter("Authentication", "Basic");
- powershell.Commands = command;
- // Run the PowerShell Instance to create a session to be used
- Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
- runspace.Open();
- powershell.Runspace = runspace;
- Collection<System.Management.Automation.PSObject> result = powershell.Invoke();
- // Ensure the connection worked
- if (powershell.Streams.Error.Count > 0 || result.Count != 1)
- {
- Collection<ErrorRecord> errors = powershell.Streams.Error.ReadAll(); // Streams property is not available
- string allErrors = "";
- if (errors != null && errors.Count > 0)
- {
- foreach (ErrorRecord er in errors)
- {
- allErrors += er.Exception.ToString() + ", ";
- }
- return new ApiFailedResponse("Failed to connect to exchange: " + allErrors).ToJsonResult();
- }
- return new ApiFailedResponse("Failed to connect to exchange").ToJsonResult();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement