É possível renomear a categoria do Outlook programaticamente?
-
18-09-2019 - |
Pergunta
Estamos desenvolvendo o suplemento do Outlook 2007. Para testar a renomeação da categoria do Outlook, adicionei o seguinte bloco de código
var session = Application.Session;
var categories = session.Categories;
var category1 = session.Categories[1];
//catefory1.Name is "Group1" before executing line below
category1.Name = "TEST!!!";
Marshal.ReleaseComObject(category1);
Marshal.ReleaseComObject(categories);
Marshal.ReleaseComObject(session);
até o final do suplemento private void ThisAddIn_Startup(object sender, EventArgs e)
método. A categoria é renomeada, mas se o Outlook estiver fechado, as linhas acima são comentadas e o Outlook será iniciado novamente - o nome da categoria não é "teste !!!" como eu esperava. É "Grupo1" como foi antes de renomear. É possível renomear a categoria do Outlook "para sempre" pelo código? Microsoft.Office.interop.outlook.category não possui métodos save () ou update () ou persist ().
PS Estamos desenvolvendo o suplemento do Outlook 2007 usando o Visual Studio 2008, .NET 3.5, C# 3. O problema é reproduzido com o Outlook 2007 SP1 e SP2. Outras versões das perspectivas não foram testadas.
Solução
Eu resolvi o problema (o problema em si parece ser o bug do Outlook 2007) usando um hack. Os links a seguir me ajudaram a criar o hack (opa, não há reputação suficiente para postar mais do que 1 link):
- http: //blogs.officezealot.com/legault/archive/2009/08/13/21577.aspx
- http://www.officekb.com/uwe/forum.aspx/outlook-prog-addins/3142/apply-categories-to-other-users-tislook-2007
- http: //help.wugnet.com/office/set-master-category-list-tislook-2007-topict1095935.html
- http: //forums.slipstick.com/showthread.php? t = 18189
- http: //msdn.microsoft.com/en-us/library/ee203806%28exchg.80%29.aspx
O hack em si está mostrando abaixo:
using System;
using System.Text;
using System.Xml;
using System.IO;
using Microsoft.Office.Interop.Outlook;
namespace OutlookHack
{
public static class OutlookCategoryHelper
{
private const string CategoryListStorageItemIdentifier = "IPM.Configuration.CategoryList";
private const string CategoryListPropertySchemaName = @"http://schemas.microsoft.com/mapi/proptag/0x7C080102";
private const string CategoriesXmlElementNamespace = "CategoryList.xsd";
private const string XmlNamespaceAttribute = "xmlns";
private const string CategoryElement = "category";
private const string NameAttribute = "name";
public static void RenameCategory(string oldName, string newName, Application outlookApplication)
{
MAPIFolder calendarFolder = outlookApplication.Session.GetDefaultFolder(
OlDefaultFolders.olFolderCalendar);
StorageItem categoryListStorageItem = calendarFolder.GetStorage(
CategoryListStorageItemIdentifier, OlStorageIdentifierType.olIdentifyByMessageClass);
if (categoryListStorageItem != null)
{
PropertyAccessor categoryListPropertyAccessor = categoryListStorageItem.PropertyAccessor;
string schemaName = CategoryListPropertySchemaName;
try
{
// next statement raises Out of Memory error if property is too big
var xmlBytes = (byte[])categoryListPropertyAccessor.GetProperty(schemaName);
// the byte array has to be translated into a string and then the XML has to be parsed
var xmlReader = XmlReader.Create(new StringReader(Encoding.UTF8.GetString(xmlBytes)));
// xmlWriter will write new category list xml with renamed category
XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = ("\t") };
var stringWriter = new StringWriter();
var xmlWriter = XmlWriter.Create(stringWriter, settings);
xmlReader.Read(); // read xml declaration
xmlWriter.WriteNode(xmlReader, true);
xmlReader.Read(); // read categories
xmlWriter.WriteStartElement(xmlReader.Name, CategoriesXmlElementNamespace);
while (xmlReader.MoveToNextAttribute())
{
if (xmlReader.Name != XmlNamespaceAttribute) // skip namespace attr
{
xmlWriter.WriteAttributeString(xmlReader.Name, xmlReader.Value);
}
}
while (xmlReader.Read())
{
switch (xmlReader.NodeType)
{
case XmlNodeType.Element: // read category
xmlWriter.WriteStartElement(CategoryElement);
while (xmlReader.MoveToNextAttribute())
{
if ((xmlReader.Name == NameAttribute) && (xmlReader.Value == oldName))
{
xmlWriter.WriteAttributeString(NameAttribute, newName);
}
else
{
xmlWriter.WriteAttributeString(xmlReader.Name, xmlReader.Value);
}
}
xmlWriter.WriteEndElement();
break;
case XmlNodeType.EndElement: // categories ended
xmlWriter.WriteEndElement();
break;
}
}
xmlReader.Close();
xmlWriter.Close();
xmlBytes = Encoding.UTF8.GetBytes(stringWriter.ToString());
categoryListPropertyAccessor.SetProperty(schemaName, xmlBytes);
categoryListStorageItem.Save();
}
catch (OutOfMemoryException)
{
// if error is "out of memory error" then the XML blob was too big
}
}
}
}
}
Este método auxiliar deve ser chamado antes da renomeação da categoria, por exemplo:
var session = Application.Session;
var categories = session.Categories;
var category1 = session.Categories[1];
//catefory1.Name is "Group1" before executing line below
OutlookCategoryHelper.RenameCategory(category1.Name, "TEST!!!", Application);
category1.Name = "TEST!!!";
Marshal.ReleaseComObject(category1);
Marshal.ReleaseComObject(categories);
Marshal.ReleaseComObject(session);
Outras dicas
Este é um bug do Outlook Introduz com o Outlook 2007 SP2.
"Considere o seguinte cenário. Você tem um aplicativo personalizado que pode ser executado para criar novas categorias no Outlook 2007. Você executa o aplicativo para criar uma nova categoria no Outlook 2007. Então, se você reiniciar o Outlook 2007, a categoria que você criou é Removido inesperadamente. Esse problema ocorre depois de instalar a atualização ou o SP2 de fevereiro. "
Há um hotfix disponível desde 30 de junho de 2009:http://support.microsoft.com/default.aspx/kb/970944/en
Atenciosamente, Tim