Esempio n. 1
0
        private void Write(object comObject, ConfigurationName name, bool?posting)
        {
            object argument;
            string argumentString;

            if (name.Scope == ConfigurationScope.егистрыСведений)
            {
                argument       = true;
                argumentString = argument.ToString();
            }
            else
            {
                var writeModeName = posting.HasValue ? (posting.Value ? "Проведение" : "ОтменаПроведения") : "Запись";
                var writeMode     = globalContext.ежимЗаписиДокумента();
                argument       = ComHelpers.GetProperty(writeMode, writeModeName);
                argumentString = "РежимЗаписиДокумента." + writeModeName;
            }
            try
            {
                ComHelpers.Invoke(comObject, "Write", argument);
            }
            catch (TargetInvocationException e)
            {
                const string messageFormat = "error writing document [{0}] with argument [{1}]";
                throw new InvalidOperationException(string.Format(messageFormat, name.Fullname, argumentString),
                                                    e.InnerException);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Destroys object
        /// </summary>
        public void Dispose()
        {
            if (_disposedFlag.Set())
            {
                _activeScriptGarbageCollector = null;
                if (_is64Bit)
                {
                    _activeScriptParse64 = null;
                }
                else
                {
                    _activeScriptParse32 = null;
                }

                ComHelpers.ReleaseAndEmpty(ref _pActiveScriptGarbageCollector);
                if (_is64Bit)
                {
                    ComHelpers.ReleaseAndEmpty(ref _pActiveScriptDebug64);
                    ComHelpers.ReleaseAndEmpty(ref _pActiveScriptParse64);
                }
                else
                {
                    ComHelpers.ReleaseAndEmpty(ref _pActiveScriptDebug32);
                    ComHelpers.ReleaseAndEmpty(ref _pActiveScriptParse32);
                }
                ComHelpers.ReleaseAndEmpty(ref _pActiveScript);

                if (_activeScript != null)
                {
                    _activeScript.Close();
                    Marshal.FinalReleaseComObject(_activeScript);
                    _activeScript = null;
                }
            }
        }
        private string[] GetPropertyTypes(object a)
        {
            var type        = ComHelpers.GetProperty(a, "Тип");
            var typesObject = ComHelpers.Invoke(type, "Типы");
            var typesCount  = Call.Количество(typesObject);

            if (typesCount == 0)
            {
                throw new InvalidOperationException("assertion failure");
            }
            var types = new string[typesCount];

            for (var i = 0; i < typesCount; i++)
            {
                var typeObject         = Call.Получить(typesObject, i);
                var stringPresentation = globalContext.String(typeObject);
                if (MetadataHelpers.simpleTypesMap.ContainsKey(stringPresentation))
                {
                    return(null);
                }
                var propertyComObject = Call.НайтиПоТипу(globalContext.Metadata, typeObject);
                if (propertyComObject == null)
                {
                    return(null);
                }
                types[i] = Call.ПолноеИмя(propertyComObject);
            }
            return(types);
        }
Esempio n. 4
0
        /// <summary>
        /// Determines each column's width.
        /// </summary>
        /// <param name="range">Range with columns to examine.</param>
        /// <returns>An array of integers representing column widths.
        /// Caveat: This array is 1-based!</returns>
        private int[] ColumnWidths(Range range)
        {
            Range columns    = range.Columns;
            long  numColumns = columns.Count;

            int[] widths = new int[numColumns + 1];
            Logger.Info("ColumnWidths: Computing widths of {0} columns", numColumns);
            for (long i = 1; i <= numColumns; i++)
            {
                Range column = columns[i];
                Range cells  = column.Cells;
                for (int j = 1; j <= cells.Count; j++)
                {
                    Range cell = cells[j];
                    int   w    = ValueToString(cell.Value2).Length;
                    if (w > widths[i])
                    {
                        widths[i] = w;
                    }
                    ComHelpers.ReleaseComObject(cell);
                    if (IsCancellationRequested)
                    {
                        break;
                    }
                }
                ComHelpers.ReleaseComObject(cells);
                ComHelpers.ReleaseComObject(column);
                if (IsCancellationRequested)
                {
                    break;
                }
            }
            ComHelpers.ReleaseComObject(columns);
            return(widths);
        }
Esempio n. 5
0
        private void EmitTableSections(ClassGenerationContext classContext, string tableSectionsName,
                                       ConfigurationItemDescriptor descriptor)
        {
            var tableSections = ComHelpers.GetProperty(classContext.comObject, tableSectionsName);

            foreach (var tableSection in (IEnumerable)tableSections)
            {
                var tableSectionName   = Call.Имя(tableSection);
                var nestedClassContext = new ClassGenerationContext
                {
                    comObject         = tableSection,
                    descriptor        = descriptor,
                    generationContext = classContext.generationContext,
                    target            = new ClassModel
                    {
                        Name = "ТабличнаяЧасть" + tableSectionName
                    }
                };
                EmitClass(nestedClassContext);
                classContext.EmitNestedClass(nestedClassContext.target);
                classContext.EmitProperty(new PropertyModel
                {
                    Type         = string.Format("List<{0}>", nestedClassContext.target.Name),
                    PropertyName = tableSectionName
                });
            }
        }
        /// <summary>
        /// Destroys object
        /// </summary>
        /// <param name="disposing">Flag, allowing destruction of
        /// managed objects contained in fields of class</param>
        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                _disposed = true;

                _lastException = null;

                if (_siteItems != null)
                {
                    _siteItems.Clear();
                    _siteItems = null;
                }

                if (_dispatch != null)
                {
                    ComHelpers.ReleaseComObject(ref _dispatch, !disposing);
                    _dispatch = null;
                }

                if (_activeScriptParse != null)
                {
                    _activeScriptParse.Dispose();
                    _activeScriptParse = null;
                }

                _activeScript = null;
            }
        }
Esempio n. 7
0
        private void EmitConstants(GenerationContext context)
        {
            var constants      = ComHelpers.GetProperty(globalContext.Metadata, "Константы");
            var constantsCount = Call.Количество(constants);

            for (var i = 0; i < constantsCount; i++)
            {
                var constant       = Call.Получить(constants, i);
                var typeDescriptor = ExtractType(constant, context);
                if (!typeDescriptor.HasValue)
                {
                    continue;
                }
                var configurationName = new ConfigurationName(ConfigurationScope.Константы,
                                                              Call.Имя(constant));
                var template = new ConstantFileTemplate
                {
                    Model = new ConstantFileModel
                    {
                        Type      = typeDescriptor.Value.name,
                        Name      = configurationName.Name,
                        Synonym   = GenerateHelpers.EscapeString(Call.Синоним(constant)),
                        Namespace = GetNamespaceName(configurationName.Scope),
                        MaxLength = typeDescriptor.Value.maxLength
                    }
                };
                context.Write(configurationName, template.TransformText());
            }
        }
Esempio n. 8
0
        private void EmitEnum(ConfigurationItem item, GenerationContext context)
        {
            var model = new EnumFileModel
            {
                Name      = item.Name.Name,
                Namespace = GetNamespaceName(item.Name.Scope)
            };
            var values = ComHelpers.GetProperty(item.ComObject, "ЗначенияПеречисления");
            var count  = Call.Количество(values);

            for (var i = 0; i < count; i++)
            {
                var value = Call.Получить(values, i);
                model.Items.Add(new EnumItemModel
                {
                    Name    = Call.Имя(value),
                    Synonym = GenerateHelpers.EscapeString(Call.Синоним(value))
                });
            }
            var enumFileTemplate = new EnumFileTemplate {
                Model = model
            };

            context.Write(item.Name, enumFileTemplate.TransformText());
        }
        public void Recreate()
        {
            object comTable = null;

            LogHelpers.LogWithTiming("loading COM schema info",
                                     () => comTable = ComHelpers.Invoke(globalContext.ComObject(),
                                                                        "ПолучитьСтруктуруХраненияБазыДанных", Missing.Value, true));

            TableMapping[] tableMappings = null;
            LogHelpers.LogWithTiming("extracting table mappings from COM schema info",
                                     () => tableMappings = ExtractTableMappingsFromCom(comTable));

            LogHelpers.LogWithTiming("recreating db schema",
                                     () => database.RecreateSchema("simple1c"));

            LogHelpers.LogWithTiming("writing table mappings to db",
                                     () => store.WriteTableMappings(tableMappings));

            EnumMapping[] enumMappings = null;
            LogHelpers.LogWithTiming("extracting enum mappings from COM ",
                                     () => enumMappings = ExtractEnumMappingsFromCom());

            LogHelpers.LogWithTiming("writing enum mappings to db",
                                     () => store.WriteEnumMappings(enumMappings));

            LogHelpers.LogWithTiming("creating helper functions", () => CreateHelperFunctions(tableMappings));
        }
Esempio n. 10
0
        public static IEnumerable <object> GetAttributes(object comObject, ConfigurationItemDescriptor descriptor)
        {
            var standardAttributes = ComHelpers.GetProperty(comObject, "СтандартныеРеквизиты");
            var isChartOfAccounts  = Call.Имя(comObject) == "Хозрасчетный";

            foreach (var attr in (IEnumerable)standardAttributes)
            {
                var name = Call.Имя(attr);
                if (isChartOfAccounts && name != "Код" && name != "Наименование")
                {
                    continue;
                }
                if (standardPropertiesToExclude.Contains(name))
                {
                    continue;
                }
                yield return(attr);
            }
            foreach (var propertyName in descriptor.AttributePropertyNames)
            {
                var attributes      = ComHelpers.GetProperty(comObject, propertyName);
                var attributesCount = Call.Количество(attributes);
                for (var i = 0; i < attributesCount; ++i)
                {
                    yield return(Call.Получить(attributes, i));
                }
            }
        }
Esempio n. 11
0
        private int?GetMaxLength(object attribute)
        {
            var type        = ComHelpers.GetProperty(attribute, "Тип");
            var typesObject = ComHelpers.Invoke(type, "Типы");
            var typesCount  = Call.Количество(typesObject);

            if (typesCount != 1)
            {
                return(null);
            }
            var typeObject         = Call.Получить(typesObject, 0);
            var stringPresentation = globalContext.String(typeObject);

            if (stringPresentation != "Строка")
            {
                return(null);
            }
            var квалификаторыСтроки = ComHelpers.GetProperty(type, "КвалификаторыСтроки");
            var result = Call.IntProp(квалификаторыСтроки, "Длина");

            if (result == 0)
            {
                return(null);
            }
            return(result);
        }
Esempio n. 12
0
        private dynamic EnumValue(string enumName, string enumValue)
        {
            var enumsObject = ComObject().Перечисления;
            var enumObject  = ComHelpers.GetProperty(enumsObject, enumName);

            return(ComHelpers.GetProperty(enumObject, enumValue));
        }
Esempio n. 13
0
        /// <summary>
        /// Creates a wrapper for the process debug manager. A return value indicates whether
        /// the creation succeeded.
        /// </summary>
        /// <param name="wrapper">Wrapper for process debug manager</param>
        /// <returns>true if the wrapper was created successfully; otherwise, false.</returns>
        public static bool TryCreate(out ProcessDebugManagerWrapper wrapper)
        {
            const string progId = "ProcessDebugManager";

            if (Utils.Is64BitProcess())
            {
                IProcessDebugManager64 processDebugManager64;
                if (ComHelpers.TryCreateComObject(progId, null, out processDebugManager64))
                {
                    wrapper = new ProcessDebugManagerWrapper(processDebugManager64);
                    return(true);
                }
            }
            else
            {
                IProcessDebugManager32 processDebugManager32;
                if (ComHelpers.TryCreateComObject(progId, null, out processDebugManager32))
                {
                    wrapper = new ProcessDebugManagerWrapper(processDebugManager32);
                    return(true);
                }
            }

            wrapper = null;
            return(false);
        }
Esempio n. 14
0
        private IEnumerable Execute(BuiltQuery builtQuery)
        {
            if (EntityHelpers.IsConstant(builtQuery.EntityType))
            {
                var constantWrapType = builtQuery.EntityType.BaseType;
                if (constantWrapType == null)
                {
                    throw new InvalidOperationException("assertion failure");
                }
                var constantWrap = (Constant)FormatterServices.GetUninitializedObject(builtQuery.EntityType);
                var constants    = ComHelpers.GetProperty(globalContext.ComObject(), "Константы");
                var constant     = ComHelpers.GetProperty(constants, builtQuery.EntityType.Name);
                var value        = ComHelpers.Invoke(constant, "Получить");
                constantWrap.ЗначениеНетипизированное = comObjectMapper.MapFrom1C(value,
                                                                                  constantWrapType.GetGenericArguments()[0]);
                yield return(constantWrap);

                yield break;
            }
            var queryText  = builtQuery.QueryText;
            var parameters = builtQuery.Parameters;

            parametersConverter.ConvertParametersTo1C(parameters);
            var hasReference = ConfigurationName.Get(builtQuery.EntityType).HasReference;
            var queryResult  = globalContext.Execute(queryText, parameters);

            if (hasReference || builtQuery.Projection != null)
            {
                var projection = builtQuery.Projection != null
                    ? ProjectionMapperFactory.GetMapper(builtQuery.Projection, comObjectMapper)
                    : null;

                var selection = queryResult.Select();
                while (selection.Next())
                {
                    if (projection != null)
                    {
                        yield return(projection(selection.ComObject));
                    }
                    else if (builtQuery.IsCount)
                    {
                        yield return(comObjectMapper.MapFrom1C(selection["src_Count"], typeof(int)));
                    }
                    else
                    {
                        yield return(comObjectMapper.MapFrom1C(selection["Ссылка"], builtQuery.EntityType));
                    }
                }
            }
            else
            {
                var valueTable = queryResult.Unload();
                foreach (var r in valueTable)
                {
                    yield return(comObjectMapper.MapFrom1C(r.ComObject(), builtQuery.EntityType));
                }
            }
        }
Esempio n. 15
0
        bool IValueSource.TryLoadValue(string name, Type type, out object result)
        {
            var isUniqueIdentifier = name == EntityHelpers.idPropertyName && type == typeof(Guid?);
            var propertyValue      = isUniqueIdentifier
                ? ComHelpers.Invoke(comObject, name)
                : ComHelpers.GetProperty(comObject, name);

            result = comObjectMapper.MapFrom1C(propertyValue, type);
            return(true);
        }
Esempio n. 16
0
        private static void UpdateIfExists(Abstract1CEntity target, object source, string propertyName)
        {
            var property = target.GetType().GetProperty(propertyName);

            if (property == null)
            {
                return;
            }
            SetValueWithoutTracking(target, property, ComHelpers.GetProperty(source, propertyName));
        }
Esempio n. 17
0
        public ConfigurationItem FindMetaByName(ConfigurationName fullname)
        {
            var itemMetadata = ComHelpers.Invoke(Metadata, "НайтиПоПолномуИмени", fullname.Fullname);

            if (itemMetadata == null)
            {
                const string messageFormat = "can't find [{0}]";
                throw new InvalidOperationException(string.Format(messageFormat, fullname.Fullname));
            }
            return(new ConfigurationItem(fullname, itemMetadata));
        }
Esempio n. 18
0
        /// <summary>
        /// Constructs an instance of the ActiveScript JavaScript engine
        /// </summary>
        /// <param name="clsid">CLSID of JavaScript engine</param>
        /// <param name="engineMode">JavaScript engine mode</param>
        /// <param name="lowerIeVersion">Lowest supported version of Internet Explorer</param>
        /// <param name="languageVersion">Version of script language</param>
        /// <param name="useEcmaScript5Polyfill">Flag for whether to use the ECMAScript 5 Polyfill</param>
        /// <param name="useJson2Library">Flag for whether to use the JSON2 library</param>
        protected ActiveScriptJsEngineBase(string clsid, JsEngineMode engineMode, string lowerIeVersion,
                                           ScriptLanguageVersion languageVersion, bool useEcmaScript5Polyfill, bool useJson2Library)
        {
            _engineMode      = engineMode;
            _engineModeName  = JsEngineModeHelpers.GetModeName(engineMode);
            _documentVersion = DateTime.UtcNow.ToString("o");

            _dispatcher.Invoke(() =>
            {
                _pActiveScript = IntPtr.Zero;

                try
                {
                    _pActiveScript = ComHelpers.CreateInstanceByClsid <IActiveScript>(clsid);
                    _activeScript  = (IActiveScript)Marshal.GetObjectForIUnknown(_pActiveScript);
                }
                catch (Exception e)
                {
                    throw new JsEngineLoadException(
                        string.Format(CommonStrings.Runtime_IeJsEngineNotLoaded,
                                      _engineModeName, lowerIeVersion, e.Message), _engineModeName);
                }

                if (languageVersion != ScriptLanguageVersion.None)
                {
                    var activeScriptProperty = _activeScript as IActiveScriptProperty;
                    if (activeScriptProperty != null)
                    {
                        object scriptLanguageVersion = (int)languageVersion;
                        uint result = activeScriptProperty.SetProperty((uint)ScriptProperty.InvokeVersioning,
                                                                       IntPtr.Zero, ref scriptLanguageVersion);
                        if (result != (uint)ScriptHResult.Ok)
                        {
                            throw new JsEngineLoadException(
                                string.Format(NetFrameworkStrings.Runtime_ActiveScriptLanguageVersionSelectionFailed, languageVersion));
                        }
                    }
                }

                _activeScriptParse = new ActiveScriptParseWrapper(_pActiveScript, _activeScript);
                _activeScriptParse.InitNew();

                _pActiveScriptGarbageCollector = ComHelpers.QueryInterfaceNoThrow <IActiveScriptGarbageCollector>(_pActiveScript);
                _activeScriptGarbageCollector  = _activeScript as IActiveScriptGarbageCollector;

                _activeScript.SetScriptSite(this);
                _activeScript.SetScriptState(ScriptState.Started);

                InitScriptDispatch();
            });

            LoadResources(useEcmaScript5Polyfill, useJson2Library);
        }
Esempio n. 19
0
        public object GetValue(object queryResultRow)
        {
            var result = ComHelpers.GetProperty(queryResultRow, Alias);

            if (isUniqueIdentifier)
            {
                result = result == null || result == DBNull.Value
                    ? null
                    : ComHelpers.Invoke(result, EntityHelpers.idPropertyName);
            }
            return(result);
        }
Esempio n. 20
0
        private void SaveConstant(Constant constantEntity)
        {
            var configurationName = new ConfigurationName(ConfigurationScope.Константы,
                                                          constantEntity.GetType().Name);
            var metadata    = metadataAccessor.GetMetadata(configurationName);
            var valueToSave = constantEntity.ЗначениеНетипизированное;

            metadata.Validate(null, valueToSave);
            var constant = globalContext.GetManager(configurationName);
            var value    = comObjectMapper.MapTo1C(valueToSave);

            ComHelpers.Invoke(constant, "Установить", value);
        }
Esempio n. 21
0
        private EnumMapItem[] GetMappings(Type enumType)
        {
            var enumeration = ComHelpers.GetProperty(enumerations, enumType.Name);

            return(Enum.GetValues(enumType)
                   .Cast <object>()
                   .Select(v => new EnumMapItem
            {
                value = v,
                index = Convert.ToInt32(ComHelpers.Invoke(enumeration, "IndexOf",
                                                          ComHelpers.GetProperty(enumeration, v.ToString())))
            })
                   .ToArray());
        }
Esempio n. 22
0
        private void UpdateId(object source, Abstract1CEntity target, ConfigurationName name)
        {
            var property = target.GetType().GetProperty(EntityHelpers.idPropertyName);

            if (property == null)
            {
                const string messageFormat = "type [{0}] has no id";
                throw new InvalidOperationException(string.Format(messageFormat, name));
            }
            var idValue = ComHelpers.Invoke(source, EntityHelpers.idPropertyName);

            idValue = comObjectMapper.MapFrom1C(idValue, typeof(Guid));
            SetValueWithoutTracking(target, property, idValue);
        }
Esempio n. 23
0
        private object MapEnumFrom1C(Type enumType, object value1C)
        {
            var enumeration = ComHelpers.GetProperty(enumerations, enumType.Name);
            var valueIndex  = Convert.ToInt32(ComHelpers.Invoke(enumeration, "IndexOf", value1C));
            var result      = mappingSource.EnumMappingsCache.GetOrAdd(enumType, GetMappings)
                              .SingleOrDefault(x => x.index == valueIndex);

            if (result == null)
            {
                const string messageFormat = "can't map value [{0}] to enum [{1}]";
                throw new InvalidOperationException(string.Format(messageFormat,
                                                                  globalContext.String(value1C), enumType.Name));
            }
            return(result.value);
        }
Esempio n. 24
0
 /// <summary>
 /// Destroys object
 /// </summary>
 /// <param name="disposing">Flag, allowing destruction of
 /// managed objects contained in fields of class</param>
 private void Dispose(bool disposing)
 {
     if (_disposedFlag.Set())
     {
         if (_is64Bit)
         {
             _activeScriptParse64 = null;
             ComHelpers.ReleaseAndEmpty(ref _pActiveScriptParse64);
         }
         else
         {
             _activeScriptParse32 = null;
             ComHelpers.ReleaseAndEmpty(ref _pActiveScriptParse32);
         }
     }
 }
        public void RecreateRoutines()
        {
            object comTable = null;

            LogHelpers.LogWithTiming("loading COM schema info",
                                     () => comTable = ComHelpers.Invoke(globalContext.ComObject(),
                                                                        "ПолучитьСтруктуруХраненияБазыДанных", Missing.Value, true));

            TableMapping[] tableMappings = null;
            LogHelpers.LogWithTiming("extracting table mappings from COM schema info",
                                     () => tableMappings = ExtractTableMappingsFromCom(comTable));

            LogHelpers.LogWithTiming("removing helper functions", RemoveHelperFunctions);

            LogHelpers.LogWithTiming("creating helper functions", () => CreateHelperFunctions(tableMappings));
        }
        /// <summary>
        /// Destroys object
        /// </summary>
        /// <param name="disposing">Flag, allowing destruction of
        /// managed objects contained in fields of class</param>
        private void Dispose(bool disposing)
        {
            if (_disposedFlag.Set())
            {
                _dispatcher.Invoke(() =>
                {
                    if (_dispatch != null)
                    {
                        ComHelpers.ReleaseComObject(ref _dispatch, !disposing);
                        _dispatch = null;
                    }

                    if (_activeScriptWrapper != null)
                    {
                        _activeScriptWrapper.Dispose();
                        _activeScriptWrapper = null;
                    }
                });

                if (disposing)
                {
                    if (_debuggingStarted && _debugDocuments != null)
                    {
                        foreach (UIntPtr debugDocumentKey in _debugDocuments.Keys)
                        {
                            var debugDocumentValue = _debugDocuments[debugDocumentKey];
                            debugDocumentValue.Close();
                        }

                        _debugDocuments.Clear();
                    }

                    if (_processDebugManagerWrapper != null)
                    {
                        _processDebugManagerWrapper.RemoveApplication(_debugApplicationCookie);
                        _debugApplicationWrapper.Close();
                    }

                    if (_hostItems != null)
                    {
                        _hostItems.Clear();
                    }

                    _lastException = null;
                }
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Used by a smart host to delegate the <see cref="IDebugDocumentContext.EnumCodeContexts"/> method
        /// </summary>
        /// <param name="sourceContext">The source context as provided to
        /// <see cref="IActiveScriptParse32.ParseScriptText"/> or
        /// <see cref="IActiveScriptParse32.AddScriptlet"/></param>
        /// <param name="offset">Character offset relative to start of script text</param>
        /// <param name="length">Number of characters in this context</param>
        /// <param name="enumContexts">An enumerator of the code contexts in the specified range</param>
        public void EnumCodeContextsOfPosition(UIntPtr sourceContext, uint offset, uint length,
                                               out IEnumDebugCodeContexts enumContexts)
        {
            uint result;

            if (_is64Bit)
            {
                var del = ComHelpers.GetMethodDelegate <RawEnumCodeContextsOfPosition64>(_pActiveScriptDebug64, 5);
                result = del(_pActiveScriptDebug64, sourceContext.ToUInt64(), offset, length, out enumContexts);
            }
            else
            {
                var del = ComHelpers.GetMethodDelegate <RawEnumCodeContextsOfPosition32>(_pActiveScriptDebug32, 5);
                result = del(_pActiveScriptDebug32, sourceContext.ToUInt32(), offset, length, out enumContexts);
            }

            ComHelpers.HResult.Check(result);
        }
Esempio n. 28
0
        /// <summary>
        /// Checks a support of the JavaScript engine on the machine
        /// </summary>
        /// <param name="clsid">CLSID of JavaScript engine</param>
        /// <param name="isSupported">Flag indicating whether this JavaScript engine is supported</param>
        /// <param name="supportSynchronizer">Support synchronizer</param>
        /// <returns>Result of check (true - supports; false - does not support)</returns>
        protected static bool IsSupported(string clsid, ref bool?isSupported, ref object supportSynchronizer)
        {
            if (isSupported.HasValue)
            {
                return(isSupported.Value);
            }

            lock (supportSynchronizer)
            {
                if (isSupported.HasValue)
                {
                    return(isSupported.Value);
                }

                IntPtr pActiveScript = IntPtr.Zero;

                try
                {
                    pActiveScript = ComHelpers.CreateInstanceByClsid <IActiveScript>(clsid);
                    isSupported   = true;
                }
                catch (COMException e)
                {
                    if (e.ErrorCode == ComErrorCode.ClassNotRegistered)
                    {
                        isSupported = false;
                    }
                    else
                    {
                        isSupported = null;
                    }
                }
                catch
                {
                    isSupported = null;
                }
                finally
                {
                    ComHelpers.ReleaseAndEmpty(ref pActiveScript);
                }

                return(isSupported.HasValue && isSupported.Value);
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Constructs an instance of the Active Script wrapper
        /// </summary>
        /// <param name="clsid">CLSID of script engine</param>
        /// <param name="languageVersion">Version of script language</param>
        public ActiveScriptWrapper(string clsid, ScriptLanguageVersion languageVersion)
        {
            _is64Bit = Utils.Is64BitProcess();

            _pActiveScript = ComHelpers.CreateInstanceByClsid <IActiveScript>(clsid);
            if (_is64Bit)
            {
                _pActiveScriptParse64 = ComHelpers.QueryInterface <IActiveScriptParse64>(_pActiveScript);
                _pActiveScriptDebug64 = ComHelpers.QueryInterface <IActiveScriptDebug64>(_pActiveScript);
            }
            else
            {
                _pActiveScriptParse32 = ComHelpers.QueryInterface <IActiveScriptParse32>(_pActiveScript);
                _pActiveScriptDebug32 = ComHelpers.QueryInterface <IActiveScriptDebug32>(_pActiveScript);
            }
            _pActiveScriptGarbageCollector = ComHelpers.QueryInterfaceNoThrow <IActiveScriptGarbageCollector>(_pActiveScript);

            _activeScript = (IActiveScript)Marshal.GetObjectForIUnknown(_pActiveScript);
            if (_is64Bit)
            {
                _activeScriptParse64 = (IActiveScriptParse64)_activeScript;
            }
            else
            {
                _activeScriptParse32 = (IActiveScriptParse32)_activeScript;
            }
            _activeScriptGarbageCollector = _activeScript as IActiveScriptGarbageCollector;

            if (languageVersion != ScriptLanguageVersion.None)
            {
                var activeScriptProperty = _activeScript as IActiveScriptProperty;
                if (activeScriptProperty != null)
                {
                    object scriptLanguageVersion = (int)languageVersion;
                    uint   result = activeScriptProperty.SetProperty((uint)ScriptProperty.InvokeVersioning,
                                                                     IntPtr.Zero, ref scriptLanguageVersion);
                    if (result != (uint)ScriptHResult.Ok)
                    {
                        throw new JsEngineLoadException(
                                  string.Format(NetFrameworkStrings.Runtime_ActiveScriptLanguageVersionSelectionFailed, languageVersion));
                    }
                }
            }
        }
        private EnumMapping[] ExtractEnumMappingsFromCom()
        {
            var enumsManager = ComHelpers.GetProperty(globalContext.ComObject(), "Перечисления");
            var enumsMeta    = ComHelpers.GetProperty(globalContext.Metadata, "Перечисления");
            var enumsCount   = Call.Количество(enumsMeta);
            var result       = new List <EnumMapping>();

            for (var i = 0; i < enumsCount; i++)
            {
                var enumMeta       = Call.Получить(enumsMeta, i);
                var enumName       = Call.Имя(enumMeta);
                var enumManager    = ComHelpers.GetProperty(enumsManager, enumName);
                var enumValuesMeta = ComHelpers.GetProperty(enumMeta, "ЗначенияПеречисления");
                var valuesCount    = Call.Количество(enumValuesMeta);
                for (var j = 0; j < valuesCount; j++)
                {
                    var    enumValueMeta = Call.Получить(enumValuesMeta, j);
                    var    enumValueName = Call.Имя(enumValueMeta);
                    object enumValue     = null;
                    try
                    {
                        enumValue = ComHelpers.GetProperty(enumManager, enumValueName);
                    }
                    catch
                    {
                        //сраный 1С куда-то проебывает (DISP_E_MEMBERNOTFOUND)
                        //УсловияПримененияТребованийЗаконодательства.ЕстьТранспортныеСредства
                        //и только это значения этого енума, остальные на месте
                    }
                    if (enumValue != null)
                    {
                        var order = Convert.ToInt32(ComHelpers.Invoke(enumManager, "Индекс", enumValue));
                        result.Add(new EnumMapping
                        {
                            enumName      = enumName.ToLower(),
                            enumValueName = enumValueName.ToLower(),
                            orderIndex    = order
                        });
                    }
                }
            }
            return(result.ToArray());
        }