2 de abril de 2011

PowerShell e C#, Criar, Importar e Fechar Sessões Outlook Live

 

using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Security;

/// <summary>
/// Powershell commands to create, import, exit session.
/// </summary>
internal class OutlookLiveSession
{
/// <summary>
/// Powreshell Runspace instance.
/// </summary>
private readonly Runspace runspace;

/// <summary>
/// Initializes a new instance of the OutlookLiveSession class.
/// </summary>
/// <param name="runspace">Runspace instance.</param>
public OutlookLiveSession(Runspace runspace)
{
if (runspace == null)
{
throw new ArgumentOutOfRangeException("runspace");
}

this.runspace = runspace;
}

#region Methods

/// <summary>
/// Create outlook live session
/// </summary>
/// <param name="userName">The user name to authenticate the session.</param>
/// <param name="password">The password to authenticate the session.</param>
/// <param name="connectionUri">Uri for creating the connection.</param>
/// <returns>Powershell Session instance.</returns>
public PSSession CreateSession(string userName, SecureString password, string connectionUri)
{
if (string.IsNullOrEmpty(userName))
{
throw new ArgumentOutOfRangeException("userName");
}

if (password == null)
{
throw new ArgumentOutOfRangeException("password");
}

if (string.IsNullOrEmpty(connectionUri))
{
throw new ArgumentOutOfRangeException("connectionUri");
}

this.runspace.SetCredential(userName, password);

var command = new PSCommand();
command.AddScript(string.Format(SessionScripts.NewSessionScript, connectionUri));
var result = this.runspace.ExecuteCommand<PSSession>(command);
return result[0];
}

/// <summary>
/// Import Powershell Session.
/// </summary>
/// <param name="session">Powershell Session.</param>
public void ImportSession(PSSession session)
{
if (session == null)
{
throw new ArgumentOutOfRangeException("session");
}

var command = new PSCommand();
command.AddCommand(SessionScripts.ImportSessionScript);
command.AddParameter(Constants.Session, session);
this.runspace.ExecuteCommand(command);
}

/// <summary>
/// Exit Powershell Session.
/// </summary>
/// <param name="session">Powershell Session.</param>
public void ExitSession(PSSession session)
{
if (session == null)
{
throw new ArgumentOutOfRangeException("session");
}

var command = new PSCommand();
command.AddCommand(SessionScripts.ExitSessionScript);
command.AddParameter(Constants.Session, session);
this.runspace.ExecuteCommand(command);
}

#endregion
}



Sem comentários:

Enviar um comentário

Like