Exemple #1
0
        /// <summary>
        /// Try to find the best match for the supplied IETF
        /// </summary>
        /// <param name="inputIETF"></param>
        /// <returns>IETF</returns>
        private static string FindBestIETFMatch(string inputIETF)
        {
            string returnIETF = inputIETF;

            if (string.IsNullOrEmpty(returnIETF))
            {
                returnIETF = DEFAULT_LANGUAGE;
            }
            returnIETF = ReformatIETF(returnIETF);
            if (!languageFiles.ContainsKey(returnIETF))
            {
                LOG.WarnFormat("Unknown language {0}, trying best match!", returnIETF);
                if (returnIETF.Length == 5)
                {
                    returnIETF = returnIETF.Substring(0, 2);
                }
                foreach (string availableIETF in languageFiles.Keys)
                {
                    if (availableIETF.StartsWith(returnIETF))
                    {
                        LOG.InfoFormat("Found language {0}, best match for {1}!", availableIETF, returnIETF);
                        returnIETF = availableIETF;
                        break;
                    }
                }
            }
            return(returnIETF);
        }
Exemple #2
0
        private void init()
        {
            saveFileDialog = new SaveFileDialog();
            applyFilterOptions();
            string initialDirectory = null;

            try
            {
                initialDirectory = Path.GetDirectoryName(conf.OutputFileAsFullpath);
            }
            catch
            {
                LOG.WarnFormat("OutputFileAsFullpath was set to {0}, ignoring due to problem in path.", conf.OutputFileAsFullpath);
            }

            if (!string.IsNullOrEmpty(initialDirectory) && Directory.Exists(initialDirectory))
            {
                saveFileDialog.InitialDirectory = initialDirectory;
            }
            else if (Directory.Exists(conf.OutputFilePath))
            {
                saveFileDialog.InitialDirectory = conf.OutputFilePath;
            }
            // The following property fixes a problem that the directory where we save is locked (bug #2899790)
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.OverwritePrompt  = true;
            saveFileDialog.CheckPathExists  = false;
            saveFileDialog.AddExtension     = true;
            ApplySuggestedValues();
        }
Exemple #3
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);
                if (Marshal.IsComObject(_COMObject))
                {
                    try
                    {
                        int count;
                        do
                        {
                            count = Marshal.ReleaseComObject(_COMObject);
                            LOG.DebugFormat("RCW count for {0} now is {1}", _interceptType, count);
                        } while (count > 0);
                    }
                    catch (Exception ex)
                    {
                        LOG.WarnFormat("Problem releasing COM object {0}", _COMType);
                        LOG.Warn("Error: ", ex);
                    }
                }
                else
                {
                    LOG.WarnFormat("{0} is not a COM object", _COMType);
                }

                _COMObject = null;
            }
        }
        /// <summary>
        /// Apply the language text to supplied control
        /// </summary>
        protected void ApplyLanguage(Control applyTo, string languageKey)
        {
            string langString = null;

            if (!string.IsNullOrEmpty(languageKey))
            {
                if (!Language.TryGetString(languageKey, out langString))
                {
                    LOG.WarnFormat("Wrong language key '{0}' configured for control '{1}'", languageKey, applyTo.Name);
                    return;
                }
                applyTo.Text = langString;
            }
            else
            {
                // Fallback to control name!
                if (Language.TryGetString(applyTo.Name, out langString))
                {
                    applyTo.Text = langString;
                    return;
                }
                if (!DesignMode)
                {
                    LOG.DebugFormat("Greenshot control without language key: {0}", applyTo.Name);
                }
            }
        }
Exemple #5
0
 /// <summary>
 /// Get the path of an executable
 /// </summary>
 /// <param name="exeName">e.g. cmd.exe</param>
 /// <returns>Path to file</returns>
 public static string GetExePath(string exeName)
 {
     using (RegistryKey key = Registry.LocalMachine.OpenSubKey(PATH_KEY + exeName, false))
     {
         if (key != null)
         {
             // "" is the default key, which should point to the requested location
             return((string)key.GetValue(""));
         }
     }
     foreach (string pathEntry in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(';'))
     {
         try
         {
             string path = pathEntry.Trim();
             if (!String.IsNullOrEmpty(path) && File.Exists(path = Path.Combine(path, exeName)))
             {
                 return(Path.GetFullPath(path));
             }
         }
         catch (Exception)
         {
             LOG.WarnFormat("Problem with path entry '{0}'.", pathEntry);
         }
     }
     return(null);
 }
Exemple #6
0
        public void Unlock()
        {
            if (IsDisposed() || id == null)
            {
                return;
            }

            try
            {
                Zookeeper.Delete(id, -1);
            }
            catch (ThreadInterruptedException)
            {
#if NET451
                Thread.CurrentThread.Interrupt();
#endif
            }
            catch (KeeperException.NoNodeException)
            {
                //do nothing
            }
            catch (KeeperException e)
            {
                LOG.WarnFormat("Caught: {0} {1}", e, e.StackTrace);
                throw;
            }
            finally
            {
                OnLockReleased();
                id = null;
            }
        }
Exemple #7
0
        /// <summary>
        /// Creates a PropertyItem (Metadata) to store with the image.
        /// For the possible ID's see: http://msdn.microsoft.com/de-de/library/system.drawing.imaging.propertyitem.id(v=vs.80).aspx
        /// This code uses Reflection to create a PropertyItem, although it's not adviced it's not as stupid as having a image in the project so we can read a PropertyItem from that!
        /// </summary>
        /// <param name="id">ID</param>
        /// <param name="text">Text</param>
        /// <returns></returns>
        private static PropertyItem CreatePropertyItem(int id, string text)
        {
            PropertyItem propertyItem = null;

            try
            {
                ConstructorInfo ci = typeof(PropertyItem).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, new Type[] { }, null);
                propertyItem = (PropertyItem)ci.Invoke(null);
                // Make sure it's of type string
                propertyItem.Type = 2;
                // Set the ID
                propertyItem.Id = id;
                // Set the text
                byte[] byteString = Encoding.ASCII.GetBytes(text + " ");
                // Set Zero byte for String end.
                byteString[byteString.Length - 1] = 0;
                propertyItem.Value = byteString;
                propertyItem.Len   = text.Length + 1;
            }
            catch (Exception e)
            {
                LOG.WarnFormat("Error creating a PropertyItem: {0}", e.Message);
            }
            return(propertyItem);
        }
Exemple #8
0
        /// <summary>
        /// Reload the Ini file
        /// </summary>
        public static void Reload()
        {
            // Clear the current properties
            sections = new Dictionary <string, Dictionary <string, string> >();
            // Load the defaults
            Read(CreateIniLocation(configName + DEFAULTS_POSTFIX + INI_EXTENSION, true));
            // Load the normal
            Read(CreateIniLocation(configName + INI_EXTENSION, false));
            // Load the fixed settings
            fixedProperties = Read(CreateIniLocation(configName + FIXED_POSTFIX + INI_EXTENSION, true));

            foreach (IniSection section in sectionMap.Values)
            {
                try
                {
                    section.Fill(PropertiesForSection(section));
                    FixProperties(section);
                }
                catch (Exception ex)
                {
                    string sectionName = "unknown";
                    if (section != null && section.IniSectionAttribute != null && section.IniSectionAttribute.Name != null)
                    {
                        sectionName = section.IniSectionAttribute.Name;
                    }
                    LOG.WarnFormat("Problem reading the ini section {0}", sectionName);
                    LOG.Warn("Exception", ex);
                }
            }
        }
Exemple #9
0
 public void Dispose()
 {
     try
     {
         action();
         sentinel.Dispose();
     }
     catch (Exception ex)
     {
         LOG.WarnFormat("Error disposing {0} : {1}", this.GetType().FullName, ex.Message);
     }
 }
Exemple #10
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);
     }
 }
        /// <summary>
        /// Add the greenshot property!
        /// </summary>
        /// <param name="imageToSave"></param>
        private static void AddTag(Image imageToSave)
        {
            // Create meta-data
            PropertyItem softwareUsedPropertyItem = CreatePropertyItem(PROPERTY_TAG_SOFTWARE_USED, "Greenshot");

            if (softwareUsedPropertyItem != null)
            {
                try
                {
                    imageToSave.SetPropertyItem(softwareUsedPropertyItem);
                }
                catch (Exception)
                {
                    LOG.WarnFormat("Couldn't set property {0}", softwareUsedPropertyItem.Id);
                }
            }
        }
Exemple #12
0
 private void CleanUp()
 {
     // fix for bug #3379053
     try
     {
         if (eagerlyCreatedDirectory != null && eagerlyCreatedDirectory.GetFiles().Length == 0 && eagerlyCreatedDirectory.GetDirectories().Length == 0)
         {
             eagerlyCreatedDirectory.Delete();
             eagerlyCreatedDirectory = null;
         }
     }
     catch (Exception e)
     {
         LOG.WarnFormat("Couldn't cleanup directory due to: {0}", e.Message);
         eagerlyCreatedDirectory = null;
     }
 }
Exemple #13
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);
     }
 }
Exemple #14
0
 public RemoteFileInfo(WinSCP.RemoteFileInfo _remoteFileInfo)
 {
     try
     {
         FilePermissions = _remoteFileInfo.FilePermissions;
         FileType        = _remoteFileInfo.FileType;
         Group           = _remoteFileInfo.Group;
         IsDirectory     = _remoteFileInfo.IsDirectory;
         LastWriteTime   = _remoteFileInfo.LastWriteTime;
         Length          = _remoteFileInfo.Length;
         Length32        = _remoteFileInfo.Length32;
         Name            = _remoteFileInfo.Name;
         Owner           = _remoteFileInfo.Owner;
     }
     catch (Exception e)
     {
         if (e.GetType() != typeof(OverflowException))
         {
             LOG.WarnFormat("Error: {0} : {1}", e.Message, e.StackTrace);
         }
     }
 }
Exemple #15
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"));
            }
        }
        /// <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;
            }
        }
        /// <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));
        }
        /// <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));
        }
Exemple #19
0
            /// <summary>
            /// サムネイルを生成します
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="args"></param>
            public void Do(object sender, DoWorkEventArgs args)
            {
                try
                {
                    // バイナリに出力
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        PngBitmapEncoder encoder = new PngBitmapEncoder();
                        var frame = BitmapFrame.Create((BitmapImage)this._ImageSource);
                        encoder.Frames.Add(frame);
                        encoder.Save(memoryStream);

                        using (var dbc = new ThumbDbContext())
                        {
                            var repo = new ThumbnailRepository(dbc);

                            if (string.IsNullOrEmpty(_rebuildThumbnailKey))
                            {
                                string key = null;
                                while (key == null)
                                {
                                    var tal = RandomAlphameric.RandomAlphanumeric(20);
                                    var r   = repo.FindFromKey(tal);
                                    if (r.Count == 0)
                                    {
                                        key = tal;
                                    }
                                    foreach (var p in r)
                                    {
                                        if (p.ThumbnailType != _ThumbnailType)
                                        {
                                            key = tal;
                                        }
                                    }
                                }

                                var thumbnail = new Thumbnail();
                                thumbnail.ThumbnailKey  = key;
                                thumbnail.ThumbnailType = _ThumbnailType;
                                thumbnail.BitmapBytes   = memoryStream.ToArray();

                                repo.Add(thumbnail);

                                _ThumbnailKey = key;
                            }
                            else
                            {
                                var thumbnail = repo.FindFromKey(_rebuildThumbnailKey);

                                // サムネイルタイプのエンティティが存在する場合、trueをセットする。
                                bool isThumbnailSave = false;
                                foreach (var prop in thumbnail)
                                {
                                    if (prop.ThumbnailType == _ThumbnailType)
                                    {
                                        prop.BitmapBytes = memoryStream.ToArray();
                                        isThumbnailSave  = true;
                                    }
                                }

                                if (!isThumbnailSave)
                                {
                                    // 指定したサムネイルタイプのエンティティを、
                                    // 新規作成する。
                                    var thumbnail_NewThumbnailType = new Thumbnail();
                                    thumbnail_NewThumbnailType.ThumbnailKey  = _rebuildThumbnailKey;
                                    thumbnail_NewThumbnailType.ThumbnailType = _ThumbnailType;
                                    thumbnail_NewThumbnailType.BitmapBytes   = memoryStream.ToArray();
                                    repo.Add(thumbnail_NewThumbnailType);
                                    _ThumbnailKey = _rebuildThumbnailKey;
                                }
                                else
                                {
                                    _ThumbnailKey = _rebuildThumbnailKey;
                                }
                            }
                            dbc.SaveChanges();
                        }
                    }
                }
                catch (NotSupportedException expr)
                {
                    LOG.WarnFormat(expr.Message);
                }
            }
Exemple #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);
            }
        }
Exemple #21
0
        /// <summary>
        /// Fill all GreenshotControls with the values from the configuration
        /// </summary>
        protected void FillFields()
        {
            foreach (FieldInfo field in GetCachedFields(GetType()))
            {
                Object controlObject = field.GetValue(this);
                if (controlObject == null)
                {
                    continue;
                }
                IGreenshotConfigBindable configBindable = controlObject as IGreenshotConfigBindable;
                if (configBindable == null)
                {
                    continue;
                }
                if (!string.IsNullOrEmpty(configBindable.SectionName) && !string.IsNullOrEmpty(configBindable.PropertyName))
                {
                    IniSection section = IniConfig.GetIniSection(configBindable.SectionName);
                    if (section != null)
                    {
                        IniValue iniValue = null;
                        if (!section.Values.TryGetValue(configBindable.PropertyName, out iniValue))
                        {
                            LOG.WarnFormat("Wrong property '{0}' configured for field '{1}'", configBindable.PropertyName, field.Name);
                            continue;
                        }

                        CheckBox checkBox = controlObject as CheckBox;
                        if (checkBox != null)
                        {
                            checkBox.Checked = (bool)iniValue.Value;
                            checkBox.Enabled = !iniValue.IsFixed;
                            continue;
                        }
                        RadioButton radíoButton = controlObject as RadioButton;
                        if (radíoButton != null)
                        {
                            radíoButton.Checked = (bool)iniValue.Value;
                            radíoButton.Enabled = !iniValue.IsFixed;
                            continue;
                        }

                        TextBox textBox = controlObject as TextBox;
                        if (textBox != null)
                        {
                            textBox.Text    = iniValue.ToString();
                            textBox.Enabled = !iniValue.IsFixed;
                            continue;
                        }

                        GreenshotComboBox comboxBox = controlObject as GreenshotComboBox;
                        if (comboxBox != null)
                        {
                            comboxBox.Populate(iniValue.ValueType);
                            comboxBox.SetValue((Enum)iniValue.Value);
                            comboxBox.Enabled = !iniValue.IsFixed;
                            continue;
                        }
                    }
                }
            }
            OnFieldsFilled();
        }
Exemple #22
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());
                return(null);
            }

            MethodInfo method = callMessage.MethodBase as MethodInfo;

            if (null == method)
            {
                LOG.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase);
                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;

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

            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
            {
                var invokeObject = _COMObject;
                var invokeType   = _COMType;

                object[]      args;
                ParameterInfo parameter;
                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
                Type         byValType;
                COMWrapper   wrapper;
                COMWrapper[] originalArgs;
                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 (InvalidComObjectException icoEx)
                    {
                        // Should assist BUG-1616 and others
                        LOG.WarnFormat("COM object {0} has been separated from its underlying RCW cannot be used. The COM object was released while it was still in use on another thread.", _interceptType.FullName);
                        return(new ReturnMessage(icoEx, callMessage));
                    }
                    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(string.Format("The destination {0} rejected Greenshot access, probably a dialog is open. Close the dialog and try again.",
                                                                                destinationName), "Greenshot access rejected", 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;
                        }

                        var 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));
        }
Exemple #23
0
        private bool LockOperation()
        {
            do
            {
                if (id == null)
                {
                    long   sessionId = Zookeeper.SessionId;
                    string prefix    = "x-" + sessionId + "-";
                    FindPrefixInChildren(prefix, Zookeeper, dir);
                    idName = new ZNodeName(id);
                }

                if (id == null)
                {
                    continue;
                }

                var names = Zookeeper.GetChildren(dir, false);
                if (names.IsEmpty())
                {
                    LOG.WarnFormat("No children in: {0} when we've just created one! Lets recreate it...", dir);
                    // lets force the recreation of the id
                    id = null;
                }
                else
                {
                    // lets sort them explicitly (though they do seem to come back in order ususally :)
                    var sortedNames = new SortedSet <ZNodeName>();
                    foreach (string name in names)
                    {
                        sortedNames.Add(new ZNodeName(dir.Combine(name)));
                    }
                    ownerId = sortedNames.First().Name;
                    SortedSet <ZNodeName> lessThanMe = sortedNames.HeadSet(idName);
                    if (!lessThanMe.IsEmpty())
                    {
                        ZNodeName lastChildName = lessThanMe.Last();
                        lastChildId = lastChildName.Name;
                        if (LOG.IsDebugEnabled)
                        {
                            LOG.DebugFormat("watching less than me node: {0}", lastChildId);
                        }
                        Stat stat = Zookeeper.Exists(lastChildId, new LockWatcher(this));
                        if (stat != null)
                        {
                            return(false);
                        }

                        LOG.WarnFormat("Could not find the stats for less than me: {0}", lastChildName.Name);
                    }
                    else
                    {
                        if (Owner)
                        {
                            OnLockAcquired();
                            return(true);
                        }
                    }
                }
            } while (id == null);
            return(false);
        }
Exemple #24
0
        /// <summary>
        /// Write the passed Image to a tmp-file and call an external process, than read the file back and write it to the targetStream
        /// </summary>
        /// <param name="imageToProcess">Image to pass to the external process</param>
        /// <param name="targetStream">stream to write the processed image to</param>
        /// <returns></returns>
        private static bool ProcessPNGImageExternally(Image imageToProcess, Stream targetStream)
        {
            if (string.IsNullOrEmpty(conf.OptimizePNGCommand))
            {
                return(false);
            }
            if (!File.Exists(conf.OptimizePNGCommand))
            {
                LOG.WarnFormat("Can't find 'OptimizePNGCommand' {0}", conf.OptimizePNGCommand);
                return(false);
            }
            string tmpFileName = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".png");

            try
            {
                using (FileStream tmpStream = File.Create(tmpFileName))
                {
                    LOG.DebugFormat("Writing png to tmp file: {0}", tmpFileName);
                    imageToProcess.Save(tmpStream, ImageFormat.Png);
                    if (LOG.IsDebugEnabled)
                    {
                        LOG.DebugFormat("File size before processing {0}", new FileInfo(tmpFileName).Length);
                    }
                }
                if (LOG.IsDebugEnabled)
                {
                    LOG.DebugFormat("Starting : {0}", conf.OptimizePNGCommand);
                }

                ProcessStartInfo processStartInfo = new ProcessStartInfo(conf.OptimizePNGCommand);
                processStartInfo.Arguments              = string.Format(conf.OptimizePNGCommandArguments, tmpFileName);
                processStartInfo.CreateNoWindow         = true;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.RedirectStandardError  = true;
                processStartInfo.UseShellExecute        = false;
                using (Process process = Process.Start(processStartInfo))
                {
                    if (process != null)
                    {
                        process.WaitForExit();
                        if (process.ExitCode == 0)
                        {
                            if (LOG.IsDebugEnabled)
                            {
                                LOG.DebugFormat("File size after processing {0}", new FileInfo(tmpFileName).Length);
                                LOG.DebugFormat("Reading back tmp file: {0}", tmpFileName);
                            }
                            byte[] processedImage = File.ReadAllBytes(tmpFileName);
                            targetStream.Write(processedImage, 0, processedImage.Length);
                            return(true);
                        }
                        LOG.ErrorFormat("Error while processing PNG image: {0}", process.ExitCode);
                        LOG.ErrorFormat("Output: {0}", process.StandardOutput.ReadToEnd());
                        LOG.ErrorFormat("Error: {0}", process.StandardError.ReadToEnd());
                    }
                }
            }
            catch (Exception e)
            {
                LOG.Error("Error while processing PNG image: ", e);
            }
            finally
            {
                if (File.Exists(tmpFileName))
                {
                    LOG.DebugFormat("Cleaning up tmp file: {0}", tmpFileName);
                    File.Delete(tmpFileName);
                }
            }
            return(false);
        }
Exemple #25
0
        /// <summary>
        /// Scan the files in all directories
        /// </summary>
        private static void ScanFiles()
        {
            languageFiles.Clear();
            helpFiles.Clear();
            foreach (string languagePath in languagePaths)
            {
                if (!Directory.Exists(languagePath))
                {
                    LOG.InfoFormat("Skipping non existing language path {0}", languagePath);
                    continue;
                }
                LOG.InfoFormat("Searching language directory '{0}' for language files with pattern '{1}'", languagePath, LANGUAGE_FILENAME_PATTERN);
                try
                {
                    foreach (string languageFilepath in Directory.GetFiles(languagePath, LANGUAGE_FILENAME_PATTERN, SearchOption.AllDirectories))
                    {
                        //LOG.DebugFormat("Found language file: {0}", languageFilepath);
                        LanguageFile languageFile = LoadFileInfo(languageFilepath);
                        if (languageFile == null)
                        {
                            continue;
                        }
                        if (string.IsNullOrEmpty(languageFile.Ietf))
                        {
                            LOG.WarnFormat("Fixing missing ietf in language-file {0}", languageFilepath);
                            string languageFilename = Path.GetFileName(languageFilepath);
                            if (IETF_REGEXP.IsMatch(languageFilename))
                            {
                                string replacementIETF = IETF_REGEXP.Replace(languageFilename, "$1");
                                languageFile.Ietf = ReformatIETF(replacementIETF);
                                LOG.InfoFormat("Fixed IETF to {0}", languageFile.Ietf);
                            }
                            else
                            {
                                LOG.ErrorFormat("Missing ietf , no recover possible... skipping language-file {0}!", languageFilepath);
                                continue;
                            }
                        }

                        // Check if we can display the file
                        if (!string.IsNullOrEmpty(languageFile.LanguageGroup) && unsupportedLanguageGroups.Contains(languageFile.LanguageGroup))
                        {
                            LOG.InfoFormat("Skipping unsuported (not able to display) language {0} from file {1}", languageFile.Description, languageFilepath);
                            continue;
                        }

                        // build prefix, based on the filename, but only if it's not set in the file itself.
                        if (string.IsNullOrEmpty(languageFile.Prefix))
                        {
                            string languageFilename = Path.GetFileNameWithoutExtension(languageFilepath);
                            if (PREFIX_REGEXP.IsMatch(languageFilename))
                            {
                                languageFile.Prefix = PREFIX_REGEXP.Replace(languageFilename, "$1");
                                if (!string.IsNullOrEmpty(languageFile.Prefix))
                                {
                                    languageFile.Prefix = languageFile.Prefix.Replace("plugin", "").ToLower();
                                }
                            }
                        }
                        List <LanguageFile> currentFiles = null;
                        if (languageFiles.ContainsKey(languageFile.Ietf))
                        {
                            currentFiles = languageFiles[languageFile.Ietf];
                            bool needToAdd = true;
                            List <LanguageFile> deleteList = new List <LanguageFile>();
                            foreach (LanguageFile compareWithLangfile in currentFiles)
                            {
                                if ((languageFile.Prefix == null && compareWithLangfile.Prefix == null) || (languageFile.Prefix != null && languageFile.Prefix.Equals(compareWithLangfile.Prefix)))
                                {
                                    if (compareWithLangfile.Version > languageFile.Version)
                                    {
                                        LOG.WarnFormat("Skipping {0}:{1}:{2} as {3}:{4}:{5} is newer", languageFile.Filepath, languageFile.Prefix, languageFile.Version, compareWithLangfile.Filepath, compareWithLangfile.Prefix, compareWithLangfile.Version);
                                        needToAdd = false;
                                        break;
                                    }
                                    else
                                    {
                                        LOG.WarnFormat("Found {0}:{1}:{2} and deleting {3}:{4}:{5}", languageFile.Filepath, languageFile.Prefix, languageFile.Version, compareWithLangfile.Filepath, compareWithLangfile.Prefix, compareWithLangfile.Version);
                                        deleteList.Add(compareWithLangfile);
                                    }
                                }
                            }
                            if (needToAdd)
                            {
                                foreach (LanguageFile deleteFile in deleteList)
                                {
                                    currentFiles.Remove(deleteFile);
                                }
                                LOG.InfoFormat("Added language {0} from: {1}", languageFile.Description, languageFile.Filepath);
                                currentFiles.Add(languageFile);
                            }
                        }
                        else
                        {
                            currentFiles = new List <LanguageFile>();
                            currentFiles.Add(languageFile);
                            languageFiles.Add(languageFile.Ietf, currentFiles);
                            LOG.InfoFormat("Added language {0} from: {1}", languageFile.Description, languageFile.Filepath);
                        }
                    }
                }
                catch (DirectoryNotFoundException)
                {
                    LOG.InfoFormat("Non existing language directory: {0}", languagePath);
                }
                catch (Exception e)
                {
                    LOG.Error("Error trying for read directory " + languagePath, e);
                }

                // Now find the help files
                LOG.InfoFormat("Searching language directory '{0}' for help files with pattern '{1}'", languagePath, HELP_FILENAME_PATTERN);
                try
                {
                    foreach (string helpFilepath in Directory.GetFiles(languagePath, HELP_FILENAME_PATTERN, SearchOption.AllDirectories))
                    {
                        LOG.DebugFormat("Found help file: {0}", helpFilepath);
                        string helpFilename = Path.GetFileName(helpFilepath);
                        string ietf         = ReformatIETF(helpFilename.Replace(".html", "").Replace("help-", ""));
                        if (!helpFiles.ContainsKey(ietf))
                        {
                            helpFiles.Add(ietf, helpFilepath);
                        }
                        else
                        {
                            LOG.WarnFormat("skipping help file {0}, already a file with the same IETF {1} found!", helpFilepath, ietf);
                        }
                    }
                }
                catch (DirectoryNotFoundException)
                {
                    LOG.InfoFormat("Non existing language directory: {0}", languagePath);
                }
                catch (Exception e)
                {
                    LOG.Error("Error trying for read directory " + languagePath, e);
                }
            }
        }