Code quality changes

This commit is contained in:
Robin 2016-09-22 20:40:13 +02:00
commit 610f45d082
189 changed files with 4609 additions and 5203 deletions

View file

@ -32,18 +32,17 @@ namespace GreenshotOfficePlugin {
/// Description of PowerpointDestination.
/// </summary>
public class ExcelDestination : AbstractDestination {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ExcelDestination));
private const int ICON_APPLICATION = 0;
private const int ICON_WORKBOOK = 1;
private static readonly string exePath = null;
private readonly string workbookName = null;
private const int IconApplication = 0;
private const int IconWorkbook = 1;
private static readonly string ExePath;
private readonly string _workbookName;
static ExcelDestination() {
exePath = PluginUtils.GetExePath("EXCEL.EXE");
if (exePath != null && File.Exists(exePath)) {
ExePath = PluginUtils.GetExePath("EXCEL.EXE");
if (ExePath != null && File.Exists(ExePath)) {
WindowDetails.AddProcessToExcludeFromFreeze("excel");
} else {
exePath = null;
ExePath = null;
}
}
@ -51,51 +50,20 @@ namespace GreenshotOfficePlugin {
}
public ExcelDestination(string workbookName) {
this.workbookName = workbookName;
_workbookName = workbookName;
}
public override string Designation {
get {
return "Excel";
}
}
public override string Designation => "Excel";
public override string Description {
get {
if (workbookName == null) {
return "Microsoft Excel";
} else {
return workbookName;
}
}
}
public override string Description => _workbookName ?? "Microsoft Excel";
public override int Priority {
get {
return 5;
}
}
public override bool isDynamic {
get {
return true;
}
}
public override int Priority => 5;
public override bool isActive {
get {
return base.isActive && exePath != null;
}
}
public override bool IsDynamic => true;
public override Image DisplayIcon {
get {
if (!string.IsNullOrEmpty(workbookName)) {
return PluginUtils.GetCachedExeIcon(exePath, ICON_WORKBOOK);
}
return PluginUtils.GetCachedExeIcon(exePath, ICON_APPLICATION);
}
}
public override bool IsActive => base.IsActive && ExePath != null;
public override Image DisplayIcon => PluginUtils.GetCachedExeIcon(ExePath, !string.IsNullOrEmpty(_workbookName) ? IconWorkbook : IconApplication);
public override IEnumerable<IDestination> DynamicDestinations() {
foreach (string workbookName in ExcelExporter.GetWorkbooks()) {
@ -111,8 +79,8 @@ namespace GreenshotOfficePlugin {
imageFile = ImageOutput.SaveNamedTmpFile(surface, captureDetails, new SurfaceOutputSettings().PreventGreenshotFormat());
createdFile = true;
}
if (workbookName != null) {
ExcelExporter.InsertIntoExistingWorkbook(workbookName, imageFile, surface.Image.Size);
if (_workbookName != null) {
ExcelExporter.InsertIntoExistingWorkbook(_workbookName, imageFile, surface.Image.Size);
} else {
ExcelExporter.InsertIntoNewWorkbook(imageFile, surface.Image.Size);
}

View file

@ -32,8 +32,8 @@ namespace GreenshotOfficePlugin {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(WordDestination));
private const int ICON_APPLICATION = 0;
public const string DESIGNATION = "OneNote";
private static readonly string exePath = null;
private readonly OneNotePage page = null;
private static readonly string exePath;
private readonly OneNotePage page;
static OneNoteDestination() {
exePath = PluginUtils.GetExePath("ONENOTE.EXE");
@ -74,15 +74,15 @@ namespace GreenshotOfficePlugin {
}
}
public override bool isDynamic {
public override bool IsDynamic {
get {
return true;
}
}
public override bool isActive {
public override bool IsActive {
get {
return base.isActive && exePath != null;
return base.IsActive && exePath != null;
}
}

View file

@ -34,31 +34,30 @@ namespace GreenshotOfficePlugin {
/// Description of OutlookDestination.
/// </summary>
public class OutlookDestination : AbstractDestination {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OutlookDestination));
private const int ICON_APPLICATION = 0;
private const int ICON_MEETING = 2;
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(OutlookDestination));
private const int IconApplication = 0;
private const int IconMeeting = 2;
private static readonly Image mailIcon = GreenshotResources.getImage("Email.Image");
private static readonly OfficeConfiguration conf = IniConfig.GetIniSection<OfficeConfiguration>();
private static readonly string exePath = null;
private static readonly bool isActiveFlag = false;
private static readonly string mapiClient = "Microsoft Outlook";
public const string DESIGNATION = "Outlook";
private readonly string outlookInspectorCaption;
private readonly OlObjectClass outlookInspectorType;
private static readonly Image MailIcon = GreenshotResources.getImage("Email.Image");
private static readonly OfficeConfiguration OfficeConfig = IniConfig.GetIniSection<OfficeConfiguration>();
private static readonly string ExePath;
private static readonly bool IsActiveFlag;
private const string MapiClient = "Microsoft Outlook";
private readonly string _outlookInspectorCaption;
private readonly OlObjectClass _outlookInspectorType;
static OutlookDestination() {
if (EmailConfigHelper.HasOutlook()) {
isActiveFlag = true;
IsActiveFlag = true;
}
exePath = PluginUtils.GetExePath("OUTLOOK.EXE");
if (exePath != null && File.Exists(exePath)) {
ExePath = PluginUtils.GetExePath("OUTLOOK.EXE");
if (ExePath != null && File.Exists(ExePath)) {
WindowDetails.AddProcessToExcludeFromFreeze("outlook");
} else {
exePath = null;
ExePath = null;
}
if (exePath == null) {
isActiveFlag = false;
if (ExePath == null) {
IsActiveFlag = false;
}
}
@ -66,62 +65,34 @@ namespace GreenshotOfficePlugin {
}
public OutlookDestination(string outlookInspectorCaption, OlObjectClass outlookInspectorType) {
this.outlookInspectorCaption = outlookInspectorCaption;
this.outlookInspectorType = outlookInspectorType;
_outlookInspectorCaption = outlookInspectorCaption;
_outlookInspectorType = outlookInspectorType;
}
public override string Designation {
get {
return DESIGNATION;
}
}
public override string Designation => "Outlook";
public override string Description {
get {
if (outlookInspectorCaption == null) {
return mapiClient;
} else {
return outlookInspectorCaption;
}
}
}
public override string Description => _outlookInspectorCaption ?? MapiClient;
public override int Priority {
get {
return 3;
}
}
public override int Priority => 3;
public override bool isActive {
get {
return base.isActive && isActiveFlag;
}
}
public override bool IsActive => base.IsActive && IsActiveFlag;
public override bool isDynamic {
get {
return true;
}
}
public override bool IsDynamic => true;
public override Keys EditorShortcutKeys {
get {
return Keys.Control | Keys.E;
}
}
public override Keys EditorShortcutKeys => Keys.Control | Keys.E;
public override Image DisplayIcon {
get {
if (outlookInspectorCaption != null) {
if (OlObjectClass.olAppointment.Equals(outlookInspectorType)) {
// Make sure we loaded the icon, maybe the configuration has been changed!
return PluginUtils.GetCachedExeIcon(exePath, ICON_MEETING);
} else {
return mailIcon;
}
} else {
return PluginUtils.GetCachedExeIcon(exePath, ICON_APPLICATION);
get
{
if (_outlookInspectorCaption == null)
{
return PluginUtils.GetCachedExeIcon(ExePath, IconApplication);
}
if (OlObjectClass.olAppointment.Equals(_outlookInspectorType)) {
// Make sure we loaded the icon, maybe the configuration has been changed!
return PluginUtils.GetCachedExeIcon(ExePath, IconMeeting);
}
return MailIcon;
}
}
@ -148,7 +119,7 @@ namespace GreenshotOfficePlugin {
if (tmpFile == null || surface.Modified || !Regex.IsMatch(tmpFile, @".*(\.png|\.gif|\.jpg|\.jpeg|\.tiff|\.bmp)$")) {
tmpFile = ImageOutput.SaveNamedTmpFile(surface, captureDetails, new SurfaceOutputSettings().PreventGreenshotFormat());
} else {
LOG.InfoFormat("Using already available file: {0}", tmpFile);
Log.InfoFormat("Using already available file: {0}", tmpFile);
}
// Create a attachment name for the image
@ -163,15 +134,17 @@ namespace GreenshotOfficePlugin {
// Make sure it's "clean" so it doesn't corrupt the header
attachmentName = Regex.Replace(attachmentName, @"[^\x20\d\w]", "");
if (outlookInspectorCaption != null) {
OutlookEmailExporter.ExportToInspector(outlookInspectorCaption, tmpFile, attachmentName);
if (_outlookInspectorCaption != null) {
OutlookEmailExporter.ExportToInspector(_outlookInspectorCaption, tmpFile, attachmentName);
exportInformation.ExportMade = true;
} else {
if (!manuallyInitiated) {
IDictionary<string, OlObjectClass> inspectorCaptions = OutlookEmailExporter.RetrievePossibleTargets();
var inspectorCaptions = OutlookEmailExporter.RetrievePossibleTargets();
if (inspectorCaptions != null && inspectorCaptions.Count > 0) {
List<IDestination> destinations = new List<IDestination>();
destinations.Add(new OutlookDestination());
var destinations = new List<IDestination>
{
new OutlookDestination()
};
foreach (string inspectorCaption in inspectorCaptions.Keys) {
destinations.Add(new OutlookDestination(inspectorCaption, inspectorCaptions[inspectorCaption]));
}
@ -179,7 +152,7 @@ namespace GreenshotOfficePlugin {
return ShowPickerMenu(false, surface, captureDetails, destinations);
}
} else {
exportInformation.ExportMade = OutlookEmailExporter.ExportToOutlook(conf.OutlookEmailFormat, tmpFile, FilenameHelper.FillPattern(conf.EmailSubjectPattern, captureDetails, false), attachmentName, conf.EmailTo, conf.EmailCC, conf.EmailBCC, null);
exportInformation.ExportMade = OutlookEmailExporter.ExportToOutlook(OfficeConfig.OutlookEmailFormat, tmpFile, FilenameHelper.FillPattern(OfficeConfig.EmailSubjectPattern, captureDetails, false), attachmentName, OfficeConfig.EmailTo, OfficeConfig.EmailCC, OfficeConfig.EmailBCC, null);
}
}
ProcessExport(exportInformation, surface);

View file

@ -32,19 +32,18 @@ namespace GreenshotOfficePlugin {
/// Description of PowerpointDestination.
/// </summary>
public class PowerpointDestination : AbstractDestination {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PowerpointDestination));
private const int ICON_APPLICATION = 0;
private const int ICON_PRESENTATION = 1;
private const int IconApplication = 0;
private const int IconPresentation = 1;
private static readonly string exePath = null;
private readonly string presentationName = null;
private static readonly string ExePath;
private readonly string _presentationName;
static PowerpointDestination() {
exePath = PluginUtils.GetExePath("POWERPNT.EXE");
if (exePath != null && File.Exists(exePath)) {
ExePath = PluginUtils.GetExePath("POWERPNT.EXE");
if (ExePath != null && File.Exists(ExePath)) {
WindowDetails.AddProcessToExcludeFromFreeze("powerpnt");
} else {
exePath = null;
ExePath = null;
}
}
@ -52,50 +51,34 @@ namespace GreenshotOfficePlugin {
}
public PowerpointDestination(string presentationName) {
this.presentationName = presentationName;
_presentationName = presentationName;
}
public override string Designation {
get {
return "Powerpoint";
}
}
public override string Designation => "Powerpoint";
public override string Description {
get {
if (presentationName == null) {
get
{
if (_presentationName == null) {
return "Microsoft Powerpoint";
} else {
return presentationName;
}
return _presentationName;
}
}
public override int Priority {
get {
return 4;
}
}
public override bool isDynamic {
get {
return true;
}
}
public override int Priority => 4;
public override bool isActive {
get {
return base.isActive && exePath != null;
}
}
public override bool IsDynamic => true;
public override bool IsActive => base.IsActive && ExePath != null;
public override Image DisplayIcon {
get {
if (!string.IsNullOrEmpty(presentationName)) {
return PluginUtils.GetCachedExeIcon(exePath, ICON_PRESENTATION);
if (!string.IsNullOrEmpty(_presentationName)) {
return PluginUtils.GetCachedExeIcon(ExePath, IconPresentation);
}
return PluginUtils.GetCachedExeIcon(exePath, ICON_APPLICATION);
return PluginUtils.GetCachedExeIcon(ExePath, IconApplication);
}
}
@ -113,14 +96,13 @@ namespace GreenshotOfficePlugin {
tmpFile = ImageOutput.SaveNamedTmpFile(surface, captureDetails, new SurfaceOutputSettings().PreventGreenshotFormat());
imageSize = surface.Image.Size;
}
if (presentationName != null) {
exportInformation.ExportMade = PowerpointExporter.ExportToPresentation(presentationName, tmpFile, imageSize, captureDetails.Title);
if (_presentationName != null) {
exportInformation.ExportMade = PowerpointExporter.ExportToPresentation(_presentationName, tmpFile, imageSize, captureDetails.Title);
} else {
if (!manuallyInitiated) {
List<string> presentations = PowerpointExporter.GetPowerpointPresentations();
var presentations = PowerpointExporter.GetPowerpointPresentations();
if (presentations != null && presentations.Count > 0) {
List<IDestination> destinations = new List<IDestination>();
destinations.Add(new PowerpointDestination());
var destinations = new List<IDestination> {new PowerpointDestination()};
foreach (string presentation in presentations) {
destinations.Add(new PowerpointDestination(presentation));
}

View file

@ -33,16 +33,16 @@ namespace GreenshotOfficePlugin {
/// Description of EmailDestination.
/// </summary>
public class WordDestination : AbstractDestination {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(WordDestination));
private const int ICON_APPLICATION = 0;
private const int ICON_DOCUMENT = 1;
private static readonly string exePath = null;
private readonly string documentCaption = null;
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(WordDestination));
private const int IconApplication = 0;
private const int IconDocument = 1;
private static readonly string ExePath;
private readonly string _documentCaption;
static WordDestination() {
exePath = PluginUtils.GetExePath("WINWORD.EXE");
if (exePath != null && !File.Exists(exePath)) {
exePath = null;
ExePath = PluginUtils.GetExePath("WINWORD.EXE");
if (ExePath != null && !File.Exists(ExePath)) {
ExePath = null;
}
}
@ -51,51 +51,20 @@ namespace GreenshotOfficePlugin {
}
public WordDestination(string wordCaption) {
documentCaption = wordCaption;
_documentCaption = wordCaption;
}
public override string Designation {
get {
return "Word";
}
}
public override string Designation => "Word";
public override string Description {
get {
if (documentCaption == null) {
return "Microsoft Word";
} else {
return documentCaption;
}
}
}
public override string Description => _documentCaption ?? "Microsoft Word";
public override int Priority {
get {
return 4;
}
}
public override bool isDynamic {
get {
return true;
}
}
public override int Priority => 4;
public override bool isActive {
get {
return base.isActive && exePath != null;
}
}
public override bool IsDynamic => true;
public override Image DisplayIcon {
get {
if (!string.IsNullOrEmpty(documentCaption)) {
return PluginUtils.GetCachedExeIcon(exePath, ICON_DOCUMENT);
}
return PluginUtils.GetCachedExeIcon(exePath, ICON_APPLICATION);
}
}
public override bool IsActive => base.IsActive && ExePath != null;
public override Image DisplayIcon => PluginUtils.GetCachedExeIcon(ExePath, !string.IsNullOrEmpty(_documentCaption) ? IconDocument : IconApplication);
public override IEnumerable<IDestination> DynamicDestinations() {
foreach (string wordCaption in WordExporter.GetWordDocuments()) {
@ -109,26 +78,28 @@ namespace GreenshotOfficePlugin {
if (tmpFile == null || surface.Modified || !Regex.IsMatch(tmpFile, @".*(\.png|\.gif|\.jpg|\.jpeg|\.tiff|\.bmp)$")) {
tmpFile = ImageOutput.SaveNamedTmpFile(surface, captureDetails, new SurfaceOutputSettings().PreventGreenshotFormat());
}
if (documentCaption != null) {
if (_documentCaption != null) {
try {
WordExporter.InsertIntoExistingDocument(documentCaption, tmpFile);
WordExporter.InsertIntoExistingDocument(_documentCaption, tmpFile);
exportInformation.ExportMade = true;
} catch (Exception) {
try {
WordExporter.InsertIntoExistingDocument(documentCaption, tmpFile);
WordExporter.InsertIntoExistingDocument(_documentCaption, tmpFile);
exportInformation.ExportMade = true;
} catch (Exception ex) {
LOG.Error(ex);
Log.Error(ex);
// TODO: Change to general logic in ProcessExport
surface.SendMessageEvent(this, SurfaceMessageTyp.Error, Language.GetFormattedString("destination_exportfailed", Description));
}
}
} else {
if (!manuallyInitiated) {
List<string> documents = WordExporter.GetWordDocuments();
var documents = WordExporter.GetWordDocuments();
if (documents != null && documents.Count > 0) {
List<IDestination> destinations = new List<IDestination>();
destinations.Add(new WordDestination());
var destinations = new List<IDestination>
{
new WordDestination()
};
foreach (string document in documents) {
destinations.Add(new WordDestination(document));
}
@ -145,7 +116,7 @@ namespace GreenshotOfficePlugin {
WordExporter.InsertIntoNewDocument(tmpFile, null, null);
exportInformation.ExportMade = true;
} catch (Exception ex) {
LOG.Error(ex);
Log.Error(ex);
// TODO: Change to general logic in ProcessExport
surface.SendMessageEvent(this, SurfaceMessageTyp.Error, Language.GetFormattedString("destination_exportfailed", Description));
}

View file

@ -22,14 +22,11 @@ using System;
using System.Collections.Generic;
using System.Reflection;
using System.Drawing;
using GreenshotOfficePlugin;
using Greenshot.IniFile;
namespace Greenshot.Interop.Office {
public class ExcelExporter {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ExcelExporter));
private static readonly OfficeConfiguration officeConfiguration = IniConfig.GetIniSection<OfficeConfiguration>();
private static Version excelVersion;
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ExcelExporter));
private static Version _excelVersion;
/// <summary>
/// Get all currently opened workbooks
@ -60,6 +57,7 @@ namespace Greenshot.Interop.Office {
/// </summary>
/// <param name="workbookName"></param>
/// <param name="tmpFile"></param>
/// <param name="imageSize"></param>
public static void InsertIntoExistingWorkbook(string workbookName, string tmpFile, Size imageSize) {
using (IExcelApplication excelApplication = GetExcelApplication()) {
if (excelApplication == null) {
@ -147,16 +145,16 @@ namespace Greenshot.Interop.Office {
/// </summary>
/// <param name="excelApplication"></param>
private static void InitializeVariables(IExcelApplication excelApplication) {
if (excelApplication == null || excelVersion != null) {
if (excelApplication == null || _excelVersion != null) {
return;
}
try {
excelVersion = new Version(excelApplication.Version);
LOG.InfoFormat("Using Excel {0}", excelVersion);
_excelVersion = new Version(excelApplication.Version);
Log.InfoFormat("Using Excel {0}", _excelVersion);
} catch (Exception exVersion) {
LOG.Error(exVersion);
LOG.Warn("Assuming Excel version 1997.");
excelVersion = new Version((int)OfficeVersion.OFFICE_97, 0, 0, 0);
Log.Error(exVersion);
Log.Warn("Assuming Excel version 1997.");
_excelVersion = new Version((int)OfficeVersion.OFFICE_97, 0, 0, 0);
}
}
}

View file

@ -30,11 +30,10 @@ using System.Xml;
namespace Greenshot.Interop.Office {
public class OneNoteExporter {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OneNoteExporter));
private const string XML_IMAGE_CONTENT = "<one:Image format=\"png\"><one:Size width=\"{1}.0\" height=\"{2}.0\" isSetByUser=\"true\" /><one:Data>{0}</one:Data></one:Image>";
private const string XML_OUTLINE = "<?xml version=\"1.0\"?><one:Page xmlns:one=\"{2}\" ID=\"{1}\"><one:Title><one:OE><one:T><![CDATA[{3}]]></one:T></one:OE></one:Title>{0}</one:Page>";
private const string ONENOTE_NAMESPACE_2007 = "http://schemas.microsoft.com/office/onenote/2007/onenote";
private const string ONENOTE_NAMESPACE_2010 = "http://schemas.microsoft.com/office/onenote/2010/onenote";
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(OneNoteExporter));
private const string XmlImageContent = "<one:Image format=\"png\"><one:Size width=\"{1}.0\" height=\"{2}.0\" isSetByUser=\"true\" /><one:Data>{0}</one:Data></one:Image>";
private const string XmlOutline = "<?xml version=\"1.0\"?><one:Page xmlns:one=\"{2}\" ID=\"{1}\"><one:Title><one:OE><one:T><![CDATA[{3}]]></one:T></one:OE></one:Title>{0}</one:Page>";
private const string OnenoteNamespace2010 = "http://schemas.microsoft.com/office/onenote/2010/onenote";
/// <summary>
/// Create a new page in the "unfiled notes section", with the title of the capture, and export the capture there.
@ -44,10 +43,10 @@ namespace Greenshot.Interop.Office {
public static bool ExportToNewPage(ISurface surfaceToUpload) {
using(IOneNoteApplication oneNoteApplication = COMWrapper.GetOrCreateInstance<IOneNoteApplication>()) {
OneNotePage newPage = new OneNotePage();
string unfiledNotesSectionID = GetSectionID(oneNoteApplication, SpecialLocation.slUnfiledNotesSection);
if(unfiledNotesSectionID != null) {
string pageId = "";
oneNoteApplication.CreateNewPage(unfiledNotesSectionID, out pageId, NewPageStyle.npsDefault);
string unfiledNotesSectionId = GetSectionId(oneNoteApplication, SpecialLocation.slUnfiledNotesSection);
if(unfiledNotesSectionId != null) {
string pageId;
oneNoteApplication.CreateNewPage(unfiledNotesSectionId, out pageId, NewPageStyle.npsDefault);
newPage.ID = pageId;
// Set the new name, this is automatically done in the export to page
newPage.Name = surfaceToUpload.CaptureDetails.Title;
@ -57,30 +56,6 @@ namespace Greenshot.Interop.Office {
return false;
}
/// <summary>
/// Can be used to change the title of a page
/// </summary>
/// <param name="oneNoteApplication"></param>
/// <param name="pageId"></param>
/// <param name="title"></param>
private static void UpdatePageTitle(IOneNoteApplication oneNoteApplication, string pageId, string title) {
try {
string pageXML = "";
oneNoteApplication.GetPageContent(pageId, out pageXML, PageInfo.piAll, XMLSchema.xsCurrent);
XmlDocument doc = new XmlDocument();
doc.LoadXml(pageXML);
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);
namespaceManager.AddNamespace("one", ONENOTE_NAMESPACE_2010);
doc.SelectSingleNode("//one:T", namespaceManager).InnerText = title;
// Update the page
oneNoteApplication.UpdatePageContent(doc.OuterXml, DateTime.MinValue, XMLSchema.xs2010, true);
} catch(Exception ex) {
LOG.Warn("Couldn't set page title.", ex);
}
}
/// <summary>
/// Export the capture to the specified page
/// </summary>
@ -108,14 +83,14 @@ namespace Greenshot.Interop.Office {
SurfaceOutputSettings pngOutputSettings = new SurfaceOutputSettings(OutputFormat.png, 100, false);
ImageOutput.SaveToStream(surfaceToUpload, pngStream, pngOutputSettings);
string base64String = Convert.ToBase64String(pngStream.GetBuffer());
string imageXmlStr = string.Format(XML_IMAGE_CONTENT, base64String, surfaceToUpload.Image.Width, surfaceToUpload.Image.Height);
string pageChangesXml = string.Format(XML_OUTLINE, new object[] { imageXmlStr, page.ID, ONENOTE_NAMESPACE_2010, page.Name });
LOG.InfoFormat("Sending XML: {0}", pageChangesXml);
string imageXmlStr = string.Format(XmlImageContent, base64String, surfaceToUpload.Image.Width, surfaceToUpload.Image.Height);
string pageChangesXml = string.Format(XmlOutline, imageXmlStr, page.ID, OnenoteNamespace2010, page.Name);
Log.InfoFormat("Sending XML: {0}", pageChangesXml);
oneNoteApplication.UpdatePageContent(pageChangesXml, DateTime.MinValue, XMLSchema.xs2010, false);
try {
oneNoteApplication.NavigateTo(page.ID, null, false);
} catch(Exception ex) {
LOG.Warn("Unable to navigate to the target page", ex);
Log.Warn("Unable to navigate to the target page", ex);
}
return true;
}
@ -127,17 +102,17 @@ namespace Greenshot.Interop.Office {
/// <param name="oneNoteApplication"></param>
/// <param name="specialLocation">SpecialLocation</param>
/// <returns>string with section ID</returns>
private static string GetSectionID(IOneNoteApplication oneNoteApplication, SpecialLocation specialLocation) {
private static string GetSectionId(IOneNoteApplication oneNoteApplication, SpecialLocation specialLocation) {
if(oneNoteApplication == null) {
return null;
}
string unfiledNotesPath = "";
string unfiledNotesPath;
oneNoteApplication.GetSpecialLocation(specialLocation, out unfiledNotesPath);
string notebookXml = "";
string notebookXml;
oneNoteApplication.GetHierarchy("", HierarchyScope.hsPages, out notebookXml, XMLSchema.xs2010);
if(!string.IsNullOrEmpty(notebookXml)) {
LOG.Debug(notebookXml);
Log.Debug(notebookXml);
StringReader reader = null;
try {
reader = new StringReader(notebookXml);
@ -152,10 +127,9 @@ namespace Greenshot.Interop.Office {
}
}
}
} finally {
if(reader != null) {
reader.Dispose();
}
} finally
{
reader?.Dispose();
}
}
return null;
@ -170,10 +144,10 @@ namespace Greenshot.Interop.Office {
try {
using (IOneNoteApplication oneNoteApplication = COMWrapper.GetOrCreateInstance<IOneNoteApplication>()) {
if (oneNoteApplication != null) {
string notebookXml = "";
string notebookXml;
oneNoteApplication.GetHierarchy("", HierarchyScope.hsPages, out notebookXml, XMLSchema.xs2010);
if (!string.IsNullOrEmpty(notebookXml)) {
LOG.Debug(notebookXml);
Log.Debug(notebookXml);
StringReader reader = null;
try {
reader = new StringReader(notebookXml);
@ -185,18 +159,22 @@ namespace Greenshot.Interop.Office {
if ("one:Notebook".Equals(xmlReader.Name)) {
string id = xmlReader.GetAttribute("ID");
if (id != null && (currentNotebook == null || !id.Equals(currentNotebook.ID))) {
currentNotebook = new OneNoteNotebook();
currentNotebook.ID = xmlReader.GetAttribute("ID");
currentNotebook.Name = xmlReader.GetAttribute("name");
currentNotebook = new OneNoteNotebook
{
ID = xmlReader.GetAttribute("ID"),
Name = xmlReader.GetAttribute("name")
};
}
}
if ("one:Section".Equals(xmlReader.Name)) {
string id = xmlReader.GetAttribute("ID");
if (id != null && (currentSection == null || !id.Equals(currentSection.ID))) {
currentSection = new OneNoteSection();
currentSection.ID = xmlReader.GetAttribute("ID");
currentSection.Name = xmlReader.GetAttribute("name");
currentSection.Parent = currentNotebook;
currentSection = new OneNoteSection
{
ID = xmlReader.GetAttribute("ID"),
Name = xmlReader.GetAttribute("name"),
Parent = currentNotebook
};
}
}
if ("one:Page".Equals(xmlReader.Name)) {
@ -204,10 +182,12 @@ namespace Greenshot.Interop.Office {
if ("true".Equals(xmlReader.GetAttribute("isInRecycleBin"))) {
continue;
}
OneNotePage page = new OneNotePage();
page.Parent = currentSection;
page.Name = xmlReader.GetAttribute("name");
page.ID = xmlReader.GetAttribute("ID");
OneNotePage page = new OneNotePage
{
Parent = currentSection,
Name = xmlReader.GetAttribute("name"),
ID = xmlReader.GetAttribute("ID")
};
if (page.ID == null || page.Name == null) {
continue;
}
@ -216,27 +196,26 @@ namespace Greenshot.Interop.Office {
}
}
}
} finally {
if (reader != null) {
reader.Dispose();
}
} finally
{
reader?.Dispose();
}
}
}
}
} catch (COMException cEx) {
if (cEx.ErrorCode == unchecked((int)0x8002801D)) {
LOG.Warn("Wrong registry keys, to solve this remove the OneNote key as described here: http://microsoftmercenary.com/wp/outlook-excel-interop-calls-breaking-solved/");
Log.Warn("Wrong registry keys, to solve this remove the OneNote key as described here: http://microsoftmercenary.com/wp/outlook-excel-interop-calls-breaking-solved/");
}
LOG.Warn("Problem retrieving onenote destinations, ignoring: ", cEx);
Log.Warn("Problem retrieving onenote destinations, ignoring: ", cEx);
} catch (Exception ex) {
LOG.Warn("Problem retrieving onenote destinations, ignoring: ", ex);
Log.Warn("Problem retrieving onenote destinations, ignoring: ", ex);
}
pages.Sort(delegate(OneNotePage p1, OneNotePage p2) {
if(p1.IsCurrentlyViewed || p2.IsCurrentlyViewed) {
return p2.IsCurrentlyViewed.CompareTo(p1.IsCurrentlyViewed);
}
return p1.DisplayName.CompareTo(p2.DisplayName);
return String.Compare(p1.DisplayName, p2.DisplayName, StringComparison.Ordinal);
});
return pages;
}

View file

@ -33,18 +33,18 @@ namespace Greenshot.Interop.Office {
/// Outlook exporter has all the functionality to export to outlook
/// </summary>
public class OutlookEmailExporter {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OutlookEmailExporter));
private static readonly OfficeConfiguration conf = IniConfig.GetIniSection<OfficeConfiguration>();
private static readonly string SIGNATURE_PATH = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Signatures");
private static Version outlookVersion = null;
private static string currentUser = null;
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(OutlookEmailExporter));
private static readonly OfficeConfiguration OfficeConfig = IniConfig.GetIniSection<OfficeConfiguration>();
private static readonly string SignaturePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Signatures");
private static Version _outlookVersion;
private static string _currentUser;
// The signature key can be found at:
// HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\<DefaultProfile>\9375CFF0413111d3B88A00104B2A6676\<xxxx> [New Signature]
private const string PROFILES_KEY = @"Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\";
private const string ACCOUNT_KEY = "9375CFF0413111d3B88A00104B2A6676";
private const string NEW_SIGNATURE_VALUE = "New Signature";
private const string DEFAULT_PROFILE_VALUE = "DefaultProfile";
private const string ProfilesKey = @"Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\";
private const string AccountKey = "9375CFF0413111d3B88A00104B2A6676";
private const string NewSignatureValue = "New Signature";
private const string DefaultProfileValue = "DefaultProfile";
/// <summary>
/// A method to retrieve all inspectors which can act as an export target
@ -58,12 +58,12 @@ namespace Greenshot.Interop.Office {
return null;
}
if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2013) {
if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2013) {
// Check inline "panel" for Outlook 2013
using (var activeExplorer = outlookApplication.ActiveExplorer()) {
if (activeExplorer != null) {
using (var inlineResponse = activeExplorer.ActiveInlineResponse) {
if (canExportToInspector(inlineResponse)) {
if (CanExportToInspector(inlineResponse)) {
OlObjectClass currentItemClass = inlineResponse.Class;
inspectorCaptions.Add(activeExplorer.Caption, currentItemClass);
}
@ -77,7 +77,7 @@ namespace Greenshot.Interop.Office {
for (int i = 1; i <= inspectors.Count; i++) {
using (IInspector inspector = outlookApplication.Inspectors[i]) {
using (IItem currentItem = inspector.CurrentItem) {
if (canExportToInspector(currentItem)) {
if (CanExportToInspector(currentItem)) {
OlObjectClass currentItemClass = currentItem.Class;
inspectorCaptions.Add(inspector.Caption, currentItemClass);
}
@ -88,7 +88,7 @@ namespace Greenshot.Interop.Office {
}
}
} catch (Exception ex) {
LOG.Warn("Problem retrieving word destinations, ignoring: ", ex);
Log.Warn("Problem retrieving word destinations, ignoring: ", ex);
}
return inspectorCaptions;
}
@ -98,29 +98,28 @@ namespace Greenshot.Interop.Office {
/// </summary>
/// <param name="currentItem">the Item to check</param>
/// <returns></returns>
private static bool canExportToInspector(IItem currentItem) {
private static bool CanExportToInspector(IItem currentItem) {
try {
if (currentItem != null) {
OlObjectClass currentItemClass = currentItem.Class;
if (OlObjectClass.olMail.Equals(currentItemClass)) {
MailItem mailItem = (MailItem)currentItem;
//MailItem mailItem = COMWrapper.Cast<MailItem>(currentItem);
LOG.DebugFormat("Mail sent: {0}", mailItem.Sent);
Log.DebugFormat("Mail sent: {0}", mailItem.Sent);
if (!mailItem.Sent) {
return true;
}
} else if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2010 && conf.OutlookAllowExportInMeetings && OlObjectClass.olAppointment.Equals(currentItemClass)) {
} else if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2010 && OfficeConfig.OutlookAllowExportInMeetings && OlObjectClass.olAppointment.Equals(currentItemClass)) {
//AppointmentItem appointmentItem = COMWrapper.Cast<AppointmentItem>(currentItem);
AppointmentItem appointmentItem = (AppointmentItem)currentItem;
if (string.IsNullOrEmpty(appointmentItem.Organizer) || (currentUser != null && currentUser.Equals(appointmentItem.Organizer))) {
if (string.IsNullOrEmpty(appointmentItem.Organizer) || (_currentUser != null && _currentUser.Equals(appointmentItem.Organizer))) {
return true;
} else {
LOG.DebugFormat("Not exporting, as organizer is {1} and currentuser {2}", appointmentItem.Organizer, currentUser);
}
Log.DebugFormat("Not exporting, as organizer is {0} and currentuser {1}", appointmentItem.Organizer, _currentUser);
}
}
} catch (Exception ex) {
LOG.WarnFormat("Couldn't process item due to: {0}", ex.Message);
Log.WarnFormat("Couldn't process item due to: {0}", ex.Message);
}
return false;
}
@ -138,7 +137,7 @@ namespace Greenshot.Interop.Office {
if (outlookApplication == null) {
return false;
}
if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2013) {
if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2013) {
// Check inline "panel" for Outlook 2013
using (var activeExplorer = outlookApplication.ActiveExplorer()) {
if (activeExplorer == null) {
@ -148,11 +147,11 @@ namespace Greenshot.Interop.Office {
if (currentCaption.StartsWith(inspectorCaption)) {
using (var inlineResponse = activeExplorer.ActiveInlineResponse) {
using (IItem currentItem = activeExplorer.ActiveInlineResponse) {
if (canExportToInspector(inlineResponse)) {
if (CanExportToInspector(inlineResponse)) {
try {
return ExportToInspector(activeExplorer, currentItem, tmpFile, attachmentName);
} catch (Exception exExport) {
LOG.Error("Export to " + currentCaption + " failed.", exExport);
Log.Error("Export to " + currentCaption + " failed.", exExport);
}
}
}
@ -165,17 +164,17 @@ namespace Greenshot.Interop.Office {
if (inspectors == null || inspectors.Count == 0) {
return false;
}
LOG.DebugFormat("Got {0} inspectors to check", inspectors.Count);
Log.DebugFormat("Got {0} inspectors to check", inspectors.Count);
for (int i = 1; i <= inspectors.Count; i++) {
using (IInspector inspector = outlookApplication.Inspectors[i]) {
string currentCaption = inspector.Caption;
if (currentCaption.StartsWith(inspectorCaption)) {
using (IItem currentItem = inspector.CurrentItem) {
if (canExportToInspector(currentItem)) {
if (CanExportToInspector(currentItem)) {
try {
return ExportToInspector(inspector, currentItem, tmpFile, attachmentName);
} catch (Exception exExport) {
LOG.Error("Export to " + currentCaption + " failed.", exExport);
Log.Error("Export to " + currentCaption + " failed.", exExport);
}
}
}
@ -190,21 +189,21 @@ namespace Greenshot.Interop.Office {
/// <summary>
/// Export the file to the supplied inspector
/// </summary>
/// <param name="inspector">Inspector</param>
/// <param name="inspectorOrExplorer">ICommonExplorer</param>
/// <param name="currentItem">Item</param>
/// <param name="tmpFile"></param>
/// <param name="attachmentName"></param>
/// <returns></returns>
private static bool ExportToInspector(ICommonExplorer inspectorOrExplorer, IItem currentItem, string tmpFile, string attachmentName) {
if (currentItem == null) {
LOG.Warn("No current item.");
Log.Warn("No current item.");
return false;
}
OlObjectClass itemClass = currentItem.Class;
bool isMail = OlObjectClass.olMail.Equals(itemClass);
bool isAppointment = OlObjectClass.olAppointment.Equals(itemClass);
if (!isMail && !isAppointment) {
LOG.Warn("Item is no mail or appointment.");
Log.Warn("Item is no mail or appointment.");
return false;
}
MailItem mailItem = null;
@ -213,7 +212,7 @@ namespace Greenshot.Interop.Office {
//mailItem = COMWrapper.Cast<MailItem>(currentItem);
mailItem = (MailItem)currentItem;
if (mailItem.Sent) {
LOG.WarnFormat("Item already sent, can't export to {0}", currentItem.Subject);
Log.WarnFormat("Item already sent, can't export to {0}", currentItem.Subject);
return false;
}
}
@ -230,41 +229,46 @@ namespace Greenshot.Interop.Office {
// http://msdn.microsoft.com/en-us/library/dd492012%28v=office.12%29.aspx
// Earlier versions of Outlook also supported an Inspector.HTMLEditor object property, but since Internet Explorer is no longer the rendering engine for HTML messages and posts, HTMLEditor is no longer supported.
IWordDocument wordDocument = null;
if (inspectorOrExplorer is IExplorer) {
var explorer = inspectorOrExplorer as IExplorer;
var explorer = inspectorOrExplorer as IExplorer;
if (explorer != null) {
wordDocument = explorer.ActiveInlineResponseWordEditor;
} else if (inspectorOrExplorer is IInspector) {
var inspector = inspectorOrExplorer as IInspector;
if (inspector.IsWordMail()) {
wordDocument = inspector.WordEditor;
}
else
{
var inspector1 = inspectorOrExplorer as IInspector;
if (inspector1 != null) {
var inspector = inspector1;
if (inspector.IsWordMail()) {
wordDocument = inspector.WordEditor;
}
}
}
if (wordDocument != null) {
try {
if (WordExporter.InsertIntoExistingDocument(wordDocument.Application, wordDocument, tmpFile, null, null)) {
LOG.Info("Inserted into Wordmail");
Log.Info("Inserted into Wordmail");
wordDocument.Dispose();
return true;
}
} catch (Exception exportException) {
LOG.Error("Error exporting to the word editor, trying to do it via another method", exportException);
Log.Error("Error exporting to the word editor, trying to do it via another method", exportException);
}
} else if (isAppointment) {
LOG.Info("Can't export to an appointment if no word editor is used");
Log.Info("Can't export to an appointment if no word editor is used");
return false;
} else {
LOG.Info("Trying export for outlook < 2007.");
Log.Info("Trying export for outlook < 2007.");
}
}
// Only use mailitem as it should be filled!!
LOG.InfoFormat("Item '{0}' has format: {1}", mailItem.Subject, mailItem.BodyFormat);
Log.InfoFormat("Item '{0}' has format: {1}", mailItem?.Subject, mailItem?.BodyFormat);
string contentID;
if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) {
contentID = Guid.NewGuid().ToString();
string contentId;
if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) {
contentId = Guid.NewGuid().ToString();
} else {
LOG.Info("Older Outlook (<2007) found, using filename as contentid.");
contentID = Path.GetFileName(tmpFile);
Log.Info("Older Outlook (<2007) found, using filename as contentid.");
contentId = Path.GetFileName(tmpFile);
}
// Use this to change the format, it will probably lose the current selection.
@ -274,7 +278,7 @@ namespace Greenshot.Interop.Office {
//}
bool inlinePossible = false;
if (inspectorOrExplorer is IInspector && OlBodyFormat.olFormatHTML.Equals(mailItem.BodyFormat)) {
if (inspectorOrExplorer is IInspector && OlBodyFormat.olFormatHTML.Equals(mailItem?.BodyFormat)) {
// if html we can try to inline it
// The following might cause a security popup... can't ignore it.
try {
@ -285,46 +289,46 @@ namespace Greenshot.Interop.Office {
IHTMLTxtRange range = selection.createRange();
if (range != null) {
// First paste, than attach (otherwise the range is wrong!)
range.pasteHTML("<BR/><IMG border=0 hspace=0 alt=\"" + attachmentName + "\" align=baseline src=\"cid:" + contentID + "\"><BR/>");
range.pasteHTML("<BR/><IMG border=0 hspace=0 alt=\"" + attachmentName + "\" align=baseline src=\"cid:" + contentId + "\"><BR/>");
inlinePossible = true;
} else {
LOG.DebugFormat("No range for '{0}'", inspectorOrExplorer.Caption);
Log.DebugFormat("No range for '{0}'", inspectorOrExplorer.Caption);
}
} else {
LOG.DebugFormat("No selection for '{0}'", inspectorOrExplorer.Caption);
Log.DebugFormat("No selection for '{0}'", inspectorOrExplorer.Caption);
}
} else {
LOG.DebugFormat("No HTML editor for '{0}'", inspectorOrExplorer.Caption);
Log.DebugFormat("No HTML editor for '{0}'", inspectorOrExplorer.Caption);
}
} catch (Exception e) {
// Continue with non inline image
LOG.Warn("Error pasting HTML, most likely due to an ACCESS_DENIED as the user clicked no.", e);
Log.Warn("Error pasting HTML, most likely due to an ACCESS_DENIED as the user clicked no.", e);
}
}
// Create the attachment (if inlined the attachment isn't visible as attachment!)
using (IAttachment attachment = mailItem.Attachments.Add(tmpFile, OlAttachmentType.olByValue, inlinePossible ? 0 : 1, attachmentName)) {
if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) {
if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) {
// Add the content id to the attachment, this only works for Outlook >= 2007
try {
IPropertyAccessor propertyAccessor = attachment.PropertyAccessor;
propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID);
propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentId);
} catch {
// Ignore
}
}
}
} catch (Exception ex) {
LOG.WarnFormat("Problem while trying to add attachment to Item '{0}' : {1}", inspectorOrExplorer.Caption, ex);
Log.WarnFormat("Problem while trying to add attachment to Item '{0}' : {1}", inspectorOrExplorer.Caption, ex);
return false;
}
try {
inspectorOrExplorer.Activate();
} catch (Exception ex) {
LOG.Warn("Problem activating inspector/explorer: ", ex);
Log.Warn("Problem activating inspector/explorer: ", ex);
return false;
}
LOG.Debug("Finished!");
Log.Debug("Finished!");
return true;
}
@ -363,7 +367,7 @@ namespace Greenshot.Interop.Office {
try {
bodyString = GetOutlookSignature(format);
} catch (Exception e) {
LOG.Error("Problem reading signature!", e);
Log.Error("Problem reading signature!", e);
}
switch (format) {
case EmailFormat.Text:
@ -377,20 +381,19 @@ namespace Greenshot.Interop.Office {
newMail.Body = bodyString;
}
break;
case EmailFormat.HTML:
default:
string contentID = Path.GetFileName(tmpFile);
string contentId = Path.GetFileName(tmpFile);
// Create the attachment (and dispose the COM object after using)
using (IAttachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 0, attachmentName)) {
// add content ID to the attachment
if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) {
if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) {
try {
contentID = Guid.NewGuid().ToString();
contentId = Guid.NewGuid().ToString();
IPropertyAccessor propertyAccessor = attachment.PropertyAccessor;
propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID);
propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentId);
} catch {
LOG.Info("Error working with the PropertyAccessor, using filename as contentid");
contentID = Path.GetFileName(tmpFile);
Log.Info("Error working with the PropertyAccessor, using filename as contentid");
contentId = Path.GetFileName(tmpFile);
}
}
}
@ -399,22 +402,19 @@ namespace Greenshot.Interop.Office {
string href = "";
string hrefEnd = "";
if (!string.IsNullOrEmpty(url)) {
href = string.Format("<A HREF=\"{0}\">", url);
href = $"<A HREF=\"{url}\">";
hrefEnd = "</A>";
}
string htmlImgEmbedded = string.Format("<BR/>{0}<IMG border=0 hspace=0 alt=\"{1}\" align=baseline src=\"cid:{2}\">{3}<BR/>", href, attachmentName, contentID, hrefEnd);
string fallbackBody = string.Format("<HTML><BODY>{0}</BODY></HTML>", htmlImgEmbedded);
string htmlImgEmbedded = $"<BR/>{href}<IMG border=0 hspace=0 alt=\"{attachmentName}\" align=baseline src=\"cid:{contentId}\">{hrefEnd}<BR/>";
string fallbackBody = $"<HTML><BODY>{htmlImgEmbedded}</BODY></HTML>";
if (bodyString == null) {
bodyString = fallbackBody;
} else {
int bodyIndex = bodyString.IndexOf("<body", StringComparison.CurrentCultureIgnoreCase);
if (bodyIndex >= 0) {
bodyIndex = bodyString.IndexOf(">", bodyIndex) + 1;
if (bodyIndex >= 0) {
bodyString = bodyString.Insert(bodyIndex, htmlImgEmbedded);
} else {
bodyString = fallbackBody;
}
if (bodyIndex >= 0)
{
bodyIndex = bodyString.IndexOf(">", bodyIndex, StringComparison.Ordinal) + 1;
bodyString = bodyIndex >= 0 ? bodyString.Insert(bodyIndex, htmlImgEmbedded) : fallbackBody;
} else {
bodyString = fallbackBody;
}
@ -460,7 +460,7 @@ namespace Greenshot.Interop.Office {
}
return exported;
} catch (Exception e) {
LOG.Error("Error while creating an outlook mail item: ", e);
Log.Error("Error while creating an outlook mail item: ", e);
}
return exported;
}
@ -470,46 +470,48 @@ namespace Greenshot.Interop.Office {
/// </summary>
/// <returns></returns>
private static string GetOutlookSignature(EmailFormat format) {
using (RegistryKey profilesKey = Registry.CurrentUser.OpenSubKey(PROFILES_KEY, false)) {
using (RegistryKey profilesKey = Registry.CurrentUser.OpenSubKey(ProfilesKey, false)) {
if (profilesKey == null) {
return null;
}
string defaultProfile = (string)profilesKey.GetValue(DEFAULT_PROFILE_VALUE);
LOG.DebugFormat("defaultProfile={0}", defaultProfile);
using (RegistryKey profileKey = profilesKey.OpenSubKey(defaultProfile + @"\" + ACCOUNT_KEY, false)) {
if (profilesKey == null) {
return null;
}
string[] numbers = profileKey.GetSubKeyNames();
foreach (string number in numbers) {
LOG.DebugFormat("Found subkey {0}", number);
using (RegistryKey numberKey = profileKey.OpenSubKey(number, false)) {
byte[] val = (byte[])numberKey.GetValue(NEW_SIGNATURE_VALUE);
if (val == null) {
continue;
}
string signatureName = "";
foreach (byte b in val) {
if (b != 0) {
signatureName += (char)b;
string defaultProfile = (string)profilesKey.GetValue(DefaultProfileValue);
Log.DebugFormat("defaultProfile={0}", defaultProfile);
using (RegistryKey profileKey = profilesKey.OpenSubKey(defaultProfile + @"\" + AccountKey, false)) {
if (profileKey != null)
{
string[] numbers = profileKey.GetSubKeyNames();
foreach (string number in numbers) {
Log.DebugFormat("Found subkey {0}", number);
using (RegistryKey numberKey = profileKey.OpenSubKey(number, false)) {
if (numberKey != null)
{
byte[] val = (byte[])numberKey.GetValue(NewSignatureValue);
if (val == null) {
continue;
}
string signatureName = "";
foreach (byte b in val) {
if (b != 0) {
signatureName += (char)b;
}
}
Log.DebugFormat("Found email signature: {0}", signatureName);
string extension;
switch (format) {
case EmailFormat.Text:
extension = ".txt";
break;
default:
extension = ".htm";
break;
}
string signatureFile = Path.Combine(SignaturePath, signatureName + extension);
if (File.Exists(signatureFile)) {
Log.DebugFormat("Found email signature file: {0}", signatureFile);
return File.ReadAllText(signatureFile, Encoding.Default);
}
}
}
LOG.DebugFormat("Found email signature: {0}", signatureName);
string extension;
switch (format) {
case EmailFormat.Text:
extension = ".txt";
break;
case EmailFormat.HTML:
default:
extension = ".htm";
break;
}
string signatureFile = Path.Combine(SIGNATURE_PATH, signatureName + extension);
if (File.Exists(signatureFile)) {
LOG.DebugFormat("Found email signature file: {0}", signatureFile);
return File.ReadAllText(signatureFile, Encoding.Default);
}
}
}
}
@ -522,25 +524,25 @@ namespace Greenshot.Interop.Office {
/// </summary>
/// <param name="outlookApplication"></param>
private static void InitializeVariables(IOutlookApplication outlookApplication) {
if (outlookApplication == null || outlookVersion != null) {
if (outlookApplication == null || _outlookVersion != null) {
return;
}
try {
outlookVersion = new Version(outlookApplication.Version);
LOG.InfoFormat("Using Outlook {0}", outlookVersion);
_outlookVersion = new Version(outlookApplication.Version);
Log.InfoFormat("Using Outlook {0}", _outlookVersion);
} catch (Exception exVersion) {
LOG.Error(exVersion);
LOG.Warn("Assuming outlook version 1997.");
outlookVersion = new Version((int)OfficeVersion.OFFICE_97, 0, 0, 0);
Log.Error(exVersion);
Log.Warn("Assuming outlook version 1997.");
_outlookVersion = new Version((int)OfficeVersion.OFFICE_97, 0, 0, 0);
}
// Preventing retrieval of currentUser if Outlook is older than 2007
if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) {
if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) {
try {
INameSpace mapiNamespace = outlookApplication.GetNameSpace("MAPI");
currentUser = mapiNamespace.CurrentUser.Name;
LOG.InfoFormat("Current user: {0}", currentUser);
} catch (Exception exNS) {
LOG.Error(exNS);
_currentUser = mapiNamespace.CurrentUser.Name;
Log.InfoFormat("Current user: {0}", _currentUser);
} catch (Exception exNs) {
Log.Error(exNs);
}
}
}

View file

@ -25,16 +25,16 @@ using Greenshot.IniFile;
namespace Greenshot.Interop.Office {
public class WordExporter {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(WordExporter));
private static Version wordVersion = null;
private static readonly OfficeConfiguration config = IniConfig.GetIniSection<OfficeConfiguration>();
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(WordExporter));
private static Version _wordVersion;
private static readonly OfficeConfiguration OfficeConfig = IniConfig.GetIniSection<OfficeConfiguration>();
/// <summary>
/// Check if the used version is higher than Office 2003
/// </summary>
/// <returns></returns>
private static bool isAfter2003() {
return wordVersion.Major > (int)OfficeVersion.OFFICE_2003;
private static bool IsAfter2003() {
return _wordVersion.Major > (int)OfficeVersion.OFFICE_2003;
}
/// <summary>
@ -77,11 +77,14 @@ namespace Greenshot.Interop.Office {
// Solution: Make sure the selected document is active, otherwise the insert will be made in a different document!
try {
wordDocument.Activate();
} catch {
}
catch
{
// ignored
}
using (ISelection selection = wordApplication.Selection) {
if (selection == null) {
LOG.InfoFormat("No selection to insert {0} into found.", tmpFile);
Log.InfoFormat("No selection to insert {0} into found.", tmpFile);
return false;
}
// Add Picture
@ -96,7 +99,7 @@ namespace Greenshot.Interop.Office {
hyperlinks.Add(shape, screentip, Type.Missing, screentip, Type.Missing, Type.Missing);
}
} catch (Exception e) {
LOG.WarnFormat("Couldn't add hyperlink for image: {0}", e.Message);
Log.WarnFormat("Couldn't add hyperlink for image: {0}", e.Message);
}
}
}
@ -110,19 +113,21 @@ namespace Greenshot.Interop.Office {
}
}
} catch (Exception e) {
if (e.InnerException != null) {
LOG.WarnFormat("Couldn't set zoom to 100, error: {0}", e.InnerException.Message);
} else {
LOG.WarnFormat("Couldn't set zoom to 100, error: {0}", e.Message);
}
Log.WarnFormat("Couldn't set zoom to 100, error: {0}", e.InnerException?.Message ?? e.Message);
}
try {
wordApplication.Activate();
} catch {
}
catch
{
// ignored
}
try {
wordDocument.Activate();
} catch {
}
catch
{
// ignored
}
return true;
}
@ -138,7 +143,7 @@ namespace Greenshot.Interop.Office {
using (IInlineShapes shapes = selection.InlineShapes) {
IInlineShape shape = shapes.AddPicture(tmpFile, false, true, Type.Missing);
// Lock aspect ratio
if (config.WordLockAspectRatio) {
if (OfficeConfig.WordLockAspectRatio) {
shape.LockAspectRatio = MsoTriState.msoTrue;
}
selection.InsertAfter("\r\n");
@ -174,18 +179,24 @@ namespace Greenshot.Interop.Office {
hyperlinks.Add(shape, screentip, Type.Missing, screentip, Type.Missing, Type.Missing);
}
} catch (Exception e) {
LOG.WarnFormat("Couldn't add hyperlink for image: {0}", e.Message);
Log.WarnFormat("Couldn't add hyperlink for image: {0}", e.Message);
}
}
}
}
try {
wordDocument.Activate();
} catch {
}
catch
{
// ignored
}
try {
wordDocument.ActiveWindow.Activate();
} catch {
}
catch
{
// ignored
}
}
}
@ -209,7 +220,7 @@ namespace Greenshot.Interop.Office {
if (document.ReadOnly) {
continue;
}
if (isAfter2003()) {
if (IsAfter2003()) {
if (document.Final) {
continue;
}
@ -222,7 +233,7 @@ namespace Greenshot.Interop.Office {
}
}
} catch (Exception ex) {
LOG.Warn("Problem retrieving word destinations, ignoring: ", ex);
Log.Warn("Problem retrieving word destinations, ignoring: ", ex);
}
openDocuments.Sort();
return openDocuments;
@ -253,16 +264,16 @@ namespace Greenshot.Interop.Office {
/// </summary>
/// <param name="wordApplication"></param>
private static void InitializeVariables(IWordApplication wordApplication) {
if (wordApplication == null || wordVersion != null) {
if (wordApplication == null || _wordVersion != null) {
return;
}
try {
wordVersion = new Version(wordApplication.Version);
LOG.InfoFormat("Using Word {0}", wordVersion);
_wordVersion = new Version(wordApplication.Version);
Log.InfoFormat("Using Word {0}", _wordVersion);
} catch (Exception exVersion) {
LOG.Error(exVersion);
LOG.Warn("Assuming Word version 1997.");
wordVersion = new Version((int)OfficeVersion.OFFICE_97, 0, 0, 0);
Log.Error(exVersion);
Log.Warn("Assuming Word version 1997.");
_wordVersion = new Version((int)OfficeVersion.OFFICE_97, 0, 0, 0);
}
}
}

View file

@ -253,8 +253,8 @@ namespace Greenshot.Interop.Office {
// See: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.propertyaccessor_members.aspx
public interface IPropertyAccessor : ICommon {
void SetProperty(string SchemaName, Object Value);
Object GetProperty(string SchemaName);
void SetProperty(string SchemaName, object Value);
object GetProperty(string SchemaName);
}
// Schema definitions for the MAPI properties
@ -363,7 +363,7 @@ namespace Greenshot.Interop.Office {
// See: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._application.inspectors.aspx
public interface IInspectors : ICommon, ICollection, IEnumerable {
// Use index + 1!!
IInspector this[Object Index] {
IInspector this[object Index] {
get;
}
}
@ -374,7 +374,7 @@ namespace Greenshot.Interop.Office {
/// </summary>
public interface IExplorers : ICommon, ICollection, IEnumerable {
// Use index + 1!!
IExplorer this[Object Index] {
IExplorer this[object Index] {
get;
}
}