Mostrar mensagens com a etiqueta Código Fonte. Mostrar todas as mensagens
Mostrar mensagens com a etiqueta Código Fonte. Mostrar todas as mensagens

3 de abril de 2011

Criar um Ticket de autenticação SSO (Live@edu) Parte II

Este código utiliza partes e namespaces do SDK citado neste post:

http://msedulive.blogspot.com/2011/04/onde-posso-encontrar-o-liveedu-sdk-em.html

 

/// <summary>
/// Admin Center Api Binding.
/// </summary>
Microsoft.AdminCenterAPI.ManageDomain2 srvc;

public AdminCenter(string emailId, string password)
{
this.emailId = emailId;
this.password = password;
CreateAuthTicket();
}

/// <summary>
/// private method used to create the authenticated management session
/// </summary>
/// <returns>
/// The login ticket obtained for the session (not used outside of this function)
/// </returns>
private string CreateAuthTicket()
{
srvc = new Microsoft.AdminCenterAPI.ManageDomain2();


//Get the URL for obtaining the ticket
string loginUrl = srvc.GetLoginUrl(this.emailId);

//Get the template for the ticket request and replace
//the username and password placeholders
string loginTemplate = srvc.GetLoginDataTemplate().Replace("%NAME%", this.emailId).Replace("%PASSWORD%", this.password);

//Post the Login ticket to the provided URL and get the
///authorization ticket
string loginTicket = PostWebData(loginUrl, loginTemplate);

//Verify that no errors occured
if (srvc.VerifyAuthData(loginTicket))
{
//Create an instance of the
//ManageDomain2Authorization class for storing the
//ticket and ticket type
Microsoft.AdminCenterAPI.ManageDomain2Authorization srvcAuth = new Microsoft.AdminCenterAPI.ManageDomain2Authorization();

//Set the ticket type
srvcAuth.authorizationType = Microsoft.AdminCenterAPI.ManageDomain2AuthorizationType.PassportTicket;

//Set the ticket data
srvcAuth.authorizationData = loginTicket;

//Store the ManageDomain2Authorization instance
//in the Web reference
srvc.ManageDomain2AuthorizationValue = srvcAuth;
return loginTicket;
}
else
{
throw new Exception("An error occurred" + " while attempting to create an authorization ticket");
}
}



Onde posso encontrar o Live@Edu SDK em versão Avançada (Level 800)

SDK Avançado de Integração com o Live@Edu

.

Outra forma de inicializar o Exchange Web Service

Exemplo em ASPX no Page_Load()

As Flags de AppSettings são valores que vêm do web.config, podes passa-las directamente alterando os valores no código

 

/// <summary>
/// Page Load Event.
/// </summary>
/// <param name="sender">Control Invoking this event.</param>
/// <param name="e">Event Arguments.</param>
protected void Page_Load(object sender, EventArgs e)
{
//// Initialize EWS service.
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.Credentials = new WebCredentials(ConfigurationManager.AppSettings["EmailAddress"],
ConfigurationManager.AppSettings["Password"]);
service.AutodiscoverUrl(ConfigurationManager.AppSettings["EmailAddress"], delegate(string url) { return true; });
}



2 de abril de 2011

Criar uma Lista de Distribuição Dinâmica (DDL)

image

 

/// <summary>
/// Session runspace instance.
/// </summary>
private readonly SessionRunspace sessionRunspace;

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

this.sessionRunspace = sessionRunspace;
}

/// <summary>
/// Method to create Dynamic distribution list (DDL)
/// </summary>
/// <param name="ddlName">Name of the DDL</param>
/// <param name="filterExp">filter expression</param>
/// <returns>true if success</returns>
public bool CreateDDL(string ddlName, string filterExp)
{
if (string.IsNullOrEmpty(ddlName))
{
throw new ArgumentOutOfRangeException("ddlName");
}

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

try
{
var command = new PSCommand();
command.AddScript(string.Format(GroupsScripts.CreateDdlScript, ddlName, filterExp));
this.sessionRunspace.ExecuteCommand(command);
return true;
}
catch
{
return false;
}
}



Criar e Importar Sessões remotas Outlook Live

Pré-requisitos: http://msedulive.blogspot.com/2011/04/pre-requisitos-powershell.html

Antes de todas as tarefas administrativas podem ser executadas, uma sessão remota para o Outlook Live tem de ser estabelecida. Discutimos como conseguir isso na seção "powershell" usando o cliente de desktop local do Windows PowerShell. Nesta seção, discutiremos como conseguir isso de um programa c#. Abaixo está o exemplo de código para criar uma sessão.

 

// Abaixo os namespaces devem ser importados para o PowerShell.
// Estes estão disponíveis em System.Management.Automation.dll
// System.Management.Automation.dll é instalado como parte do Windows
// Instalação do Framework de gerenciamento.
using System.Management.Automation;
using System.Management.Automation.Runspaces;
// Criar espaço de execução e sessão remota para Oulook Live, que é importado para
// Este espaço de execução.
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

// Set credenciais para fazer uma conexão remota com o Outlook Live
string userName = "admin@contosouniversity.net";
string password = "password";
PSCredential cred = newPSCredential(userName, password);
// Script para definir uma variável. Esta variável é usado pelo script de nova sessão.
string setVariableScript = "Set-Variable";
PowerShell ps1 = PowerShell.Create();
PSCommand setVariableCommand = newPSCommand();
setVariableCommand.AddScript(setVariableScript);
setVariableCommand.AddParameter("Name", "Cred");
setVariableCommand.AddParameter("Value", cred);
ps1.Commands = setVariableCommand;
ps1.Runspace = runspace;
ps1.Invoke<PSObject>();



30 de março de 2011

EWS – Como criar um compromisso simples

O Exchange Web Services é muito potente, neste post vou dar um exemplo de como criar um compromisso simples, útil, rápido e eficaz.

 

// Cria o compromisso.
Appointment appointment = new Appointment(service);

// Define as propriedades do compromisso.
appointment.Subject = "Dentist Appointment";
appointment.Body = "The appointment is with Dr. Smith.";
appointment.Start = new DateTime(2009, 3, 1, 9, 0, 0);
appointment.End = appointment.Start.AddHours(2);

// Guarda o compromisso.
appointment.Save(SendInvitationsMode.SendToNone);


EWS - Como podemos determinar o ID de uma mensagem enviada

Quando enviamos uma mensagem via EWS, é bom ficarmos com o ID da mesma para tratamento com outros métodos, podemos querer gravar no SQL Server por exemplo as propriedades das mensagem, fica aqui um código simples que permite retirar o UniqueID, bem como as outras propriedades da mensagem

 

// Criar a mensagem e define algumas propriedades básicas.
EmailMessage message = new EmailMessage(service);
message.Subject = "Message Subject";
message.Body = "This message was sent by using the EWS Managed API.";
message.ToRecipients.Add("User1@example.com");

// Cria uma propriedade personalizada estendida e adicioná-lo à mensagem
Guid myPropertySetId = new Guid("{20B5C09F-7CAD-44c6-BDBF-8FCBEEA08544}");
ExtendedPropertyDefinition myExtendedPropertyDefinition = new ExtendedPropertyDefinition(myPropertySetId,
"MyExtendedPropertyName", MapiPropertyType.String);
message.SetExtendedProperty(myExtendedPropertyDefinition, "MyExtendedPropertyValue");

// Envia a mensagem e salva uma cópia.
message.SendAndSaveCopy();

// Espera um segundo (enquanto o EWS envia e salva a mensagem).
System.Threading.Thread.Sleep(1000);

// Agora, encontra a cópia gravada da mensagem usando a propriedade
ItemView view = new ItemView(5);
SearchFilter searchFilter = new SearchFilter.IsEqualTo(myExtendedPropertyDefinition, "MyExtendedPropertyValue");
view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, myExtendedPropertyDefinition);
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.SentItems, searchFilter, view);

//Processa os resultados
foreach (Item myItem in findResults.Items)
{
if (myItem is EmailMessage)
{
EmailMessage em = myItem as EmailMessage;
Console.WriteLine(em.Subject);
Console.WriteLine(em.Id.UniqueId);
}
}


27 de março de 2011

Retirar o Utilizador de um string DOMINIO\Utilizador

Se na nossa escola nos autenticarmos na AD a nossa identidade será do tipo DOMINIO\Utilizador, não seria útil ter uns métodos que retirassem a parte do DOMINIO?, ora bolas que sim :), aqui vai

Vamos apenas ficar com a parte “Utilizador”

 

/// <summary>
/// Retrieves and formats NTLM user name
/// </summary>
/// <returns>user name of currently logged in</returns>
public static string RemoveDomain(string userName)
{
userName = userName.Trim();
if (userName.Contains("\\"))
{
userName = userName.Substring(userName.IndexOf("
\\") + 1).Trim();
}
if (userName.Contains("
/"))
{
userName = userName.Substring(userName.IndexOf("
/") + 1).Trim();
}

return userName;
}

Invocar Certificado dinamicamente instalado na Certificate Store

Já falamos aqui de Certificados e de como instala-los e configura-los, agora queria demostrar como fazeres um método por forma a que o possas ir buscar dinamicamente, em operações complexas tens de adiciona-lo a algum método que necessites. Ou seja, em vez de o processo de encriptação ser feito por relação de confiança entre Servidores, podes ir buscar o certificado à store e passa-lo num HttpRequest. Para tal basta saberes o Thumb Print como é lógico e foi explicado neste post Lê Aqui.

 

public static X509Certificate2 LoadCertificate(string ThumbPrint)
{
HttpContext webContext = HttpContext.Current;

// Retrieve the Local Machine certificate store and load the x.509
// client certificate, using the certificate's thumbprint to
// identify and retrieve it from the store.
try
{
webContext.Application.Lock();

X509Store x509Store = new X509Store(StoreLocation.LocalMachine);
X509Certificate2Collection x509Collection;
x509Store.Open(OpenFlags.ReadOnly);
x509Collection = x509Store.Certificates.Find(X509FindType.FindByThumbprint, ThumbPrint, false);
x509Store.Close();
if ((x509Collection.Count == 1))
{
X509Certificate2 certificate = x509Collection[0];

try
{
AsymmetricAlgorithm privateKey = certificate.PrivateKey;
}
catch
{
throw new ApplicationException(String.Format("Private key cannot be read for the certificate with thumbprint: {0}.
Ensure WinHTTPCertCfg.exe has been used to assign permissions to the IIS Application Pool Identity
(defaults to Network Service)."
, ThumbPrint));
}

webContext.Application["Certificate"] = certificate.GetRawCertData();
return certificate;
}
else
{
throw new ApplicationException("Certificate not found!");
}
}
catch (Exception ex)
{
if (ex.Message.Contains("Private key cannot be read"))
{
throw ex;
}
throw new ApplicationException(String.Format("Unable to retreive certificate with thumbprint: {0}", ThumbPrint), ex);
}
finally
{
try
{
webContext.Application.UnLock();
}
catch { }
}
}


EWS Obter as propriedades das mensagens na Caixa de Entrada

Importante, não te esqueças do PageSize por causa da performance, se for necessário vais buscar por exemplo 20 a 20

public static Void GetInboxReceivedMessages(int pageSize)
{
ItemView view = new ItemView(pageSize, 0);
SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
FindItemsResults<Item> findResults = GetService().FindItems(WellKnownFolderName.Inbox, sf, view);

foreach (Item item in findResults.Items)
{
Console.Writeline("Id" + item.Id)
Console.Writeline("Assunto" + item.Subject)
Console.Writeline("Data Recepção" + item.Subjectitem.DateTimeReceived.ToShortDateString())
}
}



EWS Contar mensagens através do WellKnownFolderName

O WellKnownFolderName é denominado como as pastas conhecidas e comuns do Exchange, como Inbox, Sent Items, etc.., é esse folder que queres que vais passar no método seguinte bem como o máximo número de mensagens, pois se tiveres 5000 pode-se tornar lento como é óbvio.

 

Se quiseres as mensagens não lidas passas o parâmetro IsRead para false

 

/// <summary>
/// Obters the mensages lidas pasta.
/// </summary>
/// <param name="folder">The folder.</param>
/// <param name="pageSize">Size of the page.</param>
/// <returns></returns>
public static int ObterMensagesLidasPasta(WellKnownFolderName folder, int pageSize)
{
ItemView view = new ItemView(pageSize, 0);
SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true);

FindItemsResults<Item> findResults = GetService().FindItems(folder, sf, view);
return findResults.Items.Count;
}


EWS Como criar um E-mail simples

Eis um método que podes utilizar para enviar um mail simples via Exchange Web Services

Tens de adicionar a referencia ao teu projecto: Microsoft.Exchange.WebServices

/// <summary>
/// Criars the email simples.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="subject">The subject.</param>
/// <param name="body">The body.</param>
/// <param name="mailTo">The mail to.</param>
public static void CriarEmailSimples(ExchangeService service, string subject,
string body, List<string> mailTo)
{
// Create an e-mail message and identify the Exchange service.
EmailMessage message = new EmailMessage(service)
{
/* Subject*/
Subject = subject, /* Body*/
Body = new MessageBody(body)
};

// Recipients
foreach (string recipientes in mailTo)
{
message.ToRecipients.Add(recipientes);
}

// Send the mail. This makes a trip to the EWS server.
message.SendAndSaveCopy();
}



Exchange Web Services (Instanciar o Serviço) passando o ISA

Em ambientes LIve@edu muitas vezes queremos “puxar” para a nossa aplicação a informação contida no Exchange On-line, para que tal aconteça li muito acerca de Autodiscovery para aqui e Autodiscovery para ali. O problema principal é que quando estamos na nossa Escola/Empresa, e visto os Domínios estarem repartidos na Cloud e na Empresa o mesmo não vai funcionar porque não resolve de dentro, ou seja não passa no ISA, mas para passar no ISA então há que esperar que tal aconteça, e tempo é dinheiro.

 

Tipicamente passa-se o seguinte:

 

This Error event indicates that the Microsoft® Exchange Autodiscover service could not discover the Exchange Availability service that is running in a remote Active Directory® directory service forest. The Exchange Autodiscover service that runs on a Front End server that is running Exchange Server 2007 (also known as Exchange Client Access server) is a Web service that locates a mailbox. The Exchange Availability service is also a Web service that retrieves the Schedule+ Free Busy and Out-of-Office (OOF) data for that specific mailbox. This event may occur when an Exchange 2007 Client Access server and user mailbox are in different Active Directory forests. Because the Exchange Autodiscover service cannot directly connect to a mailbox that resides in a remote Active Directory forest, it requests that the Exchange Availability service that is running in the remote Active Directory forest retrieve the requested information locally.

 

CORRECÇÃO

Vou corrigir esta parte porque esta solução não é suportada pela Microsoft e pode gerar erro no Exchange Online INTERNAL SERVER ERROR, aqui vai a solução final.

A TER EM ATENÇÃO

As definições de PROXY são a da tua máquina host de domínio não de uma ligação de VM

 

A Solução que eu encontrei foi resolver o Autodiscovery de fora e apanhar o Link, sendo assim já podemos instanciar o Serviço desta forma, para o fazeres basta invocares o método GetService().Xpto

Tens de adicionar a referencia ao teu projecto: Microsoft.Exchange.WebServices

 

/// <summary>
/// Gets the service.
/// </summary>
/// <returns></returns>
public static ExchangeService GetService()
{
// Get User and Pass for Super User Live@Edu
string sUser = GetUrl.sUser;
string sPass = GetUrl.sPass;

// Create the binding.

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010)
{ /* Define credentials.*/
Credentials = new WebCredentials(sUser, sPass),
Url = new Uri("https://OTeuServerNaCloud.outlook.com/EWS/Exchange.asmx")
};
return service;
}



EXEMPLO 




Credentials = new NetworkCredential(UserXPTO, PassXPTO, Microsoft)



Código Complero




public static ExchangeService GetBinding()
{
// Create the binding.
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
//Proxy
IWebProxy proxy = new WebProxy(GetUrl.ProxyAddress, true)
{
Credentials = new NetworkCredential(GetUrl.ProxyUser, GetUrl.ProxyPass,
GetUrl.ProxyDomain)
};

WebRequest.DefaultWebProxy = proxy;
service.Credentials = new WebCredentials("admin@dominio.pt", "999999");

try
{
// Use the AutodiscoverUrl method to locate the service endpoint.
service.AutodiscoverUrl("admin@dominio.pt", RedirectionUrlValidationCallback);
}
catch (AutodiscoverRemoteException ex)
{
Console.WriteLine("Exception thrown: " + ex.Error.Message);
}
return service;
}

static bool RedirectionUrlValidationCallback(String redirectionUrl)
{
// Perform validation.
// Validation is developer dependent to ensure a safe redirect.
return true;
}

26 de março de 2011

Como obter o URL para Login via SSO (Exchange On-line)

Na Parte 1, vimos o material que nos é facultado aquando da activação do SSO, bem como o conteúdo do SDK, agora chegou a hora de por-mos em prática e agarrarmos algum código.

 

Vou exemplificar apenas para O Exchange On-line

 
Todo o código que vai visualizar neste Blog foi alterado por mim por forma a facilitar o funcionamento em integração com vários Portais, desde SharePoint, WindowsForms e ASPX.

Em grosso modo o que nós iremos necessitar para gerar o nosso código é o seguinte:

  1. O Site ID
  2. O Certeficate Thumb
  3. O Redirect URL
  4. Utilizador Master do Domínio
  5. Password Master do Domínio

Como ver o Certificate Thumb?

  1. Clica 2 vezes no Certificado e vai até:

image

Eu por uma questão de comodidade em ambientes ASPX coloco tudo no Web.config, senão vejamos:

 

Mas na realidade para que é que eu quero estes valores? tens razão ainda não expliquei. Quando se efectua um Request de login ao LiveID não vamos necessitar da password do utilizador para nada, pois o certificado e os valores conjugados (Em Cima)

Mas como? na realidade o que nós recebemos do Servidor da Microsoft é o SLT (Short Live Ticket), este ticket não é nada mais nem menos que uma série de informação encriptada que podemos ver em cima, através dos segundos que definirmos, assim ele será válido

  

Este método retornará algo do género

 
https://login.live.com/ppsecure/post.srf?wa=wsignin1.0&rpsnv=11&rver=5.5.4177.0&wp=MBI_SSL&wreply=https://outlook.com/edu&id=
0000000&slt=CeH9USwpW4RGmqNeZwnizgkQg8RQMj1assaadd9lKTY!xEZJtkyM12asdas2ec1BzXnMvXhncF7mI7RN8scT77XMbri0Tasds5pcVbNSxRcuRMIQLvCebTGWs3*n!mgXHw
 
// Examples of RedirectURL are...
//"https://outlook.com/edu" if Outlook Live
//"http://mail.live.com/default.aspx" if Hotmail
//http://skydrive.live.com/home.aspx?provision=1;



<appSettings>
<!-- LIVE@EDU SSO PARAMETROS -->
<add key="Domain" value="pt" />
<add key="SiteID" value="000000" />
<add key="certThumb" value="13 f8 e5 f0 92 43 ed a6 rt f2 05 e5 f2 de 33 5a 4d 09 83 69" />
<add key="redirectURL" value="https://outlook.com/edu" />
<add key="loginSeconds" value="5" />
<add key="WebProxy" value="" />
<add key="Scenario" value="A" />
<add key="suser" value="admin@pt" />
<add key="spass" value="admin@pt" />
</appSettings>


public static string GetShortLiveTicket(string TeuUtilizador)
{
string wlUserId = String.Format("{0}@{1}", TeuUtilizador, "https://outlook.com/edu");
LiveSLT ticket = new LiveSLT(CertThumb, SiteID, WebProxy, int.Parse(loginSeconds));
string slt = ticket.GetSLT(wlUserId, SiteID);
if ((String.IsNullOrEmpty(slt)) || (!ticket.Success))
{
_hasError = true;
return "/";
}
_hasError = false;
string result = LiveRPS.CreateRedirectString(slt, RedirectUrl, SiteID);
return result;
}


Like