Exemplo n.º 1
0
 public void Process(WatchedEvent @event)
 {
     if (LOG.IsDebugEnabled)
     {
         LOG.DebugFormat("Watcher fired on path: {0} state: {1} type {2}", @event.Path, @event.State, @event.Type);
     }
     try
     {
         writeLock.Lock();
     }
     catch (Exception e)
     {
         LOG.WarnFormat("Failed to acquire lock: {0} {1}", e, e.StackTrace);
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// Retrieve a list of all formats currently in the IDataObject
        /// </summary>
        /// <returns>List<string> with the current formats</returns>
        public static List <string> GetFormats(IDataObject dataObj)
        {
            string[] formats = null;

            if (dataObj != null)
            {
                formats = dataObj.GetFormats();
            }
            if (formats != null)
            {
                LOG.DebugFormat("Got clipboard formats: {0}", String.Join(",", formats));
                return(new List <string>(formats));
            }
            return(new List <string>());
        }
Exemplo n.º 3
0
 /// <summary>
 /// Add a new path to the paths that will be scanned for language files!
 /// </summary>
 /// <param name="path"></param>
 /// <returns>true if the path exists and is added</returns>
 public static bool AddLanguageFilePath(string path)
 {
     if (!languagePaths.Contains(path))
     {
         LOG.DebugFormat("New language path {0}", path);
         if (AddPath(path))
         {
             ScanFiles();
             Reload();
         }
         else
         {
             return(false);
         }
     }
     return(true);
 }
Exemplo n.º 4
0
        public void PrintRemoteTree()
        {
            LOG.Debug("Listing remote tree...");

            try
            {
                Tree <RemoteFileInfo> .PrintTree(m_remoteTree, 0);
            }
            catch (Exception e)
            {
                LOG.ErrorFormat("Error: {0}", e);
            }

            int numberOfFiles = Tree <RemoteFileInfo> .GetNumberOfChildren(m_remoteTree, 0);

            LOG.DebugFormat("Refreshed {0} remote files", numberOfFiles);
        }
Exemplo n.º 5
0
        public void PrintIgnoreTree()
        {
            LOG.Debug("Listing ignored files...");

            try
            {
                Tree <RemoteFileInfo> .PrintTree(m_ignoreTree, 0);
            }
            catch (Exception e)
            {
                LOG.ErrorFormat("Error: {0}", e);
            }

            int numberOfFiles = Tree <RemoteFileInfo> .GetNumberOfChildren(m_ignoreTree, 0);

            LOG.DebugFormat("Loaded {0} ignored files", numberOfFiles);
        }
Exemplo n.º 6
0
 /// <summary>
 /// Internal method to add a path to the paths that will be scanned for language files!
 /// </summary>
 /// <param name="path"></param>
 /// <returns>true if the path exists and is added</returns>
 private static bool AddPath(string path)
 {
     if (!languagePaths.Contains(path))
     {
         if (Directory.Exists(path))
         {
             LOG.DebugFormat("Adding language path {0}", path);
             languagePaths.Add(path);
             return(true);
         }
         else
         {
             LOG.InfoFormat("Not adding non existing language path {0}", path);
         }
     }
     return(false);
 }
Exemplo n.º 7
0
        public virtual void AddField(Field field)
        {
            if (fieldsByType != null && fieldsByType.ContainsKey(field.FieldType))
            {
                if (LOG.IsDebugEnabled)
                {
                    LOG.DebugFormat("A field with of type '{0}' already exists in this {1}, will overwrite.", field.FieldType, GetType());
                }
            }

            fields.Add(field);
            fieldsByType[field.FieldType] = field;
            field.PropertyChanged        += delegate { if (fieldChanged != null)
                                                       {
                                                           fieldChanged(this, new FieldChangedEventArgs(field));
                                                       }
            };
        }
Exemplo n.º 8
0
        private void GetFiles(string _remotePath, string _localPath, bool _remove = false, TransferOptions _transformOptions = null)
        {
            LOG.DebugFormat("Getting files from {0} >> {1}", _remotePath, _localPath);

            try
            {
                // Download files and throw on any error
                m_session.GetFiles(_remotePath, _localPath, _remove, _transformOptions).Check();
            }
            finally
            {
                // Terminate line after the last file (if any)
                if (m_lastFileName != null)
                {
                    LOG.Info("\nGetFiles done!");
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Make sure the content is also transformed.
        /// </summary>
        /// <param name="matrix"></param>
        public override void Transform(Matrix matrix)
        {
            int rotateAngle = CalculateAngle(matrix);

            // we currently assume only one transformation has been made.
            if (rotateAngle != 0)
            {
                LOG.DebugFormat("Rotating element with {0} degrees.", rotateAngle);
                DisposeShadow();
                using (var tmpMatrix = new Matrix())
                {
                    using (Image tmpImage = image)
                    {
                        image = ImageHelper.ApplyEffect(image, new RotateEffect(rotateAngle), tmpMatrix);
                    }
                }
            }
            base.Transform(matrix);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Returns the "com" type of the wrapperproxy, making it possible to perform reflection on it.
        /// </summary>
        /// <param name="wrapperProxy">wrapperProxy to get the type from</param>
        /// <returns>Type</returns>
        public static Type GetUnderlyingTypeForWrapper(object wrapperProxy)
        {
            Type       returnType = null;
            COMWrapper wrapper    = RemotingServices.GetRealProxy(wrapperProxy) as COMWrapper;

            if (wrapper != null)
            {
                IDispatch dispatch = wrapper._COMObject as IDispatch;
                if (dispatch != null)
                {
                    int result = dispatch.GetTypeInfo(0, 0, out returnType);
                    if (result != 0)
                    {
                        LOG.DebugFormat("GetTypeInfo : 0x{0} ({1})", result.ToString("X"), result);
                    }
                }
            }
            return(returnType);
        }
        private void TabbedAnythingForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            LOG.DebugFormat("FormClosing - Reason: {0}", e.CloseReason);

            if (e.CloseReason == CloseReason.UserClosing)
            {
                if (!this.ConfirmClose())
                {
                    LOG.Debug("FormClosing - Cancelled on confirm close");
                    e.Cancel = true;
                    return;
                }
            }

            ProcessTabs.TabRemoved -= ProcessTabs_TabRemoved;
            ProcessTabs.TabClosed  -= ProcessTabs_TabClosed;

            RemoveAllProcesses();
            SaveWindowState();
        }
Exemplo n.º 12
0
 /// <summary>
 /// Get LastModified for a URI
 /// </summary>
 /// <param name="uri">Uri</param>
 /// <returns>DateTime</returns>
 public static DateTime GetLastModified(Uri uri)
 {
     try
     {
         HttpWebRequest webRequest = CreateWebRequest(uri);
         webRequest.Method = HTTPMethod.HEAD.ToString();
         using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
         {
             LOG.DebugFormat("RSS feed was updated at {0}", webResponse.LastModified);
             return(webResponse.LastModified);
         }
     }
     catch (Exception wE)
     {
         LOG.WarnFormat("Problem requesting HTTP - HEAD on uri {0}", uri);
         LOG.Warn(wE.Message);
         // Pretend it is old
         return(DateTime.MinValue);
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Get an Image from the IDataObject, don't check for FileDrop
        /// </summary>
        /// <param name="dataObject"></param>
        /// <returns>Image or null</returns>
        private static Image GetImage(IDataObject dataObject)
        {
            Image returnImage = null;

            if (dataObject != null)
            {
                IList <string> formats = GetFormats(dataObject);
                string[]       retrieveFormats;

                // Found a weird bug, where PNG's from Outlook 2010 are clipped
                // So I build some special logik to get the best format:
                if (formats != null && formats.Contains(FORMAT_PNG_OFFICEART) && formats.Contains(DataFormats.Dib))
                {
                    // Outlook ??
                    LOG.Info("Most likely the current clipboard contents come from Outlook, as this has a problem with PNG and others we place the DIB format to the front...");
                    retrieveFormats = new string[] { DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, FORMAT_GIF };
                }
                else
                {
                    retrieveFormats = new string[] { FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_17, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_GIF };
                }
                foreach (string currentFormat in retrieveFormats)
                {
                    if (formats.Contains(currentFormat))
                    {
                        LOG.InfoFormat("Found {0}, trying to retrieve.", currentFormat);
                        returnImage = GetImageForFormat(currentFormat, dataObject);
                    }
                    else
                    {
                        LOG.DebugFormat("Couldn't find format {0}.", currentFormat);
                    }
                    if (returnImage != null)
                    {
                        ImageHelper.Orientate(returnImage);
                        return(returnImage);
                    }
                }
            }
            return(null);
        }
Exemplo n.º 14
0
        public void UpdateRemoteFileList()
        {
            Stopwatch.Restart();

            m_remoteTree.Data      = new RemoteFileInfo();
            m_remoteTree.Data.Name = RemoteRoot;

            Update(RemoteRoot, m_remoteTree);

            if (PrintTrees)
            {
                PrintRemoteChildren();
            }
            else
            {
                int numberOfFiles = Tree <RemoteFileInfo> .GetNumberOfChildren(m_remoteTree, 0);

                numberOfFiles = (numberOfFiles == 1) ? 0 : numberOfFiles;

                LOG.DebugFormat("Refreshed {0} remote files in [{1}ms]", numberOfFiles, Stopwatch.ElapsedMilliseconds);
            }
        }
Exemplo n.º 15
0
        public void PrintIgnoreChildren()
        {
            LOG.Debug("Listing ignore files...");

            try
            {
                if (m_ignoreTree.Children.Count > 0)
                {
                    Tree <RemoteFileInfo> .PrintTreeChildren(m_ignoreTree, RemoteRoot);
                }
            }
            catch (Exception e)
            {
                LOG.ErrorFormat("Error: {0}", e);
            }

            int numberOfFiles = Tree <RemoteFileInfo> .GetNumberOfChildren(m_ignoreTree, 0);

            numberOfFiles = (numberOfFiles == 1) ? 0 : numberOfFiles;

            LOG.DebugFormat("Loaded {0} ignore files", numberOfFiles);
        }
Exemplo n.º 16
0
        public void PrintRemoteChildren()
        {
            LOG.Debug("Listing remote files...");

            try
            {
                if (m_remoteTree.Children.Count > 0)
                {
                    Tree <RemoteFileInfo> .PrintTreeChildren(m_remoteTree, "");
                }
            }
            catch (Exception e)
            {
                LOG.ErrorFormat("Error: {0}", e);
            }

            int numberOfFiles = Tree <RemoteFileInfo> .GetNumberOfChildren(m_remoteTree, 0);

            numberOfFiles = (numberOfFiles == 1) ? 0 : numberOfFiles;

            LOG.DebugFormat("Refreshed {0} remote files", numberOfFiles);
        }
Exemplo n.º 17
0
        public SafeCurrentInputDesktopHandle() : base(true)
        {
            IntPtr hDesktop = User32.OpenInputDesktop(0, true, DesktopAccessRight.GENERIC_ALL);

            if (hDesktop != IntPtr.Zero)
            {
                SetHandle(hDesktop);
                if (User32.SetThreadDesktop(hDesktop))
                {
                    LOG.DebugFormat("Switched to desktop {0}", hDesktop);
                }
                else
                {
                    LOG.WarnFormat("Couldn't switch to desktop {0}", hDesktop);
                    LOG.Error(User32.CreateWin32Exception("SetThreadDesktop"));
                }
            }
            else
            {
                LOG.Warn("Couldn't get current desktop.");
                LOG.Error(User32.CreateWin32Exception("OpenInputDesktop"));
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Release the COM reference
        /// </summary>
        /// <param name="disposing">
        /// <see langword="true"/> if this was called from the
        /// <see cref="IDisposable"/> interface.
        /// </param>
        private void Dispose(bool disposing)
        {
            if (null != _COMObject)
            {
                LOG.DebugFormat("Disposing {0}", _InterceptType.ToString());
                if (Marshal.IsComObject(_COMObject))
                {
                    try
                    {
                        while (Marshal.ReleaseComObject(_COMObject) > 0)
                        {
                            ;
                        }
                    }
                    catch (Exception ex)
                    {
                        LOG.WarnFormat("Problem releasing {0}", _COMType);
                        LOG.Warn("Error: ", ex);
                    }
                }

                _COMObject = null;
            }
        }
        private void ProcessTabs_TabAdded(object sender, TabAddedEventArgs e)
        {
            LOG.DebugFormat("TabAdded - Tab: {0}", e.Tab);

            RegisterExistingTab(e.Tab);
        }
Exemplo n.º 20
0
        /// <summary>
        /// This method will set the ini value to the supplied value or use the default if non supplied
        /// </summary>
        /// <param name="propertyValue"></param>
        public void UseValueOrDefault(string propertyValue)
        {
            Type   valueType              = ValueType;
            string propertyName           = attributes.Name;
            string defaultValue           = attributes.DefaultValue;
            bool   defaultUsed            = false;
            object defaultValueFromConfig = containingIniSection.GetDefault(propertyName);

            if (string.IsNullOrEmpty(propertyValue))
            {
                if (defaultValue != null && defaultValue.Trim().Length != 0)
                {
                    propertyValue = defaultValue;
                    defaultUsed   = true;
                }
                else if (defaultValueFromConfig != null)
                {
                    LOG.DebugFormat("Default for Property {0} implemented!", propertyName);
                }
                else
                {
                    if (attributes.ExcludeIfNull)
                    {
                        Value = null;
                        return;
                    }
                    LOG.DebugFormat("Property {0} has no value or default value!", propertyName);
                }
            }
            // Now set the value
            if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(Dictionary <,>))
            {
                // Logic for Dictionary<,>
                Type type1 = valueType.GetGenericArguments()[0];
                Type type2 = valueType.GetGenericArguments()[1];
                //LOG.Info(String.Format("Found Dictionary<{0},{1}>", type1.Name, type2.Name));
                object     dictionary    = Activator.CreateInstance(valueType);
                MethodInfo addMethodInfo = valueType.GetMethod("Add");
                bool       addedElements = false;
                Dictionary <string, string> properties = IniConfig.PropertiesForSection(containingIniSection);
                foreach (string key in properties.Keys)
                {
                    if (key != null && key.StartsWith(propertyName + "."))
                    {
                        // What "key" do we need to store it under?
                        string subPropertyName = key.Substring(propertyName.Length + 1);
                        string stringValue     = properties[key];
                        object newValue1       = null;
                        object newValue2       = null;
                        try
                        {
                            newValue1 = ConvertStringToValueType(type1, subPropertyName, attributes.Separator);
                        }
                        catch (Exception ex)
                        {
                            LOG.Warn(ex);
                            //LOG.Error("Problem converting " + subPropertyName + " to type " + type1.FullName, e);
                        }
                        try
                        {
                            newValue2 = ConvertStringToValueType(type2, stringValue, attributes.Separator);
                        }
                        catch (Exception ex)
                        {
                            LOG.Warn(ex);
                            //LOG.Error("Problem converting " + stringValue + " to type " + type2.FullName, e);
                        }
                        addMethodInfo.Invoke(dictionary, new[] { newValue1, newValue2 });
                        addedElements = true;
                    }
                }
                // No need to return something that isn't filled!
                if (addedElements)
                {
                    Value = dictionary;
                    return;
                }
                else if (defaultValueFromConfig != null)
                {
                    Value = defaultValueFromConfig;
                    return;
                }
            }
            else if (!string.IsNullOrEmpty(propertyValue))
            {
                if (valueType.IsGenericType && valueType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                {
                    // We are dealing with a generic type that is nullable
                    valueType = Nullable.GetUnderlyingType(valueType);
                }
                object newValue = null;
                try
                {
                    newValue = ConvertStringToValueType(valueType, propertyValue, attributes.Separator);
                }
                catch (Exception ex1)
                {
                    newValue = null;
                    if (!defaultUsed)
                    {
                        try
                        {
                            LOG.WarnFormat("Problem '{0}' while converting {1} to type {2} trying fallback...", ex1.Message, propertyValue, valueType.FullName);
                            newValue = ConvertStringToValueType(valueType, defaultValue, attributes.Separator);
                            ContainingIniSection.IsDirty = true;
                            LOG.InfoFormat("Used default value {0} for property {1}", defaultValue, propertyName);
                        }
                        catch (Exception ex2)
                        {
                            LOG.Warn("Problem converting fallback value " + defaultValue + " to type " + valueType.FullName, ex2);
                        }
                    }
                    else
                    {
                        LOG.Warn("Problem converting " + propertyValue + " to type " + valueType.FullName, ex1);
                    }
                }
                Value = newValue;
                return;
            }

            // If nothing is set, we can use the default value from the config (if we habe one)
            if (defaultValueFromConfig != null)
            {
                Value = defaultValueFromConfig;
                return;
            }
            if (ValueType != typeof(string))
            {
                try
                {
                    Value = Activator.CreateInstance(ValueType);
                }
                catch (Exception)
                {
                    LOG.WarnFormat("Couldn't create instance of {0} for {1}, using default value.", ValueType.FullName, attributes.Name);
                    Value = default(ValueType);
                }
            }
            else
            {
                Value = default(ValueType);
            }
        }
Exemplo n.º 21
0
 public void Process(WatchedEvent @event)
 {
     LOG.DebugFormat("Watcher fired on path: {0} state: {1} type {2}", @event.Path, @event.State, @event.Type);
     reset.Set();
 }
Exemplo n.º 22
0
        /// <summary>
        /// Saves image to stream with specified quality
        /// To prevent problems with GDI version of before Windows 7:
        /// the stream is checked if it's seekable and if needed a MemoryStream as "cache" is used.
        /// </summary>
        /// <param name="imageToSave">image to save</param>
        /// <param name="surface">surface for the elements, needed if the greenshot format is used</param>
        /// <param name="stream">Stream to save to</param>
        /// <param name="outputSettings">SurfaceOutputSettings</param>
        public static void SaveToStream(Image imageToSave, ISurface surface, Stream stream, SurfaceOutputSettings outputSettings)
        {
            ImageFormat  imageFormat     = null;
            bool         useMemoryStream = false;
            MemoryStream memoryStream    = null;

            if (outputSettings.Format == OutputFormat.greenshot && surface == null)
            {
                throw new ArgumentException("Surface needs to be se when using OutputFormat.Greenshot");
            }

            try
            {
                switch (outputSettings.Format)
                {
                case OutputFormat.bmp:
                    imageFormat = ImageFormat.Bmp;
                    break;

                case OutputFormat.gif:
                    imageFormat = ImageFormat.Gif;
                    break;

                case OutputFormat.jpg:
                    imageFormat = ImageFormat.Jpeg;
                    break;

                case OutputFormat.tiff:
                    imageFormat = ImageFormat.Tiff;
                    break;

                case OutputFormat.greenshot:
                case OutputFormat.png:
                default:
                    // Problem with non-seekable streams most likely doesn't happen with Windows 7 (OS Version 6.1 and later)
                    // http://stackoverflow.com/questions/8349260/generic-gdi-error-on-one-machine-but-not-the-other
                    if (!stream.CanSeek)
                    {
                        int majorVersion = Environment.OSVersion.Version.Major;
                        int minorVersion = Environment.OSVersion.Version.Minor;
                        if (majorVersion < 6 || (majorVersion == 6 && minorVersion == 0))
                        {
                            useMemoryStream = true;
                            LOG.Warn("Using memorystream prevent an issue with saving to a non seekable stream.");
                        }
                    }
                    imageFormat = ImageFormat.Png;
                    break;
                }
                LOG.DebugFormat("Saving image to stream with Format {0} and PixelFormat {1}", imageFormat, imageToSave.PixelFormat);

                // Check if we want to use a memory stream, to prevent a issue which happens with Windows before "7".
                // The save is made to the targetStream, this is directed to either the MemoryStream or the original
                Stream targetStream = stream;
                if (useMemoryStream)
                {
                    memoryStream = new MemoryStream();
                    targetStream = memoryStream;
                }

                if (imageFormat == ImageFormat.Jpeg)
                {
                    bool foundEncoder = false;
                    foreach (ImageCodecInfo imageCodec in ImageCodecInfo.GetImageEncoders())
                    {
                        if (imageCodec.FormatID == imageFormat.Guid)
                        {
                            EncoderParameters parameters = new EncoderParameters(1);
                            parameters.Param[0] = new EncoderParameter(Encoder.Quality, outputSettings.JPGQuality);
                            // Removing transparency if it's not supported in the output
                            if (Image.IsAlphaPixelFormat(imageToSave.PixelFormat))
                            {
                                Image nonAlphaImage = ImageHelper.Clone(imageToSave, PixelFormat.Format24bppRgb);
                                AddTag(nonAlphaImage);
                                nonAlphaImage.Save(targetStream, imageCodec, parameters);
                                nonAlphaImage.Dispose();
                                nonAlphaImage = null;
                            }
                            else
                            {
                                AddTag(imageToSave);
                                imageToSave.Save(targetStream, imageCodec, parameters);
                            }
                            foundEncoder = true;
                            break;
                        }
                    }
                    if (!foundEncoder)
                    {
                        throw new ApplicationException("No JPG encoder found, this should not happen.");
                    }
                }
                else
                {
                    // Removing transparency if it's not supported in the output
                    if (imageFormat != ImageFormat.Png && Image.IsAlphaPixelFormat(imageToSave.PixelFormat))
                    {
                        Image nonAlphaImage = ImageHelper.Clone(imageToSave, PixelFormat.Format24bppRgb);
                        AddTag(nonAlphaImage);
                        nonAlphaImage.Save(targetStream, imageFormat);
                        nonAlphaImage.Dispose();
                        nonAlphaImage = null;
                    }
                    else
                    {
                        AddTag(imageToSave);
                        imageToSave.Save(targetStream, imageFormat);
                    }
                }

                // If we used a memory stream, we need to stream the memory stream to the original stream.
                if (useMemoryStream)
                {
                    memoryStream.WriteTo(stream);
                }

                // Output the surface elements, size and marker to the stream
                if (outputSettings.Format == OutputFormat.greenshot)
                {
                    using (MemoryStream tmpStream = new MemoryStream())
                    {
                        long bytesWritten = surface.SaveElementsToStream(tmpStream);
                        using (BinaryWriter writer = new BinaryWriter(tmpStream))
                        {
                            writer.Write(bytesWritten);
                            Version v      = Assembly.GetExecutingAssembly().GetName().Version;
                            byte[]  marker = Encoding.ASCII.GetBytes(String.Format("Greenshot{0:00}.{1:00}", v.Major, v.Minor));
                            writer.Write(marker);
                            tmpStream.WriteTo(stream);
                        }
                    }
                }
            }
            finally
            {
                if (memoryStream != null)
                {
                    memoryStream.Dispose();
                }
            }
        }
Exemplo n.º 23
0
 public void TakeLeadership()
 {
     Leader = b;
     LOG.DebugFormat("Leader: {0:x}", b);
 }
Exemplo n.º 24
0
        /// <summary>
        /// Gets a COM object and returns the transparent proxy which intercepts all calls to the object
        /// </summary>
        /// <param name="type">Interface which defines the method and properties to intercept</param>
        /// <returns>Transparent proxy to the real proxy for the object</returns>
        /// <remarks>The <paramref name="type"/> must be an interface decorated with the <see cref="ComProgIdAttribute"/>attribute.</remarks>
        public static T GetInstance <T>()
        {
            Type type = typeof(T);

            if (null == type)
            {
                throw new ArgumentNullException("type");
            }
            if (!type.IsInterface)
            {
                throw new ArgumentException("The specified type must be an interface.", "type");
            }

            ComProgIdAttribute progIDAttribute = ComProgIdAttribute.GetAttribute(type);

            if (null == progIDAttribute || null == progIDAttribute.Value || 0 == progIDAttribute.Value.Length)
            {
                throw new ArgumentException("The specified type must define a ComProgId attribute.", "type");
            }
            string progId = progIDAttribute.Value;

            object comObject = null;

            // Convert from clsid to Prog ID, if needed
            if (progId.StartsWith("clsid:"))
            {
                Guid guid   = new Guid(progId.Substring(6));
                int  result = ProgIDFromCLSID(ref guid, out progId);
                if (result != 0)
                {
                    // Restore progId, as it's overwritten
                    progId = progIDAttribute.Value;

                    try
                    {
                        GetActiveObject(ref guid, IntPtr.Zero, out comObject);
                    }
                    catch (Exception)
                    {
                        LOG.WarnFormat("Error {0} getting instance for class id {1}", result, progIDAttribute.Value);
                    }
                    if (comObject == null)
                    {
                        LOG.WarnFormat("Error {0} getting progId {1}", result, progIDAttribute.Value);
                    }
                }
                else
                {
                    LOG.InfoFormat("Mapped {0} to progId {1}", progIDAttribute.Value, progId);
                }
            }

            if (comObject == null)
            {
                try
                {
                    comObject = Marshal.GetActiveObject(progId);
                }
                catch (COMException comE)
                {
                    if (comE.ErrorCode == MK_E_UNAVAILABLE)
                    {
                        LOG.DebugFormat("No current instance of {0} object available.", progId);
                    }
                    else if (comE.ErrorCode == CO_E_CLASSSTRING)
                    {
                        LOG.WarnFormat("Unknown progId {0}", progId);
                    }
                    else
                    {
                        LOG.Warn("Error getting active object for " + progIDAttribute.Value, comE);
                    }
                }
                catch (Exception e)
                {
                    LOG.Warn("Error getting active object for " + progIDAttribute.Value, e);
                }
            }

            if (comObject != null)
            {
                if (comObject is IDispatch)
                {
                    COMWrapper wrapper = new COMWrapper(comObject, type, progIDAttribute.Value);
                    return((T)wrapper.GetTransparentProxy());
                }
                else
                {
                    return((T)comObject);
                }
            }
            return(default(T));
        }
Exemplo n.º 25
0
        public void AddAllRemoteFilesToIgnoreList()
        {
            LOG.DebugFormat("Adding all remote files from {0} to ignore list", RemoteRoot);

            m_ignoreTree = Tree <RemoteFileInfo> .Clone(m_remoteTree);
        }
Exemplo n.º 26
0
 /// <summary>
 /// Called if the cancel button is clicked, will use Thread.Abort()
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void CancelButtonClick(object sender, EventArgs e)
 {
     LOG.DebugFormat("Cancel clicked on {0}", title);
     cancelButton.Enabled = false;
     waitFor.Abort();
 }
Exemplo n.º 27
0
        public bool RunForLeader()
        {
            long   sessionId = Zookeeper.SessionId;
            string prefix    = "election-" + sessionId + "-";
            var    names     = Zookeeper.GetChildren(path, false);

            // See whether we have already run for election in this process
            foreach (string name in names)
            {
                if (name.StartsWith(prefix))
                {
                    id = name;
                    if (LOG.IsDebugEnabled)
                    {
                        LOG.DebugFormat("Found id created last time: {0}", id);
                    }
                }
            }

            if (id == null)
            {
                id = Zookeeper.Create(path.Combine(prefix), data, Acl, CreateMode.EphemeralSequential);

                if (LOG.IsDebugEnabled)
                {
                    LOG.DebugFormat("Created id: {0}", id);
                }
            }

            idName = new ZNodeName(id);

            names = Zookeeper.GetChildren(path, false);
            var sortedNames = new SortedSet <ZNodeName>();

            foreach (var name in names)
            {
                sortedNames.Add(new ZNodeName(name));
            }

            var priors = sortedNames.HeadSet(idName);

            if (priors.Count == 0)
            {
                throw new InvalidOperationException("Count of priors is 0, but should at least include this node.");
            }

            if (priors.Count == 1)
            {
                IsOwner = true;
                watcher.TakeLeadership();
                return(true);
            }
            // only watch the node directly before us
            ZNodeName penultimate = null, last = null;

            foreach (var name in sortedNames)
            {
                penultimate = last;
                last        = name;
            }
            if (penultimate == null)
            {
                throw new InvalidOperationException("Penultimate value in priors is null, but count shoudl have been at least 2.");
            }
            var penultimatePath = path.Combine(penultimate.Name);

            if (Zookeeper.Exists(penultimatePath, new LeaderWatcher(Zookeeper, this, penultimatePath, watcher, path, id)) == null)
            {
                IsOwner = true;
                watcher.TakeLeadership();
                return(true);
            }
            return(false);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Intercept method calls
        /// </summary>
        /// <param name="myMessage">
        /// Contains information about the method being called
        /// </param>
        /// <returns>
        /// A <see cref="ReturnMessage"/>.
        /// </returns>
        public override IMessage Invoke(IMessage myMessage)
        {
            IMethodCallMessage callMessage = myMessage as IMethodCallMessage;

            if (null == callMessage)
            {
                LOG.DebugFormat("Message type not implemented: {0}", myMessage.GetType().ToString());
                return(null);
            }

            MethodInfo method = callMessage.MethodBase as MethodInfo;

            if (null == method)
            {
                LOG.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase.ToString());
                return(null);
            }

            object returnValue = null;

            object[] outArgs      = null;
            int      outArgsCount = 0;

            string       methodName = method.Name;
            Type         returnType = method.ReturnType;
            BindingFlags flags      = BindingFlags.InvokeMethod;
            int          argCount   = callMessage.ArgCount;

            object invokeObject;
            Type   invokeType;
            Type   byValType;

            object[] args;
            object   arg;

            COMWrapper[] originalArgs;
            COMWrapper   wrapper;

            ParameterModifier[] argModifiers = null;
            ParameterInfo[]     parameters   = null;
            ParameterInfo       parameter;

            if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType)
            {
                Dispose();
            }
            else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType)
            {
                returnValue = ToString();
            }
            else if ("GetType" == methodName && 0 == argCount && typeof(Type) == returnType)
            {
                returnValue = _InterceptType;
            }
            else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType)
            {
                returnValue = GetHashCode();
            }
            else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType)
            {
                returnValue = Equals(callMessage.Args[0]);
            }
            else if (1 == argCount && typeof(void) == returnType && (methodName.StartsWith("add_") || methodName.StartsWith("remove_")))
            {
                bool removeHandler = methodName.StartsWith("remove_");
                methodName = methodName.Substring(removeHandler ? 7 : 4);

                Delegate handler = callMessage.InArgs[0] as Delegate;
                if (null == handler)
                {
                    return(new ReturnMessage(new ArgumentNullException("handler"), callMessage));
                }
            }
            else
            {
                invokeObject = _COMObject;
                invokeType   = _COMType;

                if (methodName.StartsWith("get_"))
                {
                    // Property Get
                    methodName = methodName.Substring(4);
                    flags      = BindingFlags.GetProperty;
                    args       = callMessage.InArgs;
                }
                else if (methodName.StartsWith("set_"))
                {
                    // Property Set
                    methodName = methodName.Substring(4);
                    flags      = BindingFlags.SetProperty;
                    args       = callMessage.InArgs;
                }
                else
                {
                    args = callMessage.Args;
                    if (null != args && 0 != args.Length)
                    {
                        // Modifiers for ref / out parameters
                        argModifiers    = new ParameterModifier[1];
                        argModifiers[0] = new ParameterModifier(args.Length);

                        parameters = method.GetParameters();
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            parameter = parameters[i];
                            if (parameter.IsOut || parameter.ParameterType.IsByRef)
                            {
                                argModifiers[0][i] = true;
                                outArgsCount++;
                            }
                        }

                        if (0 == outArgsCount)
                        {
                            argModifiers = null;
                        }
                    }
                }

                // Un-wrap wrapped COM objects before passing to the method
                if (null == args || 0 == args.Length)
                {
                    originalArgs = null;
                }
                else
                {
                    originalArgs = new COMWrapper[args.Length];
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (null != args[i] && RemotingServices.IsTransparentProxy(args[i]))
                        {
                            wrapper = RemotingServices.GetRealProxy(args[i]) as COMWrapper;
                            if (null != wrapper)
                            {
                                originalArgs[i] = wrapper;
                                args[i]         = wrapper._COMObject;
                            }
                        }
                        else if (0 != outArgsCount && argModifiers[0][i])
                        {
                            byValType = GetByValType(parameters[i].ParameterType);
                            if (byValType.IsInterface)
                            {
                                // If we're passing a COM object by reference, and
                                // the parameter is null, we need to pass a
                                // DispatchWrapper to avoid a type mismatch exception.
                                if (null == args[i])
                                {
                                    args[i] = new DispatchWrapper(null);
                                }
                            }
                            else if (typeof(Decimal) == byValType)
                            {
                                // If we're passing a decimal value by reference,
                                // we need to pass a CurrencyWrapper to avoid a
                                // type mismatch exception.
                                // http://support.microsoft.com/?kbid=837378
                                args[i] = new CurrencyWrapper(args[i]);
                            }
                        }
                    }
                }

                do
                {
                    try
                    {
                        returnValue = invokeType.InvokeMember(methodName, flags, null, invokeObject, args, argModifiers, null, null);
                        break;
                    }
                    catch (Exception ex)
                    {
                        // Test for rejected
                        COMException comEx = ex as COMException;
                        if (comEx == null)
                        {
                            comEx = ex.InnerException as COMException;
                        }
                        if (comEx != null && (comEx.ErrorCode == RPC_E_CALL_REJECTED || comEx.ErrorCode == RPC_E_FAIL))
                        {
                            string destinationName = _TargetName;
                            // Try to find a "catchy" name for the rejecting application
                            if (destinationName != null && destinationName.Contains("."))
                            {
                                destinationName = destinationName.Substring(0, destinationName.IndexOf("."));
                            }
                            if (destinationName == null)
                            {
                                destinationName = _InterceptType.FullName;
                            }
                            DialogResult result = MessageBox.Show(Language.GetFormattedString("com_rejected", destinationName), Language.GetString("com_rejected_title"), MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
                            if (result == DialogResult.OK)
                            {
                                continue;
                            }
                        }
                        // Not rejected OR pressed cancel
                        return(new ReturnMessage(ex, callMessage));
                    }
                } while (true);

                // Handle enum and interface return types
                if (null != returnValue)
                {
                    if (returnType.IsInterface)
                    {
                        // Wrap the returned value in an intercepting COM wrapper
                        if (Marshal.IsComObject(returnValue))
                        {
                            returnValue = Wrap(returnValue, returnType, _TargetName);
                        }
                    }
                    else if (returnType.IsEnum)
                    {
                        // Convert to proper Enum type
                        returnValue = Enum.Parse(returnType, returnValue.ToString());
                    }
                }

                // Handle out args
                if (0 != outArgsCount)
                {
                    outArgs = new object[args.Length];
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        if (!argModifiers[0][i])
                        {
                            continue;
                        }

                        arg = args[i];
                        if (null == arg)
                        {
                            continue;
                        }

                        parameter = parameters[i];
                        wrapper   = null;

                        byValType = GetByValType(parameter.ParameterType);
                        if (typeof(Decimal) == byValType)
                        {
                            if (arg is CurrencyWrapper)
                            {
                                arg = ((CurrencyWrapper)arg).WrappedObject;
                            }
                        }
                        else if (byValType.IsEnum)
                        {
                            arg = Enum.Parse(byValType, arg.ToString());
                        }
                        else if (byValType.IsInterface)
                        {
                            if (Marshal.IsComObject(arg))
                            {
                                wrapper = originalArgs[i];
                                if (null != wrapper && wrapper._COMObject != arg)
                                {
                                    wrapper.Dispose();
                                    wrapper = null;
                                }

                                if (null == wrapper)
                                {
                                    wrapper = new COMWrapper(arg, byValType, _TargetName);
                                }
                                arg = wrapper.GetTransparentProxy();
                            }
                        }
                        outArgs[i] = arg;
                    }
                }
            }

            return(new ReturnMessage(returnValue, outArgs, outArgsCount, callMessage.LogicalCallContext, callMessage));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Get an Image from the IDataObject, don't check for FileDrop
        /// </summary>
        /// <param name="dataObject"></param>
        /// <returns>Image or null</returns>
        private static Image GetImage(IDataObject dataObject)
        {
            Image returnImage = null;

            if (dataObject != null)
            {
                IList <string> formats = GetFormats(dataObject);
                string[]       retrieveFormats;

                // Found a weird bug, where PNG's from Outlook 2010 are clipped
                // So I build some special logik to get the best format:
                if (formats != null && formats.Contains(FORMAT_PNG_OFFICEART) && formats.Contains(DataFormats.Dib))
                {
                    // Outlook ??
                    LOG.Info("Most likely the current clipboard contents come from Outlook, as this has a problem with PNG and others we place the DIB format to the front...");
                    retrieveFormats = new string[] { DataFormats.Dib, FORMAT_BITMAP_PLACEHOLDER, FORMAT_FILECONTENTS, FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, FORMAT_GIF };
                }
                else
                {
                    retrieveFormats = new string[] { FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, DataFormats.Dib, FORMAT_BITMAP_PLACEHOLDER, FORMAT_FILECONTENTS, FORMAT_GIF };
                }
                foreach (string currentFormat in retrieveFormats)
                {
                    if (FORMAT_BITMAP_PLACEHOLDER.Equals(currentFormat))
                    {
                        LOG.Info("Using default .NET Clipboard.GetImage()");
                        try
                        {
                            returnImage = Clipboard.GetImage();
                            if (returnImage != null)
                            {
                                return(returnImage);
                            }
                            else
                            {
                                LOG.Info("Clipboard.GetImage() didn't return an image.");
                            }
                        }
                        catch (Exception ex)
                        {
                            LOG.Error("Problem retrieving Image via Clipboard.GetImage(): ", ex);
                        }
                    }
                    else if (formats.Contains(currentFormat))
                    {
                        LOG.InfoFormat("Found {0}, trying to retrieve.", currentFormat);
                        if (currentFormat == DataFormats.Dib)
                        {
                            returnImage = GetDIBImage(dataObject);
                        }
                        else
                        {
                            returnImage = GetImageFormat(currentFormat, dataObject);
                        }
                        if (returnImage != null)
                        {
                            return(returnImage);
                        }
                    }
                    else
                    {
                        LOG.DebugFormat("Couldn't find format {0}.", currentFormat);
                    }
                }
            }
            return(null);
        }
Exemplo n.º 30
0
        /// <summary>
        /// A simple create instance, doesn't create a wrapper!!
        /// </summary>
        /// <returns>T</returns>
        public static T CreateInstance <T>()
        {
            Type type = typeof(T);

            if (null == type)
            {
                throw new ArgumentNullException("type");
            }
            if (!type.IsInterface)
            {
                throw new ArgumentException("The specified type must be an interface.", "type");
            }

            ComProgIdAttribute progIDAttribute = ComProgIdAttribute.GetAttribute(type);

            if (null == progIDAttribute || null == progIDAttribute.Value || 0 == progIDAttribute.Value.Length)
            {
                throw new ArgumentException("The specified type must define a ComProgId attribute.", "type");
            }
            string progId  = progIDAttribute.Value;
            Type   comType = null;

            if (progId.StartsWith("clsid:"))
            {
                Guid guid = new Guid(progId.Substring(6));
                try
                {
                    comType = Type.GetTypeFromCLSID(guid);
                }
                catch (Exception ex)
                {
                    LOG.WarnFormat("Error {1} type for {0}", progId, ex.Message);
                }
            }
            else
            {
                try
                {
                    comType = Type.GetTypeFromProgID(progId, true);
                }
                catch (Exception ex)
                {
                    LOG.WarnFormat("Error {1} type for {0}", progId, ex.Message);
                }
            }
            object comObject = null;

            if (comType != null)
            {
                try
                {
                    comObject = Activator.CreateInstance(comType);
                    if (comObject != null)
                    {
                        LOG.DebugFormat("Created new instance of {0} object.", progId);
                    }
                }
                catch (Exception e)
                {
                    LOG.WarnFormat("Error {1} creating object for {0}", progId, e.Message);
                }
            }
            if (comObject != null)
            {
                return((T)comObject);
            }
            return(default(T));
        }