Example #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);
            }
        }
Example #2
0
        private Metadata CreateMetadata(ConfigurationName name)
        {
            var metadata = globalContext.FindMetaByName(name);

            if (name.Scope == ConfigurationScope.Константы)
            {
                return(new Metadata(name.Fullname, new[]
                {
                    new MetadataRequisite {
                        MaxLength = GetMaxLength(metadata.ComObject)
                    }
                }));
            }
            var descriptor = MetadataHelpers.GetDescriptor(name.Scope);
            var attributes = MetadataHelpers.GetAttributes(metadata.ComObject, descriptor).ToArray();
            var result     = new MetadataRequisite[attributes.Length];

            for (var i = 0; i < attributes.Length; i++)
            {
                var attr = attributes[i];
                result[i] = new MetadataRequisite
                {
                    Name      = Call.Имя(attr),
                    MaxLength = GetMaxLength(attr)
                };
            }
            return(new Metadata(name.Fullname, result));
        }
Example #3
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));
                }
            }
        }
Example #4
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));
        }
Example #5
0
        public Metadata GetMetadata(ConfigurationName configurationName)
        {
            Metadata result;

            if (!mappingSource.MetadataCache.TryGetValue(configurationName, out result))
            {
                result = CreateMetadata(configurationName);
                mappingSource.MetadataCache.TryAdd(configurationName, result);
            }
            return(result);
        }
Example #6
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);
        }
Example #7
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);
        }
Example #8
0
 public TypeRegistry(Assembly assembly)
 {
     Assembly = assembly;
     foreach (var x in assembly.GetTypes())
     {
         if (!x.IsClass && !x.IsEnum)
         {
             continue;
         }
         var name = ConfigurationName.GetOrNull(x);
         if (!name.HasValue)
         {
             continue;
         }
         typeMapping.Add(name.Value.Fullname, x);
     }
 }
Example #9
0
        private object ConvertParameterValue(object value)
        {
            switch (value)
            {
            case ConvertEnumCmd convertEnum:
                return(comObjectMapper.MapEnumTo1C(convertEnum.valueIndex, convertEnum.enumType));

            case ConvertUniqueIdentifierCmd convertUniqueIdentifier:
            {
                var name          = ConfigurationName.Get(convertUniqueIdentifier.entityType);
                var itemManager   = globalContext.GetManager(name);
                var guidComObject = comObjectMapper.MapGuidTo1C(convertUniqueIdentifier.id);
                return(ComHelpers.Invoke(itemManager, "ПолучитьСсылку", guidComObject));
            }

            default:
                throw new InvalidOperationException("assertion failure");
            }
        }
Example #10
0
        private object ConvertParameterValue(object value)
        {
            var convertEnum = value as ConvertEnumCmd;

            if (convertEnum != null)
            {
                return(comObjectMapper.MapEnumTo1C(convertEnum.valueIndex, convertEnum.enumType));
            }
            var convertUniqueIdentifier = value as ConvertUniqueIdentifierCmd;

            if (convertUniqueIdentifier != null)
            {
                var name          = ConfigurationName.Get(convertUniqueIdentifier.entityType);
                var itemManager   = globalContext.GetManager(name);
                var guidComObject = comObjectMapper.MapGuidTo1C(convertUniqueIdentifier.id);
                return(ComHelpers.Invoke(itemManager, "ѕолучить—сылку", guidComObject));
            }
            throw new InvalidOperationException("assertion failure");
        }
Example #11
0
        private object GetComObjectForEditing(ConfigurationName name, Abstract1CEntity entity)
        {
            var controller  = entity.Controller;
            var valueSource = controller.ValueSource;

            if (!controller.IsNew && name.HasReference)
            {
                return(ComHelpers.Invoke(valueSource.GetBackingStorage(), "ПолучитьОбъект"));
            }
            switch (name.Scope)
            {
            case ConfigurationScope.Справочники:
                object isGroup;
                var    needCreateFolder = controller.Changed != null &&
                                          controller.Changed.TryGetValue("ЭтоГруппа", out isGroup) &&
                                          (bool)isGroup;
                return(needCreateFolder
                        ? ComHelpers.Invoke(globalContext.GetManager(name), "CreateFolder")
                        : ComHelpers.Invoke(globalContext.GetManager(name), "CreateItem"));

            case ConfigurationScope.Документы:
                return(ComHelpers.Invoke(globalContext.GetManager(name), "CreateDocument"));

            case ConfigurationScope.егистрыСведений:
                return(valueSource != null && valueSource.Writable
                        ? valueSource.GetBackingStorage()
                        : ComHelpers.Invoke(globalContext.GetManager(name), "СоздатьМенеджерЗаписи"));

            case ConfigurationScope.ПланыСчетов:
            case ConfigurationScope.ПланыВидовХарактеристик:
                const string message = "creation of [{0}] is not implemented";
                throw new InvalidOperationException(string.Format(message, name.Scope));

            case ConfigurationScope.Перечисления:
            case ConfigurationScope.Константы:
                throw new InvalidOperationException("assertion failure");

            default:
                const string messageFormat = "invalid scope for [{0}]";
                throw new ArgumentOutOfRangeException(string.Format(messageFormat, name));
            }
        }
        private static TypeInfo?GetTypeInfoOrNull(GlobalContext globalContext, object typeDescriptor, object type)
        {
            var typeAsString = globalContext.String(type);

            if (typeAsString == "Число" || typeAsString == "Number")
            {
                var квалификаторыЧисла = ComHelpers.GetProperty(typeDescriptor, "КвалификаторыЧисла");
                var floatLength        = Convert.ToInt32(ComHelpers.GetProperty(квалификаторыЧисла, "РазрядностьДробнойЧасти"));
                var digits             = Convert.ToInt32(ComHelpers.GetProperty(квалификаторыЧисла, "Разрядность"));
                return(TypeInfo.Simple(floatLength == 0 ? (digits < 10 ? "int" : "long") : "decimal"));
            }
            if (typeAsString == "Строка" || typeAsString == "String")
            {
                var квалификаторыСтроки = ComHelpers.GetProperty(typeDescriptor, "КвалификаторыСтроки");
                var maxLength           = Call.IntProp(квалификаторыСтроки, "Длина");
                return(TypeInfo.Simple("string", maxLength == 0 ? (int?)null : maxLength));
            }
            if (typeAsString == "Хранилище значения" || typeAsString == "Value storage")
            {
                return(null);
            }
            string typeName;

            if (simpleTypesMap.TryGetValue(typeAsString, out typeName))
            {
                return(TypeInfo.Simple(typeName));
            }
            var comObject = GetMetaByType(globalContext, type);
            var fullName  = Call.ПолноеИмя(comObject);
            var name      = ConfigurationName.ParseOrNull(fullName);

            if (!name.HasValue)
            {
                return(null);
            }
            return(new TypeInfo {
                configurationItem = new ConfigurationItem(name.Value, comObject)
            });
        }
Example #13
0
        public object GetManager(ConfigurationName name)
        {
            var scopeManager = Get(name.Scope.ToString());

            return(ComHelpers.GetProperty(scopeManager, name.Name));
        }
Example #14
0
        private void Save(Abstract1CEntity source, object comObject, Stack <object> pending)
        {
            if (!source.Controller.IsDirty)
            {
                return;
            }
            if (pending.Contains(source))
            {
                const string messageFormat = "cycle detected for entity type [{0}]: [{1}]";
                throw new InvalidOperationException(string.Format(messageFormat, source.GetType().FormatName(),
                                                                  pending
                                                                  .Reverse()
                                                                  .Select(x => x is Abstract1CEntity ? x.GetType().FormatName() : x)
                                                                  .JoinStrings("->")));
            }
            pending.Push(source);
            Metadata          metadata;
            ConfigurationName?configurationName;

            if (comObject == null)
            {
                configurationName = ConfigurationName.Get(source.GetType());
                metadata          = metadataAccessor.GetMetadata(configurationName.Value);
                comObject         = GetComObjectForEditing(configurationName.Value, source);
            }
            else
            {
                metadata          = null;
                configurationName = null;
            }
            bool?newPostingValue = null;
            var  changeLog       = source.Controller.Changed;

            if (changeLog != null)
            {
                foreach (var p in changeLog)
                {
                    var value = p.Value;
                    if (p.Key == "Проведен" && configurationName.HasValue &&
                        configurationName.Value.Scope == ConfigurationScope.Документы)
                    {
                        newPostingValue = (bool?)value;
                        continue;
                    }
                    pending.Push(p.Key);
                    SaveProperty(p.Key, p.Value, comObject, pending, metadata);
                    pending.Pop();
                }
            }
            var needPatchWithOriginalValues = configurationName.HasValue &&
                                              configurationName.Value.Scope == ConfigurationScope.егистрыСведений &&
                                              source.Controller.ValueSource != null &&
                                              !source.Controller.ValueSource.Writable &&
                                              changeLog != null;

            if (needPatchWithOriginalValues)
            {
                var backingStorage = source.Controller.ValueSource.GetBackingStorage();
                foreach (var r in metadata.Requisites)
                {
                    if (!changeLog.ContainsKey(r.Name))
                    {
                        pending.Push(r);
                        var value = ComHelpers.GetProperty(backingStorage, r.Name);
                        SaveProperty(r.Name, value, comObject, pending, metadata);
                        pending.Pop();
                    }
                }
            }
            object valueSourceComObject;

            if (configurationName.HasValue)
            {
                if (!newPostingValue.HasValue && configurationName.Value.Scope == ConfigurationScope.Документы)
                {
                    var oldPostingValue = Convert.ToBoolean(ComHelpers.GetProperty(comObject, "Проведен"));
                    if (oldPostingValue)
                    {
                        Write(comObject, configurationName.Value, false);
                        newPostingValue = true;
                    }
                }
                Write(comObject, configurationName.Value, newPostingValue);
                switch (configurationName.Value.Scope)
                {
                case ConfigurationScope.Справочники:
                    UpdateIfExists(source, comObject, "Код");
                    break;

                case ConfigurationScope.Документы:
                    UpdateIfExists(source, comObject, "Номер");
                    break;
                }
                if (configurationName.Value.HasReference)
                {
                    valueSourceComObject = ComHelpers.GetProperty(comObject, "Ссылка");
                    UpdateId(valueSourceComObject, source, configurationName.Value);
                }
                else
                {
                    valueSourceComObject = comObject;
                }
            }
            else
            {
                UpdateIfExists(source, comObject, "НомерСтроки");
                valueSourceComObject = comObject;
            }
            var valueSourceIsWriteable = configurationName.HasValue &&
                                         configurationName.Value.Scope == ConfigurationScope.егистрыСведений;

            source.Controller.ResetDirty(new ComValueSource(valueSourceComObject, comObjectMapper,
                                                            valueSourceIsWriteable));
            pending.Pop();
        }
Example #15
0
        private InMemoryEntity Save(Abstract1CEntity entity, bool isTableSection)
        {
            if (entity == null)
            {
                return(null);
            }
            var changed = entity.Controller.Changed;

            if (changed != null)
            {
                var keys = changed.Keys.ToArray();
                foreach (var k in keys)
                {
                    var abstract1CEntity = changed[k] as Abstract1CEntity;
                    if (abstract1CEntity != null)
                    {
                        changed[k] = Save(abstract1CEntity, false);
                        continue;
                    }
                    var list = changed[k] as IList;
                    if (list != null)
                    {
                        changed[k] = ConvertList(list);
                        continue;
                    }
                    var syncList = changed[k] as SyncList;
                    if (syncList != null)
                    {
                        changed[k] = ConvertList(syncList.Current);
                    }
                }
            }
            InMemoryEntity inMemoryEntity;

            if (!entity.Controller.IsNew)
            {
                var inmemoryEntityRevision = (InMemoryEntityRevision)entity.Controller.ValueSource;
                inMemoryEntity = inmemoryEntityRevision.inMemoryEntity;
                if (changed != null)
                {
                    inMemoryEntity.revision = new InMemoryEntityRevision(inMemoryEntity, inmemoryEntityRevision, changed);
                    Collection(entity.GetType()).revision++;
                }
            }
            else
            {
                if (changed == null)
                {
                    changed = new Dictionary <string, object>();
                }
                inMemoryEntity = new InMemoryEntity();
                var revision = new InMemoryEntityRevision(inMemoryEntity, null, changed);
                inMemoryEntity.entityType = entity.GetType();
                inMemoryEntity.revision   = revision;
                if (!isTableSection)
                {
                    var configurationName = ConfigurationName.Get(entity.GetType());
                    if (configurationName.Scope == ConfigurationScope.Справочники)
                    {
                        AssignNewGuid(entity, changed, "Код");
                    }
                    else if (configurationName.Scope == ConfigurationScope.Документы)
                    {
                        AssignNewGuid(entity, changed, "Номер");
                    }
                    if (entity.Controller.IsNew && configurationName.HasReference)
                    {
                        var idProperty = entity.GetType().GetProperty(EntityHelpers.idPropertyName);
                        if (idProperty == null)
                        {
                            throw new InvalidOperationException("assertion failure");
                        }
                        AssignValue(entity, changed, idProperty, Guid.NewGuid());
                    }
                    var inMemoryEntityCollection = Collection(entity.GetType());
                    inMemoryEntityCollection.revision++;
                    inMemoryEntityCollection.list.Add(inMemoryEntity);
                }
            }
            entity.Controller.ResetDirty(inMemoryEntity.revision);
            return(inMemoryEntity);
        }
Example #16
0
 public object MapFrom1C(object source, Type type)
 {
     if (source == null || source == DBNull.Value)
     {
         return(null);
     }
     if (type == typeof(object))
     {
         if (source is MarshalByRefObject)
         {
             var typeName = GetFullName(source);
             type = mappingSource.TypeRegistry.GetType(typeName);
         }
         else
         {
             type = source.GetType();
         }
     }
     type = Nullable.GetUnderlyingType(type) ?? type;
     if (type == typeof(DateTime))
     {
         var dateTime = (DateTime)source;
         return(dateTime == nullDateTime ? null : source);
     }
     if (type == typeof(Guid))
     {
         var guid = Guid.Parse(globalContext.String(source));
         return(guid == Guid.Empty ? (object)null : guid);
     }
     if (type.IsEnum)
     {
         return(Call.IsEmpty(source) ? null : MapEnumFrom1C(type, source));
     }
     if (type == typeof(Type))
     {
         return(ConvertType(source));
     }
     if (type == typeof(Type[]))
     {
         var typesObject = ComHelpers.Invoke(source, "Типы");
         var typesCount  = Call.Количество(typesObject);
         var result      = new Type[typesCount];
         for (var i = 0; i < result.Length; i++)
         {
             var typeObject = Call.Получить(typesObject, i);
             result[i] = ConvertType(typeObject);
         }
         return(result);
     }
     if (typeof(Abstract1CEntity).IsAssignableFrom(type))
     {
         var configurationName = ConfigurationName.GetOrNull(type);
         var isEmpty           = configurationName.HasValue &&
                                 configurationName.Value.HasReference &&
                                 Call.IsEmpty(source);
         if (isEmpty)
         {
             return(null);
         }
         var result = (Abstract1CEntity)FormatterServices.GetUninitializedObject(type);
         result.Controller = new EntityController(new ComValueSource(source, this, false));
         return(result);
     }
     if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>))
     {
         var itemType = type.GetGenericArguments()[0];
         if (!typeof(Abstract1CEntity).IsAssignableFrom(itemType))
         {
             throw new InvalidOperationException("assertion failure");
         }
         var itemsCount = Call.Количество(source);
         var list       = ListFactory.Create(itemType, null, itemsCount);
         for (var i = 0; i < itemsCount; ++i)
         {
             list.Add(MapFrom1C(Call.Получить(source, i), itemType));
         }
         return(list);
     }
     return(source is IConvertible?Convert.ChangeType(source, type) : source);
 }