Exemplo n.º 1
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (this.DataContext is KeyProperty)
            {
                KeyProperty prop = this.DataContext as KeyProperty;

                ViewEditKeyProperty editWindow = new ViewEditKeyProperty(prop);
                editWindow.ShowDialog();
                prop = editWindow.EditProperty;

                prop.OnPropertyChanged(new EventArgs());

                //update all of the textboxes
                var expression = txtInstanceName.GetBindingExpression(Run.TextProperty);
                if (expression != null)
                {
                    expression.UpdateTarget();
                }
                expression = txtGroup.GetBindingExpression(Run.TextProperty);
                if (expression != null)
                {
                    expression.UpdateTarget();
                }
                expression = txtType.GetBindingExpression(Run.TextProperty);
                if (expression != null)
                {
                    expression.UpdateTarget();
                }
                expression = txtInstanceId.GetBindingExpression(Run.TextProperty);
                if (expression != null)
                {
                    expression.UpdateTarget();
                }
            }
        }
Exemplo n.º 2
0
        internal static byte[] GetKeyProperty(SafeCspKeyHandle keyHandle, KeyProperty property)
        {
            Contract.Assert(keyHandle != null && !keyHandle.IsInvalid, "keyHandle != null && !keyHandle.IsInvalid");

            int bufferSize = 0;

            byte[] buffer = null;

            // Figure out how big of a buffer we need to hold the property
            if (!UnsafeNativeMethods.CryptGetKeyParam(keyHandle, property, buffer, ref bufferSize, 0))
            {
                int errorCode = Marshal.GetLastWin32Error();
                if (errorCode != (int)ErrorCode.MoreData)
                {
                    throw new CryptographicException(errorCode);
                }
            }

            // Now get the property bytes directly
            buffer = new byte[bufferSize];
            if (!UnsafeNativeMethods.CryptGetKeyParam(keyHandle, property, buffer, ref bufferSize, 0))
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }

            return(buffer);
        }
Exemplo n.º 3
0
 public static void SetCustomKey(VirtualKey oldKey, KeyProperty newVal)
 {
     if (Instance._customKeyMap == null)
     {
         Instance._customKeyMap = new KeyMap();
     }
     Instance._customKeyMap.SetKeyBind(oldKey, newVal);
 }
 public DecalImageModel()
 {
     ID             = new KeyProperty();
     DecalID        = new KeyProperty();
     AspectRatio    = new FloatProperty();
     Color1Property = new Vector4Property();
     Color2Property = new Vector4Property();
     Color3Property = new Vector4Property();
     Color4Property = new Vector4Property();
 }
Exemplo n.º 5
0
        public ViewEditKeyProperty(KeyProperty prop)
        {
            InitializeComponent();

            EditProperty = prop;

            txtTypeId.Text         = EditProperty.TypeId.ToHex();
            txtGroupContainer.Text = EditProperty.GroupContainer.ToHex();
            txtInstanceId.Text     = EditProperty.InstanceId.ToHex();
        }
Exemplo n.º 6
0
 private void UserControl_DataContextChanged_1(object sender, DependencyPropertyChangedEventArgs e)
 {
     if (this.DataContext is KeyProperty)
     {
         KeyProperty prop = this.DataContext as KeyProperty;
         indexes = DatabaseManager.Instance.Indices.FindAll(i => i.InstanceId == prop.InstanceId &&
                                                            (prop.TypeId == 0 || i.TypeId == prop.TypeId) &&
                                                            (prop.GroupContainer == 0 || i.GroupContainer == prop.GroupContainer));
         resultsCount.Text = String.Format("({0})", indexes.Count);
     }
 }
Exemplo n.º 7
0
        public async Task <TEntity> Update(TEntity entity)
        {
            int     id      = (int)KeyProperty.GetValue(entity);
            TEntity current = await FirstOrDefault(stored => stored.Id, id);

            if (current == null)
            {
                throw new NotFoundException("entity with such id");
            }

            IDictionary <string, object> changedColumns = new Dictionary <string, object>();

            foreach (PropertyInfo property in PropertiesExceptKey)
            {
                object storedValue  = property.GetValue(current);
                object updatedValue = property.GetValue(entity);

                if (storedValue.Equals(updatedValue))
                {
                    continue;
                }

                changedColumns.Add(GetColumnByProperty(property), updatedValue);
            }

            if (changedColumns.Count == 0)
            {
                return(current);
            }

            IEnumerable <string> changeQueryItems = changedColumns.Select(change => $"{change.Key} = @{change.Key}");
            string setString = string.Join(", ", changeQueryItems);

            string updateText = $"UPDATE {TableName}\n" +
                                $"SET {setString}\n" +
                                $"WHERE {KeyColumnName} = {id};";

            using (SqlConnection connection = new SqlConnection(ConnectionString))
                using (SqlCommand updater = new SqlCommand(updateText, connection))
                {
                    foreach (KeyValuePair <string, object> changedColumn in changedColumns)
                    {
                        updater.Parameters.AddWithValue($"@{changedColumn.Key}", changedColumn.Value);
                    }

                    connection.Open();
                    await updater.ExecuteNonQueryAsync();
                }

            return(await FirstOrDefault(updated => updated.Id, id));
        }
Exemplo n.º 8
0
        private void CreateUnitModel()
        {
            if (UnitFileEntry.LOD1 != null)
            {
                //get the 3d model to show in this scene
                KeyProperty   lod1  = UnitFileEntry.LOD1;
                DatabaseIndex index = DatabaseManager.Instance.Indices.Find(k => k.InstanceId == lod1.InstanceId && k.GroupContainer == lod1.GroupContainer && k.TypeId == lod1.TypeId);

                if (index != null)
                {
                    RW4Model _rw4model = new RW4Model();
                    using (Stream stream = new MemoryStream(index.GetIndexData(true)))
                    {
                        _rw4model.Read(stream);
                    }

                    RW4Section section = _rw4model.Sections.First(s => s.TypeCode == SectionTypeCodes.Mesh);
                    if (section != null)
                    {
                        SporeMaster.RenderWare4.RW4Mesh mesh = section.obj as SporeMaster.RenderWare4.RW4Mesh;

                        meshMain.TriangleIndices.Clear();
                        meshMain.Positions.Clear();
                        meshMain.Normals.Clear();
                        meshMain.TextureCoordinates.Clear();

                        try
                        {
                            foreach (var v in mesh.vertices.vertices)
                            {
                                meshMain.Positions.Add(new Point3D(v.Position.X, v.Position.Y, v.Position.Z));
                            }
                            foreach (var t in mesh.triangles.triangles)
                            {
                                meshMain.TriangleIndices.Add((int)t.i);
                                meshMain.TriangleIndices.Add((int)t.j);
                                meshMain.TriangleIndices.Add((int)t.k);
                            }
                        }
                        catch { }
                    }

                    if (UnitFileEntry.ModelSize != null)
                    {
                        ScaleTransform3D scaleTransform = new ScaleTransform3D(UnitFileEntry.ModelSize.Value, UnitFileEntry.ModelSize.Value, UnitFileEntry.ModelSize.Value);
                        modelMain.Transform = scaleTransform;
                    }
                }
            }
        }
Exemplo n.º 9
0
        private void mnuSearch_Click(object sender, RoutedEventArgs e)
        {
            Window     owner = Window.GetWindow(this);
            MainWindow main  = null;

            if (owner is MainWindow)
            {
                main = owner as MainWindow;
            }
            else if (owner is ViewWindow)
            {
                main = ((ViewWindow)owner).Main;
            }
            KeyProperty prop = this.DataContext as KeyProperty;

            SimCityPak.Views.ViewSearchProperties res = new SimCityPak.Views.ViewSearchProperties(main, prop.InstanceId.ToHex(), null, true);
            res.Show();
        }
Exemplo n.º 10
0
 public string TryGetObjectKeyString(object target)
 {
     if (HasKeyProperty)
     {
         var value = KeyProperty.GetValueForObject(target);
         if (value == null)
         {
             return(null);
         }
         else
         {
             return(value.ToString());
         }
     }
     else
     {
         return(null);
     }
 }
Exemplo n.º 11
0
    public override int GetHashCode()
    {
        unchecked
        {
            var hashCode = EnumTypeFullyQualified.GetHashCode();
            hashCode = (hashCode * 397) ^ IsValidatable.GetHashCode();
            hashCode = (hashCode * 397) ^ HasCreateInvalidImplementation.GetHashCode();
            hashCode = (hashCode * 397) ^ IsReferenceType.GetHashCode();
            hashCode = (hashCode * 397) ^ IsAbstract.GetHashCode();
            hashCode = (hashCode * 397) ^ AttributeInfo.GetHashCode();
            hashCode = (hashCode * 397) ^ KeyProperty.GetHashCode();
            hashCode = (hashCode * 397) ^ (BaseEnum?.GetHashCode() ?? 0);
            hashCode = (hashCode * 397) ^ Settings.GetHashCode();
            hashCode = (hashCode * 397) ^ ItemNames.ComputeHashCode();
            hashCode = (hashCode * 397) ^ AssignableInstanceFieldsAndProperties.ComputeHashCode();
            hashCode = (hashCode * 397) ^ FullyQualifiedDerivedTypes.ComputeHashCode();

            return(hashCode);
        }
    }
Exemplo n.º 12
0
    public bool Equals(EnumSourceGeneratorState?other)
    {
        if (ReferenceEquals(null, other))
        {
            return(false);
        }
        if (ReferenceEquals(this, other))
        {
            return(true);
        }

        return(EnumTypeFullyQualified == other.EnumTypeFullyQualified &&
               IsValidatable == other.IsValidatable &&
               HasCreateInvalidImplementation == other.HasCreateInvalidImplementation &&
               IsReferenceType == other.IsReferenceType &&
               IsAbstract == other.IsAbstract &&
               AttributeInfo.Equals(other.AttributeInfo) &&
               KeyProperty.Equals(other.KeyProperty) &&
               Equals(BaseEnum, other.BaseEnum) &&
               Settings.Equals(other.Settings) &&
               ItemNames.EqualsTo(other.ItemNames) &&
               AssignableInstanceFieldsAndProperties.EqualsTo(other.AssignableInstanceFieldsAndProperties) &&
               FullyQualifiedDerivedTypes.EqualsTo(other.FullyQualifiedDerivedTypes));
    }
Exemplo n.º 13
0
        public String CreateContact(Guid contact_ID, Contact contact)
        {
            Guid contactid = contact_ID;

            try
            {
                contact cont = new contact();


                CrmConnection crmc       = new CrmConnection("Crm");
                CrmService    crmService = crmc.CreateCrmService();

                if (contact_ID == new Guid("{00000000-0000-0000-0000-000000000000}"))
                {
                    contactid = crmService.Create(cont);
                }

                // Создаем экземпляр динамческого объекта и указываем его имя
                DynamicEntity myDEUpdate = new DynamicEntity();
                myDEUpdate.Name = "contact";


                // Создаем KeyProperty для хранения GUID’а обновляемой записи
                KeyProperty myContactGuid = new KeyProperty();
                myContactGuid.Name = "contactid";

                // Указываем GUID обновляемой записи
                Key myContactKey = new Key();
                myContactKey.Value  = contactid;
                myContactGuid.Value = myContactKey;
                myDEUpdate.Properties.Add(myContactGuid);



                if (contact.address1_city != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("address1_city", contact.address1_city));
                }

                if (contact.address1_country != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("address1_country", contact.address1_country));
                }

                if (contact.address1_line1 != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("address1_line1", contact.address1_line1));
                }

                if (contact.address1_name != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("address1_name", contact.address1_name));
                }

                if (contact.address1_postalcode != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("address1_postalcode", contact.address1_postalcode));
                }

                if (contact.emailaddress1 != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("emailaddress1", contact.emailaddress1));
                }

                if (contact.firstname != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("firstname", contact.firstname));
                }

                if (contact.lastname != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("lastname", contact.lastname));
                }

                if (contact.middlename != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("middlename", contact.middlename));
                }

                if (contact.mobilephone != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("mobilephone", contact.mobilephone));
                }

                if (contact.salutation != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("salutation", contact.salutation));
                }

                //Кем выдан
                if (contact.new_giveoutby != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("new_giveoutby", contact.new_giveoutby));
                }

                //Номер
                if (contact.new_nomer != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("new_nomer", contact.new_nomer));
                }

                //Серия
                if (contact.new_seria != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("new_seria", contact.new_seria));
                }



                //Пол
                if (contact.gendercode != 0)
                {
                    myDEUpdate.Properties.Add(new PicklistProperty("gendercode", new Picklist(contact.gendercode)));
                }

                //Гражданство
                if (contact.new_nationality != 0)
                {
                    myDEUpdate.Properties.Add(new PicklistProperty("new_nationality", new Picklist(contact.new_nationality)));
                }

                //Тип ФЛ
                if (contact.new_type != 0)
                {
                    myDEUpdate.Properties.Add(new PicklistProperty("new_type", new Picklist(contact.new_type)));
                }

                //Семейное положение
                if (contact.familystatuscode != 0)
                {
                    myDEUpdate.Properties.Add(new PicklistProperty("familystatuscode", new Picklist(contact.familystatuscode)));
                }


                //День рождения
                if (contact.birthdate != null)
                {
                    myDEUpdate.Properties.Add(new CrmDateTimeProperty("birthdate", CrmDateTime.FromUser(DateTime.ParseExact(contact.birthdate, "yyyyMMddHHmmss", CultureInfo.InvariantCulture))));
                }

                //Посетил открытый урок
                if (contact.new_openles != null)
                {
                    myDEUpdate.Properties.Add(new CrmDateTimeProperty("new_openles", CrmDateTime.FromUser(DateTime.ParseExact(contact.new_openles, "yyyyMMddHHmmss", CultureInfo.InvariantCulture))));
                }

                //Дата выдачи
                if (contact.new_dategiveout != null)
                {
                    myDEUpdate.Properties.Add(new CrmDateTimeProperty("new_dategiveout", CrmDateTime.FromUser(DateTime.ParseExact(contact.new_dategiveout, "yyyyMMddHHmmss", CultureInfo.InvariantCulture))));
                }


                crmService.Update(myDEUpdate);


                //поиск контакта для переназначения ответственного, если таковой меняется
                Owner ownerID = new Owner();
                if (contact_ID != new Guid("{00000000-0000-0000-0000-000000000000}"))
                {
                    try
                    {
                        string ln = ""; //фамилия
                        BusinessEntityCollection fcontact = searchContact(contact_ID.ToString());
                        foreach (DynamicEntity cont1 in fcontact.BusinessEntities)
                        {
                            ln = cont1["lastname"].ToString();
                            if (cont1.Properties.Contains("ownerid"))
                            {
                                ownerID = (Owner)cont1["ownerid"];
                            }
                        }

                        logger.Info($"Нашли контакт {ln}. ownerid={ownerID.Value.ToString()}");
                    }
                    catch (Exception ex)
                    {
                        logger.Error($"Ошибка: {ex.ToString()}");
                    }
                }

                if (contact.ownerid != new Guid("{00000000-0000-0000-0000-000000000000}"))
                {
                    if (ownerID.Value != contact.ownerid)
                    {
                        TargetOwnedContact target   = new TargetOwnedContact();
                        SecurityPrincipal  assignee = new SecurityPrincipal();
                        assignee.Type        = SecurityPrincipalType.User;
                        assignee.PrincipalId = contact.ownerid;
                        target.EntityId      = contactid;

                        AssignRequest assign = new AssignRequest();
                        assign.Assignee = assignee;
                        assign.Target   = target;
                        AssignResponse res = (AssignResponse)crmService.Execute(assign);
                    }
                }
                return(contactid.ToString());
            }
            catch (SoapException ex)
            {
                logger.Error($"Ошибка: {ex.Detail.InnerText}");
                return(ex.Detail.InnerText);
            }
        }
Exemplo n.º 14
0
        private DataDictionary CreateDataDictionary()
        {
            try
            {

                DataObject _dataObject = null;
                KeyProperty _keyproperties = new KeyProperty();
                DataProperty _dataproperties = new DataProperty();
                DataDictionary _dataDictionary = new DataDictionary();

                foreach (var dic in _objectyDictionary)
                {
                    string objectName = dic.Key;
                    bool isFirstRecored = false;
                    string url = _schemaUrl.Replace("{resource}", dic.Key);
                    string json = GetJsonResponseFrom(url);

                    JObject schemaObject = JObject.Parse(json);

                    foreach (JProperty propery in schemaObject.Properties())
                    {
                        string propertyName = propery.Name;
                        if (propertyName != "links")
                        {
                            if (!isFirstRecored)
                            {
                                isFirstRecored = true;
                                _dataObject = new DataObject();

                                _dataObject.objectName = objectName;
                                _dataObject.tableName = objectName;
                                _dataObject.keyDelimeter = _keyDelimiter;

                            }

                            _dataproperties = new DataProperty();
                            _dataproperties.propertyName = propertyName;
                            _dataproperties.columnName = propertyName;
                            _dataproperties.keyType = KeyType.unassigned;
                            _dataproperties.isNullable = true;

                            foreach(JProperty p in ((JObject)propery.Value).Properties())
                            {
                                if (p.Name == "type")
                                {
                                    _dataproperties.dataType = ResolveDataType(p.Value.ToString());
                                }
                                else if(p.Name == "size")
                                {
                                    if (p.Value.ToString() == "string")
                                        _dataproperties.dataLength = Convert.ToInt32(p.Value.ToString());
                                }
                            }

                            _dataObject.dataProperties.Add(_dataproperties);
                        }
                    }

                    foreach (JProperty propery in schemaObject.Properties())
                    {
                        if (propery.Name == "links")
                        {
                            _selfUrl.Add(objectName, schemaObject["links"]["self"].Value<string>());

                            JArray keyList = (JArray)schemaObject["links"]["key"];
                            for (int i = 0; i < keyList.Count; i++)
                            {
                                DataProperty property = _dataObject.dataProperties.Single<DataProperty>(x => x.propertyName == keyList[i].ToString());
                                property.keyType =  KeyType.assigned;
                                property.isNullable = false;

                                _dataObject.keyProperties.Add(new KeyProperty() { keyPropertyName = property.propertyName });
                            }

                        }
                    }

                    _dataDictionary.dataObjects.Add(_dataObject);
                }

                return _dataDictionary;
            }
            catch (Exception ex)
            {
                _logger.Error("Error in loading data dictionary : " + ex);
                throw ex;
            }
        }
Exemplo n.º 15
0
        public Dictionary <uint, Property> GetParentProperties(Dictionary <uint, Property> returnProperties, Dictionary <uint, Property> parentProperties)
        {
            if (returnProperties == null)
            {
                returnProperties = new Dictionary <uint, Property>();
            }

            //add keys that didn't exist yet
            foreach (uint index in parentProperties.Keys)
            {
                if (!returnProperties.ContainsKey(index) && index != 0x00B2CCCB)
                {
                    //This property specifies behavior bundles to exclude - instead of adding this property, remove all the bundles from the appropriate arrays

                    returnProperties.Add(index, parentProperties[index]);
                }
            }

            if (parentProperties.ContainsKey(0x00B2CCCB))
            {
                Property    parentProperty      = parentProperties[0x00B2CCCB];
                KeyProperty parentPropertyValue = parentProperty as KeyProperty;

                //search the currently opened package for this type/instance group id. if it doesn't exist, find it in the default simcity packages

                DatabaseIndex parentIndex = null;
                if (DatabaseManager.Instance.Indices.Exists(i => i.InstanceId == parentPropertyValue.InstanceId && i.TypeId == parentPropertyValue.TypeId && i.GroupContainer == parentPropertyValue.GroupContainer))
                {
                    parentIndex = DatabaseManager.Instance.Indices.First(i => i.InstanceId == parentPropertyValue.InstanceId && i.TypeId == parentPropertyValue.TypeId && i.GroupContainer == parentPropertyValue.GroupContainer);
                }
                else
                {
                    string        folderEcoGamePath = Properties.Settings.Default.SimCityFolder + @"\SimCityUserData\EcoGame\";
                    DirectoryInfo folderEcoGame     = new DirectoryInfo(folderEcoGamePath);

                    //search the simcity data packages for this type/instance group id. if it doesn't exist, find it in the default simcity packages
                    FileInfo[]         scriptsFiles   = folderEcoGame.GetFiles("SimCity-Scripts_*.package", SearchOption.TopDirectoryOnly);
                    FileInfo           scriptsFile    = scriptsFiles.First(sf => sf.LastWriteTime == scriptsFiles.Max(sf2 => sf2.LastWriteTime));
                    DatabasePackedFile ScriptsPackage = DatabasePackedFile.LoadFromFile(scriptsFile.FullName);

                    parentIndex = ScriptsPackage.Indices.FirstOrDefault(i => i.InstanceId == parentPropertyValue.InstanceId && i.TypeId == parentPropertyValue.TypeId && i.GroupContainer == parentPropertyValue.GroupContainer);
                }

                // if(parentIndex != null)
                // {
                byte[] data = parentIndex.GetIndexData(true);

                using (Stream s = new MemoryStream(data, 0, data.Length))
                {
                    PropertyFile propertyFile = new PropertyFile();
                    propertyFile.Read(s);

                    return(GetParentProperties(returnProperties, propertyFile.Values));
                }



                throw new Exception("Inheritance not found!");
                return(returnProperties);
            }
            else
            {
                return(returnProperties);
            }
        }
Exemplo n.º 16
0
 get => (string)GetValue(KeyProperty); set => SetValue(KeyProperty, value);
Exemplo n.º 17
0
 public EFCoreRepository(TDbContext dbContext)
 {
     DbContext  = dbContext;
     _keySetter = KeyProperty.GetSetter();
 }
Exemplo n.º 18
0
 get => (Key)GetValue(KeyProperty); set => SetValue(KeyProperty, value);
Exemplo n.º 19
0
        private void mnuCopy_Click(object sender, RoutedEventArgs e)
        {
            //check if current index is a valid menu item
            if (this.DataContext.GetType() == typeof(DatabaseIndexData))
            {
                DatabaseIndexData menuItemIndex = (DatabaseIndexData)this.DataContext;
                menuItemIndex.Index.IsModified = true;
                if (menuItemIndex.Index.InstanceType == (uint)PropertyFileTypeIds.Menu2)
                {
                    SaveFileDialog dialog = new SaveFileDialog();
                    if (dialog.ShowDialog().GetValueOrDefault(false))
                    {
                        List <DatabaseIndex> indices = new List <DatabaseIndex>();

                        menuItemIndex.Index.ModifiedInstanceId = TGIRandomGenerator.GetNext();
                        indices.Add(menuItemIndex.Index);

                        PropertyFile menuFile = new PropertyFile(menuItemIndex.Index);

                        #region Extract Icon

                        if (menuFile.Values.ContainsKey(PropertyConstants.menuIcon))
                        {
                            KeyProperty   iconProperty = (KeyProperty)menuFile.Values[PropertyConstants.menuIcon];
                            DatabaseIndex iconIndex    = DatabaseIndex.FindIndex(iconProperty.TypeId, null, null, iconProperty.InstanceId, true, false);

                            iconIndex.ModifiedInstanceId = TGIRandomGenerator.GetNext();
                            indices.Add(iconIndex);

                            iconProperty.InstanceId          = iconIndex.ModifiedInstanceId.Value;
                            menuItemIndex.Index.ModifiedData = new ModifiedPropertyFile()
                            {
                                PropertyFile = menuFile
                            };

                            menuFile.Values[PropertyConstants.menuIcon] = iconProperty;
                        }

                        #endregion

                        #region Extract Marquee Image

                        if (menuFile.Values.ContainsKey(PropertyConstants.menuMarqueeImage))
                        {
                            KeyProperty   marqueeProperty = (KeyProperty)menuFile.Values[PropertyConstants.menuMarqueeImage];
                            DatabaseIndex marqueeIndex    = DatabaseIndex.FindIndex(marqueeProperty.TypeId, null, null, marqueeProperty.InstanceId, true, false);

                            marqueeIndex.ModifiedInstanceId = TGIRandomGenerator.GetNext();
                            indices.Add(marqueeIndex);

                            marqueeProperty.InstanceId       = marqueeIndex.ModifiedInstanceId.Value;
                            menuItemIndex.Index.ModifiedData = new ModifiedPropertyFile()
                            {
                                PropertyFile = menuFile
                            };

                            menuFile.Values[PropertyConstants.menuMarqueeImage] = marqueeProperty;
                        }

                        #endregion

                        #region Extract Ecogame Unit

                        if (menuFile.Values.ContainsKey(PropertyConstants.menuUnit))
                        {
                            KeyProperty   unitProperty = (KeyProperty)menuFile.Values[PropertyConstants.menuUnit];
                            DatabaseIndex unitIndex    = DatabaseIndex.FindIndex((uint)TypeIds.PropertyFile, null, 0xe0, unitProperty.InstanceId, false, true);

                            PropertyFile unitFile = new PropertyFile(unitIndex);
                            unitFile.FlattenParentInheritance();

                            #region Extract Unit Display

                            if (unitFile.Values.ContainsKey(PropertyConstants.ecoGameUnitDisplayModel))
                            {
                                KeyProperty   unitDisplayProperty = (KeyProperty)unitFile.Values[PropertyConstants.ecoGameUnitDisplayModel];
                                DatabaseIndex unitDisplayIndex    = DatabaseIndex.FindIndex((uint)TypeIds.PropertyFile, null, 0xe1, unitDisplayProperty.InstanceId, false, true);

                                unitDisplayIndex.ModifiedInstanceId = TGIRandomGenerator.GetNext();
                                unitDisplayProperty.InstanceId      = unitDisplayIndex.ModifiedInstanceId.Value;

                                unitFile.Values[PropertyConstants.ecoGameUnitDisplayModel] = unitDisplayProperty;

                                PropertyFile unitDisplayFile = new PropertyFile(unitDisplayIndex);

                                #region Extract LODs

                                if (unitDisplayFile.Values.ContainsKey(PropertyConstants.UnitLOD1))
                                {
                                    KeyProperty   LOD1Property = (KeyProperty)unitDisplayFile.Values[PropertyConstants.UnitLOD1];
                                    DatabaseIndex LOD1Index    = DatabaseIndex.FindIndex(LOD1Property.TypeId, null, null, LOD1Property.InstanceId, true, false);
                                    LOD1Index.ModifiedInstanceId = TGIRandomGenerator.GetNext();
                                    indices.Add(LOD1Index);
                                    LOD1Property.InstanceId = LOD1Index.ModifiedInstanceId.Value;
                                    unitDisplayFile.Values[PropertyConstants.UnitLOD1] = LOD1Property;
                                }

                                if (unitDisplayFile.Values.ContainsKey(PropertyConstants.UnitLOD2))
                                {
                                    KeyProperty   LOD2Property = (KeyProperty)unitDisplayFile.Values[PropertyConstants.UnitLOD2];
                                    DatabaseIndex LOD2Index    = DatabaseIndex.FindIndex(LOD2Property.TypeId, null, null, LOD2Property.InstanceId, true, false);
                                    LOD2Index.ModifiedInstanceId = TGIRandomGenerator.GetNext();
                                    indices.Add(LOD2Index);
                                    LOD2Property.InstanceId = LOD2Index.ModifiedInstanceId.Value;
                                    unitDisplayFile.Values[PropertyConstants.UnitLOD2] = LOD2Property;
                                }

                                if (unitDisplayFile.Values.ContainsKey(PropertyConstants.UnitLOD3))
                                {
                                    KeyProperty   LOD3Property = (KeyProperty)unitDisplayFile.Values[PropertyConstants.UnitLOD3];
                                    DatabaseIndex LOD3Index    = DatabaseIndex.FindIndex(LOD3Property.TypeId, null, null, LOD3Property.InstanceId, true, false);
                                    LOD3Index.ModifiedInstanceId = TGIRandomGenerator.GetNext();
                                    indices.Add(LOD3Index);
                                    LOD3Property.InstanceId = LOD3Index.ModifiedInstanceId.Value;
                                    unitDisplayFile.Values[PropertyConstants.UnitLOD3] = LOD3Property;
                                }

                                if (unitDisplayFile.Values.ContainsKey(PropertyConstants.UnitLOD4))
                                {
                                    KeyProperty   LOD4Property = (KeyProperty)unitDisplayFile.Values[PropertyConstants.UnitLOD4];
                                    DatabaseIndex LOD4Index    = DatabaseIndex.FindIndex(LOD4Property.TypeId, null, null, LOD4Property.InstanceId, true, false);
                                    LOD4Index.ModifiedInstanceId = TGIRandomGenerator.GetNext();
                                    indices.Add(LOD4Index);
                                    LOD4Property.InstanceId = LOD4Index.ModifiedInstanceId.Value;
                                    unitDisplayFile.Values[PropertyConstants.UnitLOD4] = LOD4Property;
                                }


                                #endregion

                                unitDisplayIndex.ModifiedData = new ModifiedPropertyFile()
                                {
                                    PropertyFile = unitDisplayFile
                                };
                                unitDisplayIndex.IsModified = true;

                                indices.Add(unitDisplayIndex);
                            }

                            #endregion

                            unitIndex.ModifiedInstanceId = TGIRandomGenerator.GetNext();
                            unitIndex.ModifiedData       = new ModifiedPropertyFile()
                            {
                                PropertyFile = unitFile
                            };
                            unitIndex.IsModified = true;

                            indices.Add(unitIndex);

                            unitProperty.InstanceId          = unitIndex.ModifiedInstanceId.Value;
                            menuItemIndex.Index.ModifiedData = new ModifiedPropertyFile()
                            {
                                PropertyFile = menuFile
                            };

                            menuFile.Values[PropertyConstants.menuUnit] = unitProperty;
                        }

                        #endregion
                        DatabasePackedFile.SaveAs(dialog.FileName, indices);
                    }
                }
                else
                {
                    MessageBox.Show("This only works for menu items...");
                }
            }
        }
        /// <summary>
        /// Creates the instance.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException">value</exception>
        public virtual Property GetProperty(string propertyName, object value)
        {
            Property property;

            if (string.IsNullOrEmpty(propertyName))
            {
                throw new ArgumentException("Property name must be non null.", "propertyName");
            }
            if (value == null)
            {
                throw new ArgumentNullException("Property value must be non null.", "value");
            }

            if (string.Compare(propertyName, "StateCode", true, CultureInfo.InvariantCulture) == 0)
            {
                property = new StateProperty {
                    Value = (string)value
                };
            }
            else if (value is string)
            {
                property = new StringProperty {
                    Value = (string)value
                };
            }
            else if (value is UniqueIdentifier)
            {
                property = new UniqueIdentifierProperty {
                    Value = (UniqueIdentifier)value
                };
            }
            else if (value is Status)
            {
                property = new StatusProperty {
                    Value = (Status)value
                };
            }
            else if (value is Picklist)
            {
                property = new PicklistProperty {
                    Value = (Picklist)value
                };
            }
            else if (value is Owner)
            {
                property = new OwnerProperty {
                    Value = (Owner)value
                };
            }
            else if (value is Lookup)
            {
                property = new LookupProperty {
                    Value = (Lookup)value
                };
            }
            else if (value is CrmCampaignIntegration.Services.Key)
            {
                property = new KeyProperty {
                    Value = (CrmCampaignIntegration.Services.Key)value
                };
            }
            else if (value is EntityNameReference)
            {
                property = new EntityNameReferenceProperty {
                    Value = (EntityNameReference)value
                };
            }
            else if (value is DynamicEntity[])
            {
                property = new DynamicEntityArrayProperty {
                    Value = (DynamicEntity[])value
                };
            }
            else if (value is Customer)
            {
                property = new CustomerProperty {
                    Value = (Customer)value
                };
            }
            else if (value is CrmCampaignIntegration.Services.CrmNumber)
            {
                property = new CrmNumberProperty {
                    Value = (CrmCampaignIntegration.Services.CrmNumber)value
                };
            }
            else if (value is CrmMoney)
            {
                property = new CrmMoneyProperty {
                    Value = (CrmMoney)value
                };
            }
            else if (value is CrmCampaignIntegration.Services.CrmFloat)
            {
                property = new CrmFloatProperty {
                    Value = (CrmCampaignIntegration.Services.CrmFloat)value
                };
            }
            else if (value is CrmDecimal)
            {
                property = new CrmDecimalProperty {
                    Value = (CrmDecimal)value
                };
            }
            else if (value is CrmCampaignIntegration.Services.CrmDateTime)
            {
                property = new CrmDateTimeProperty {
                    Value = (CrmCampaignIntegration.Services.CrmDateTime)value
                };
            }
            else if (value is CrmCampaignIntegration.Services.CrmBoolean)
            {
                property = new CrmBooleanProperty {
                    Value = (CrmCampaignIntegration.Services.CrmBoolean)value
                };
            }
            else
            {
                throw new NotSupportedException(string.Format("Unknown value type: {0}", value.GetType()));
            }

            property.Name = propertyName;
            return(property);
        }
Exemplo n.º 21
0
        private DataDictionary LoadDataObjects(List<string> tableNames)
        {
            try
            {
                DataObjects _dataObjects = new DataObjects();
                DataObject _dataObject = new DataObject();
                KeyProperty _keyproperties = new KeyProperty();
                DataProperty _dataproperties = new DataProperty();
                DataDictionary dataDictionary = new DataDictionary();
                ConnectToAccess();

                foreach (string strname in tableNames)
                {
                    _dataObject = new DataObject();
                    _dataObject.objectName = strname.ToLower();
                    _dataObject.tableName = strname.ToLower();
                    _dataObject.keyDelimeter = "_";

                    DataTable colKey = _connOledb.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, new Object[] { null, null, strname });
                    DataView view = colKey.DefaultView;
                    view.Sort = "ORDINAL";
                    colKey = view.ToTable();
                    List<string> tableKeys = new List<string>();
                    foreach (DataRow row in colKey.Rows)
                    {
                        tableKeys.Add(row["COLUMN_NAME"].ToString());
                    }

                    DataTable tableColumns = _connOledb.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, strname, null });
                    foreach (DataRow row in tableColumns.Rows)
                    {
                        _dataproperties = new DataProperty();
                        _dataproperties.columnName = row["COLUMN_NAME"].ToString();
                        _dataproperties.propertyName = row["COLUMN_NAME"].ToString();

                        if (!(row["CHARACTER_MAXIMUM_LENGTH"] is DBNull))
                        {
                            _dataproperties.dataLength = Convert.ToInt32(row["CHARACTER_MAXIMUM_LENGTH"]);
                            if(_dataproperties.dataLength == 0)
                                _dataproperties.dataLength = 8000; // Memo Stores up to 8000 characters
                        }
                        else
                            _dataproperties.dataLength = 50;

                        _dataproperties.isNullable = Convert.ToBoolean(row["IS_NULLABLE"]);

                        if (tableKeys.Contains(_dataproperties.columnName))
                        {
                            _keyproperties = new KeyProperty();
                            _keyproperties.keyPropertyName = _dataproperties.columnName;
                            _dataObject.keyProperties.Add(_keyproperties);
                            _dataproperties.keyType = KeyType.assigned;
                        }
                        else
                        {
                            _dataproperties.keyType = KeyType.unassigned;
                        }

                        switch (row["DATA_TYPE"].ToString())
                        {
                            case "11":
                                _dataproperties.dataType = DataType.Boolean;
                                break;
                            case "2":
                            case "3":
                            case "4":
                                _dataproperties.dataType = DataType.Int32;
                                break;
                            case "7":
                                _dataproperties.dataType = DataType.DateTime;
                                break;
                            default:
                                _dataproperties.dataType = DataType.String;
                                break;
                        }
                        _dataObject.dataProperties.Add(_dataproperties);
                    }
                    dataDictionary.dataObjects.Add(_dataObject);
                }
                return dataDictionary;
            }
            catch (Exception ex)
            {
                logger.Error("Error in generating the dictionary.");
                throw ex;
            }
            finally
            {
                _connOledb.Close();
            }
        }
Exemplo n.º 22
0
        private void ReloadDisplayProperties(Dictionary <uint, Property> propertyCollection)
        {
            try
            {
                displayProperties = new List <PropertyModel>();
                foreach (KeyValuePair <uint, Property> prop in propertyCollection)
                {
                    if (prop.Value is ArrayProperty)
                    {
                        int           arrIndex = 0;
                        ArrayProperty arr      = prop.Value as ArrayProperty;
                        foreach (Property subProp in arr.Values)
                        {
                            subProp.PropertyChanged += new EventHandler(Value_PropertyChanged);
                            displayProperties.Add(new PropertyModel(prop.Key, subProp, true, arrIndex));
                            arrIndex++;
                        }
                    }
                    else
                    {
                        displayProperties.Add(new PropertyModel(prop.Key, prop.Value, false, 0));
                    }
                    if (prop.Value is KeyProperty)
                    {
                        KeyProperty kp = prop.Value as KeyProperty;
                        if (kp.TypeId == 0x2f7d0004 || kp.TypeId == 0x3f8662ea)//PNG
                        {
                            DatabaseIndex imageIndex = DatabaseManager.Instance.Indices.Find(idx => idx.InstanceId == kp.InstanceId && idx.GroupContainer == kp.GroupContainer && idx.TypeId == kp.TypeId);
                            if (imageIndex != null)
                            {
                                Image  imageControl = new Image();
                                byte[] imgdata      = imageIndex.GetIndexData(true);
                                using (MemoryStream imageByteStream = new MemoryStream(imgdata))
                                {
                                    try
                                    {
                                        BitmapImage image = new BitmapImage();
                                        image.BeginInit();
                                        image.StreamSource = imageByteStream;
                                        image.CacheOption  = BitmapCacheOption.OnLoad;
                                        image.EndInit();
                                        imageControl.Source  = image;
                                        imageControl.Width   = 80;
                                        imageControl.Height  = 80;
                                        imageControl.Stretch = Stretch.Fill;
                                        pnlImages.Children.Add(imageControl);
                                    }
                                    catch
                                    {
                                    }
                                }
                            }
                        }
                    }
                    prop.Value.PropertyChanged += new EventHandler(Value_PropertyChanged);
                }
                ((Expander)pnlImages.Parent).Visibility = (pnlImages.Children.Count == 0) ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;

                dataGrid1.ItemsSource = displayProperties;

                txtStatus.Text = string.Format("Loaded {0} of {1} properties", propertyFile.Values.Count, propertyFile.PropertyCount);
            }
            catch
            {
            }
        }
    // Use this for initialization
    void Awake()
    {
        MusicPlayer = GameObject.FindObjectOfType <MusicPlayer>();

        RectTransform p       = gameObject.GetComponent <RectTransform>();
        RectTransform r       = WhiteKey.gameObject.GetComponent <RectTransform>();
        float         width   = r.rect.width;
        Vector3       basePos = WhiteKey.transform.localPosition;

        int[] ofs = { 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12 };
        numKeys = (int)((p.rect.width - (p.rect.width / 2 + (basePos.x - width / 2)) * 2) / width) * 12 / 7;
        for (int i = 0; i < numKeys; i++)
        {
            int o = ofs[i % 12];
            if ((o & 1) != 0)
            {
                continue;
            }
            int         index = i;
            KeyProperty key   = Instantiate(WhiteKey);
            Vector3     pos   = basePos;
            Vector3     scl   = key.transform.localScale;
            pos.x += ((i / 12) * 14 + o) * (width / 2);
            key.transform.SetParent(gameObject.transform);
            key.transform.localPosition = pos;
            key.transform.localScale    = scl;
            key.OnKeyDownEvent.AddListener(() => OnKeyDown(index));
            key.OnKeyUpEvent.AddListener(() => OnKeyUp(index));
        }
        for (int i = 0; i < numKeys; i++)
        {
            int o = ofs[i % 12];
            if ((o & 1) == 0)
            {
                continue;
            }
            int         index = i;
            KeyProperty key   = Instantiate(BlackKey);
            Vector3     pos   = basePos;
            Vector3     scl   = key.transform.localScale;
            pos.x += ((i / 12) * 14 + o) * (width / 2);
            key.transform.SetParent(gameObject.transform);
            key.transform.localPosition = pos;
            key.transform.localScale    = scl;
            key.OnKeyDownEvent.AddListener(() => OnKeyDown(index));
            key.OnKeyUpEvent.AddListener(() => OnKeyUp(index));
        }

        Text   position = gameObject.transform.Find("Position").gameObject.GetComponent <Text>();
        Button lshift   = gameObject.transform.Find("LShift").gameObject.GetComponent <Button>();

        BaseNote     -= BaseNote % 12;
        position.text = "^C" + (BaseNote / 12 - 2 + 1);
        lshift.onClick.AddListener(() =>
        {
            if (BaseNote - 12 >= 0)
            {
                BaseNote     -= 12;
                position.text = "^C" + (BaseNote / 12 - 2 + 1);
            }
        });
        Button rshift = gameObject.transform.Find("RShift").gameObject.GetComponent <Button>();

        rshift.onClick.AddListener(() =>
        {
            if (BaseNote + numKeys + 12 <= 128)
            {
                BaseNote     += 12;
                position.text = "^C" + (BaseNote / 12 - 2 + 1);
            }
        });
        Slider velocity = gameObject.transform.Find("Velocity").gameObject.GetComponent <Slider>();

        velocity.onValueChanged.AddListener((value) =>
        {
            vel = (int)value;
            velocity.gameObject.transform.Find("Value").gameObject.GetComponent <Text>().text = "" + vel;
        });

        Slider volume = gameObject.transform.Find("Volume").gameObject.GetComponent <Slider>();

        volume.onValueChanged.AddListener((value) =>
        {
            vol = (int)value;
            MusicPlayer.Synthesizer.MasterVolume((byte)value);
            volume.gameObject.transform.Find("Value").gameObject.GetComponent <Text>().text = "" + (byte)value;
        });

        KeyProperty hold = gameObject.transform.Find("Hold").gameObject.GetComponent <KeyProperty>();

        hold.OnKeyDownEvent.AddListener(() => MusicPlayer.Synthesizer.Channel[ChNo].Damper(+127));
        hold.OnKeyUpEvent.AddListener(() => MusicPlayer.Synthesizer.Channel[ChNo].Damper(0));

        KeyProperty damp = gameObject.transform.Find("Damp").gameObject.GetComponent <KeyProperty>();

        damp.OnKeyDownEvent.AddListener(() => MusicPlayer.Synthesizer.Channel[ChNo].Damper(-127 + 256));
        damp.OnKeyUpEvent.AddListener(() => MusicPlayer.Synthesizer.Channel[ChNo].Damper(0));
    }
Exemplo n.º 24
0
        public override bool UpdateUserProperties(string userName, Dictionary <string, object> properties)
        {
            Assert.ArgumentNotNull(userName, "userName");
            Assert.ArgumentNotNull(properties, "properties");

            const string UpdateUserProrpertiesKey = "updateUserProperties";

            ConditionalLog.Info(String.Format("UpdateUserProperties({0}). Started.", userName), this, TimerAction.Start, UpdateUserProrpertiesKey);

            var result = false;

            var user = this.UserRepository.GetUser(userName);

            if (user != null)
            {
                if (properties.ContainsKey("fullname"))
                {
                    this.ProcessFullNameProperty((string)properties["fullname"], properties);
                }

                var propertiesToUpdate = new List <Property>();

                var keyProperty = new KeyProperty();
                keyProperty.Name        = "contactid";
                keyProperty.Value       = new crm4.webservice.Key();
                keyProperty.Value.Value = user.ID;

                propertiesToUpdate.Add(keyProperty);
                foreach (var property in properties)
                {
                    this.AddPropertyToCollection(property.Key, property.Value, this.GetPropertyType(property.Key), propertiesToUpdate);
                }

                var update = new UpdateRequest
                {
                    Target = new TargetUpdateDynamic
                    {
                        Entity = new DynamicEntity
                        {
                            Name       = EntityName.contact.ToString(),
                            Properties = propertiesToUpdate.ToArray()
                        }
                    }
                };

                try
                {
                    this.CrmService.Execute(update);
                    ConditionalLog.Info(String.Format("UpdateUserProperties({0}). Updated in CRM.", userName), this, TimerAction.Tick, UpdateUserProrpertiesKey);

                    var propertyToValueConverter = new PropertyToValueConverterV4();
                    foreach (var property in propertiesToUpdate)
                    {
                        user.SetPropertyValue(property.Name, propertyToValueConverter.Convert(property));
                    }

                    result = true;
                }
                catch (Exception e)
                {
                    ConditionalLog.Error(String.Format("Couldn't save profile changes for the contact {0} in CRM.", userName), e, this);
                }
            }

            ConditionalLog.Info(String.Format("UpdateUserProperties({0}). Finished.", userName), this, TimerAction.Stop, UpdateUserProrpertiesKey);
            return(result);
        }
Exemplo n.º 25
0
        private DataDictionary LoadDataObjects()
        {
            try
            {
                string Object_Name = string.Empty;
                DataObject _dataObject = new DataObject();
                KeyProperty _keyproperties = new KeyProperty();
                DataProperty _dataproperties = new DataProperty();
                DataDictionary _dataDictionary = new DataDictionary();
                List<DataProp> dataPrpCollection = new List<DataProp>();

                foreach (var dic in _objectyDictionary)
                {
                    string objectName = dic.Key.Split('_')[1];
                    string url = dic.Value;
                    string jsonString = GetJsonResponseFrom(url);
                    FillDataPropertiesFrom(jsonString, dataPrpCollection, objectName);
                }

                foreach (DataProp dp in dataPrpCollection)
                {
                    if (Object_Name != dp.Object_Name)
                    {
                        if (!string.IsNullOrEmpty(Object_Name))
                            _dataDictionary.dataObjects.Add(_dataObject);
                        _dataObject = new DataObject();
                        Object_Name = dp.Object_Name;
                        _dataObject.objectName = Object_Name;
                        _dataObject.tableName = Object_Name;
                        _dataObject.keyDelimeter = _keyDelimiter;
                    }

                    _dataproperties = new DataProperty();
                    _dataproperties.columnName = dp.columnName;

                    if (dp.isKey)
                    {
                        KeyProperty keyProperty = new KeyProperty();
                        keyProperty.keyPropertyName = dp.columnName;
                        _dataObject.keyProperties.Add(keyProperty);

                        _dataproperties.keyType = KeyType.assigned;
                        _dataproperties.isNullable = false;
                    }
                    else
                    {
                        _dataproperties.keyType = KeyType.unassigned;
                        _dataproperties.isNullable = true;
                    }

                    _dataproperties.propertyName = dp.propertyName;
                    _dataproperties.dataLength = Convert.ToInt32(dp.dataLength);

                    _dataproperties.dataType = dp.dataType;

                    _dataObject.dataProperties.Add(_dataproperties);
                }
                _dataDictionary.dataObjects.Add(_dataObject);

                return _dataDictionary;
            }
            catch (Exception ex)
            {
                _logger.Error("Error in loading data dictionary : " + ex);
                throw ex;
            }
            finally
            {
                //Disconnect();
            }
        }
Exemplo n.º 26
0
 internal static extern bool CryptGetKeyParam(SafeCspKeyHandle hKey,
                                              KeyProperty dwParam,
                                              [In, Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbData,
                                              [In, Out] ref int pdwDataLen,
                                              int dwFlags);
Exemplo n.º 27
0
 internal static extern bool CryptGetKeyParam(SafeCspKeyHandle hKey,
                                              KeyProperty dwParam,
                                              [In, Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbData,
                                              [In, Out] ref int pdwDataLen,
                                              int dwFlags);
Exemplo n.º 28
0
 internal static int GetKeyPropertyInt32(SafeCspKeyHandle keyHandle, KeyProperty property)
 {
     byte[] rawProperty = GetKeyProperty(keyHandle, property);
     Contract.Assert(rawProperty.Length == sizeof(int) || rawProperty.Length == 0, "Unexpected property size");
     return(rawProperty.Length == sizeof(int) ? BitConverter.ToInt32(rawProperty, 0) : 0);
 }
Exemplo n.º 29
0
 internal static int GetKeyPropertyInt32(SafeCspKeyHandle keyHandle, KeyProperty property) {
     byte[] rawProperty = GetKeyProperty(keyHandle, property);
     Contract.Assert(rawProperty.Length == sizeof(int) || rawProperty.Length == 0, "Unexpected property size");
     return rawProperty.Length == sizeof(int) ? BitConverter.ToInt32(rawProperty, 0) : 0;
 }
Exemplo n.º 30
0
        public DatabaseDictionary GetDatabaseSchema(Request request)
        {
            try
            {
                string connString = request["connectionString"];
                string dbProvider = request["dbProvider"];
                dbProvider = dbProvider.ToUpper();
                string parsedConnStr = ParseConnectionString(connString, dbProvider);

                DatabaseDictionary          dbDictionary = new DatabaseDictionary();
                Dictionary <string, string> properties   = new Dictionary <string, string>();
                string metadataQuery = string.Empty;
                dbDictionary.connectionString = parsedConnStr;
                dbDictionary.dataObjects      = new System.Collections.Generic.List <DataObject>();

                properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
                properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
                properties.Add("connection.connection_string", parsedConnStr);

                if (dbProvider.Contains("MSSQL"))
                {
                    metadataQuery =
                        "select t1.table_name, t1.column_name, t1.data_type, t2.max_length, t2.is_identity, t2.is_nullable, t5.constraint_type " +
                        "from information_schema.columns t1 " +
                        "inner join sys.columns t2 on t2.name = t1.column_name " +
                        "inner join sys.tables t3 on t3.name = t1.table_name and t3.object_id = t2.object_id " +
                        "left join information_schema.key_column_usage t4 on t4.table_name = t1.table_name and t4.column_name = t1.column_name " +
                        "left join information_schema.table_constraints t5 on t5.constraint_name = t4.constraint_name " +
                        "order by t1.table_name, t5.constraint_type, t1.column_name";
                    properties.Add("connection.driver_class", "NHibernate.Driver.SqlClientDriver");

                    switch (dbProvider)
                    {
                    case "MSSQL2008":
                        dbDictionary.provider = Provider.MsSql2008;
                        properties.Add("dialect", "NHibernate.Dialect.MsSql2008Dialect");
                        break;

                    case "MSSQL2005":
                        dbDictionary.provider = Provider.MsSql2005;
                        properties.Add("dialect", "NHibernate.Dialect.MsSql2005Dialect");
                        break;

                    case "MSSQL2000":
                        dbDictionary.provider = Provider.MsSql2000;
                        properties.Add("dialect", "NHibernate.Dialect.MsSql2000Dialect");
                        break;

                    default:
                        throw new Exception("Database provider not supported.");
                    }
                }
                else if (dbProvider.Contains("ORACLE"))
                {
                    metadataQuery =
                        "select t1.object_name, t2.column_name, t2.data_type, t2.data_length, 0 as is_sequence, t2.nullable, t4.constraint_type " +
                        "from user_objects t1 " +
                        "inner join all_tab_cols t2 on t2.table_name = t1.object_name " +
                        "left join all_cons_columns t3 on t3.table_name = t2.table_name and t3.column_name = t2.column_name " +
                        "left join all_constraints t4 on t4.constraint_name = t3.constraint_name and (t4.constraint_type = 'P' or t4.constraint_type = 'R') " +
                        "where t1.object_type = 'TABLE' order by t1.object_name, t4.constraint_type, t2.column_name";
                    properties.Add("connection.driver_class", "NHibernate.Driver.OracleClientDriver");

                    switch (dbProvider)
                    {
                    case "ORACLE10G":
                        dbDictionary.provider = Provider.Oracle10g;
                        properties.Add("dialect", "NHibernate.Dialect.Oracle10gDialect");
                        break;

                    case "ORACLE9I":
                        dbDictionary.provider = Provider.Oracle9i;
                        properties.Add("dialect", "NHibernate.Dialect.Oracle9iDialect");
                        break;

                    case "ORACLE8I":
                        dbDictionary.provider = Provider.Oracle8i;
                        properties.Add("dialect", "NHibernate.Dialect.Oracle8iDialect");
                        break;

                    case "ORACLELITE":
                        dbDictionary.provider = Provider.OracleLite;
                        properties.Add("dialect", "NHibernate.Dialect.OracleLiteDialect");
                        break;

                    default:
                        throw new Exception("Database provider not supported.");
                    }
                }
                else if (dbProvider.Contains("MYSQL"))
                {
                    metadataQuery = "SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE,CHARACTER_MAXIMUM_LENGTH, COLUMN_KEY, IS_NULLABLE " +
                                    "FROM INFORMATION_SCHEMA.COLUMNS " +
                                    string.Format("WHERE TABLE_SCHEMA = '{0}'", connString.Split(';')[1].Split('=')[1]);
                    properties.Add("connection.driver_class", "NHibernate.Driver.MySqlDataDriver");

                    switch (dbProvider)
                    {
                    case "MYSQL3":
                        dbDictionary.provider = Provider.MySql3;
                        properties.Add("dialect", "NHibernate.Dialect.MySQLDialect");
                        break;

                    case "MYSQL4":
                        dbDictionary.provider = Provider.MySql4;
                        properties.Add("dialect", "NHibernate.Dialect.MySQLDialect");
                        break;

                    case "MYSQL5":
                        dbDictionary.provider = Provider.MySql5;
                        properties.Add("dialect", "NHibernate.Dialect.MySQL5Dialect");
                        break;
                    }
                }


                NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
                config.AddProperties(properties);

                ISessionFactory  sessionFactory = config.BuildSessionFactory();
                ISession         session        = sessionFactory.OpenSession();
                ISQLQuery        query          = session.CreateSQLQuery(metadataQuery);
                IList <object[]> metadataList   = query.List <object[]>();
                session.Close();

                DataObject table         = null;
                string     prevTableName = String.Empty;
                foreach (object[] metadata in metadataList)
                {
                    string tableName  = Convert.ToString(metadata[0]);
                    string columnName = Convert.ToString(metadata[1]);
                    string dataType   = Utility.SqlTypeToCSharpType(Convert.ToString(metadata[2]));
                    int    dataLength = Convert.ToInt32(metadata[3]);
                    bool   isIdentity = Convert.ToBoolean(metadata[4]);
                    string nullable   = Convert.ToString(metadata[5]).ToUpper();
                    bool   isNullable = (nullable == "Y" || nullable == "TRUE");
                    string constraint = Convert.ToString(metadata[6]);

                    if (tableName != prevTableName)
                    {
                        table = new DataObject()
                        {
                            tableName         = tableName,
                            dataProperties    = new List <DataProperty>(),
                            keyProperties     = new KeyProperties(),
                            dataRelationships = new List <DataRelationship>(), // to be supported in the future
                            objectName        = Utility.NameSafe(tableName)
                        };

                        dbDictionary.dataObjects.Add(table);
                        prevTableName = tableName;
                    }

                    if (String.IsNullOrEmpty(constraint)) // process columns
                    {
                        DataProperty column = new DataProperty()
                        {
                            columnName = columnName,
                            dataType   = (DataType)Enum.Parse(typeof(DataType), dataType),
                            // dataType = (DataType)Enum.Parse(typeof(DataType), dataType),
                            dataLength   = dataLength,
                            isNullable   = isNullable,
                            propertyName = Utility.NameSafe(columnName)
                        };

                        table.dataProperties.Add(column);
                    }
                    else // process keys
                    {
                        KeyType keyType = KeyType.assigned;

                        if (isIdentity)
                        {
                            keyType = KeyType.identity;
                        }
                        else if (constraint.ToUpper() == "FOREIGN KEY" || constraint.ToUpper() == "R")
                        {
                            keyType = KeyType.foreign;
                        }

                        KeyProperty key = new KeyProperty()
                        {
                            columnName = columnName,
                            dataType   = (DataType)Enum.Parse(typeof(DataType), dataType),
                            //   dataType = (DataType)Enum.Parse(typeof(DataType), dataType),
                            dataLength   = dataLength,
                            isNullable   = isNullable,
                            keyType      = keyType,
                            propertyName = Utility.NameSafe(columnName),
                        };

                        table.keyProperties.Add(key);
                    }
                }
                return(dbDictionary);
            }
            catch (Exception ex)
            {
                _logger.Error("Error in GetDatabaseSchema: " + ex);
                return(null);
            }
        }
Exemplo n.º 31
0
        internal static byte[] GetKeyProperty(SafeCspKeyHandle keyHandle, KeyProperty property) {
            Contract.Assert(keyHandle != null && !keyHandle.IsInvalid, "keyHandle != null && !keyHandle.IsInvalid");

            int bufferSize = 0;
            byte[] buffer = null;

            // Figure out how big of a buffer we need to hold the property
            if (!UnsafeNativeMethods.CryptGetKeyParam(keyHandle, property, buffer, ref bufferSize, 0)) {
                int errorCode = Marshal.GetLastWin32Error();
                if (errorCode != (int)ErrorCode.MoreData) {
                    throw new CryptographicException(errorCode);
                }
            }

            // Now get the property bytes directly
            buffer = new byte[bufferSize];
            if (!UnsafeNativeMethods.CryptGetKeyParam(keyHandle, property, buffer, ref bufferSize, 0)) {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }

            return buffer;
        }
Exemplo n.º 32
0
 public virtual Task <TEntity> TryGetAsync(TKey key)
 {
     return(DbContext.Set <TEntity>().AsNoTracking().SingleOrDefaultAsync(KeyProperty.GetEqualsPredicateForConstant(key)));
 }
Exemplo n.º 33
0
        private DataObject CreateDataObject(BusinessObject businessObject)
        {
            string     propertyName        = string.Empty;
            string     keyPropertyName     = string.Empty;
            string     relatedPropertyName = string.Empty;
            string     relatedObjectName   = string.Empty;
            string     relationshipName    = string.Empty;
            DataObject dataObject          = new DataObject();
            string     objectName          = businessObject.objectName;

            dataObject.objectName        = objectName;
            dataObject.objectNamespace   = projectNameSpace;
            dataObject.tableName         = objectName;
            dataObject.keyProperties     = new List <KeyProperty>();
            dataObject.dataProperties    = new List <DataProperty>();
            dataObject.dataRelationships = new List <DataRelationship>();

            if (businessObject.dataFilter != null)
            {
                dataObject.dataFilter = businessObject.dataFilter;
            }

            foreach (BusinessKeyProperty businessKeyProerpty in businessObject.businessKeyProperties)
            {
                KeyProperty  keyProperty  = new KeyProperty();
                DataProperty dataProperty = new DataProperty();
                keyPropertyName             = businessKeyProerpty.keyPropertyName;;
                keyProperty.keyPropertyName = keyPropertyName;
                dataProperty.propertyName   = keyPropertyName;
                dataProperty.dataType       = DataType.String;
                dataProperty.columnName     = keyPropertyName;
                dataProperty.isNullable     = false;
                dataProperty.keyType        = KeyType.assigned;
                dataObject.keyProperties.Add(keyProperty);
                dataObject.dataProperties.Add(dataProperty);
            }

            foreach (BusinessInterface businessInterface in businessObject.businessInterfaces)
            {
                InterfaceInformation interfaceInfo = GetInterfaceInformation(businessInterface.interfaceName);

                foreach (BusinessProperty businessProperty in businessInterface.businessProperties)
                {
                    propertyName = businessProperty.propertyName;

                    if (interfaceInfo != null)
                    {
                        if (HasProperty(interfaceInfo, propertyName))
                        {
                            DataProperty dataProperty = new DataProperty();

                            if (!String.IsNullOrEmpty(businessProperty.dbColumn))
                            {
                                dataProperty.columnName = businessProperty.dbColumn;
                            }
                            else
                            {
                                dataProperty.columnName = propertyName;
                            }
                            dataProperty.propertyName = propertyName;

                            dataProperty.dataType   = GetDatatype(businessProperty.dataType);
                            dataProperty.isNullable = businessProperty.isNullable;
                            dataProperty.isReadOnly = businessObject.isReadOnly;

                            if (!String.IsNullOrEmpty(businessProperty.description) != null)
                            {
                                dataProperty.description = businessObject.description;
                            }

                            dataObject.dataProperties.Add(dataProperty);
                        }
                        else
                        {
                            throw new Exception("Property [" + propertyName + "] not found.");
                        }
                    }
                    else
                    {
                        throw new Exception("Interface [" + businessInterface.interfaceName + "] not found.");
                    }
                }
            }

            foreach (BusinessRelationship businessRelationship in businessObject.businessRelationships)
            {
                DataRelationship dataRelationship = new DataRelationship();
                relationshipName  = businessRelationship.relationshipName;
                relatedObjectName = businessRelationship.relatedObjectName;

                if (IsRelated(relationshipName, relatedObjectName, objectName))
                {
                    dataRelationship.relatedObjectName = businessRelationship.relatedObjectName;
                    dataRelationship.relationshipName  = businessRelationship.relationshipName;
                    dataRelationship.propertyMaps      = new List <PropertyMap>();

                    if (businessRelationship.businessRelatedInterfaces != null)
                    {
                        foreach (BusinessInterface businessInterface in businessRelationship.businessRelatedInterfaces)
                        {
                            foreach (BusinessProperty businessRelationProperty in businessInterface.businessProperties)
                            {
                                InterfaceInformation interfaceInfo = GetInterfaceInformation(businessInterface.interfaceName);
                                relatedPropertyName = businessRelationProperty.propertyName;

                                if (interfaceInfo != null)
                                {
                                    if (HasProperty(interfaceInfo, relatedPropertyName))
                                    {
                                        DataProperty dataProperty = new DataProperty();
                                        PropertyMap  propertyMap  = new PropertyMap();
                                        propertyMap.relatedPropertyName = relatedPropertyName;
                                        dataProperty.propertyName       = dataRelationship.relatedObjectName + "_" + relatedPropertyName;
                                        dataProperty.dataType           = GetDatatype(businessRelationProperty.dataType);

                                        if (!String.IsNullOrEmpty(businessRelationProperty.dbColumn))
                                        {
                                            dataProperty.columnName = businessRelationProperty.dbColumn;
                                        }
                                        else
                                        {
                                            dataProperty.columnName = relatedPropertyName;
                                        }

                                        dataRelationship.propertyMaps.Add(propertyMap);
                                        dataObject.dataProperties.Add(dataProperty);
                                    }
                                    else
                                    {
                                        throw new Exception("Property [" + relatedPropertyName + "] not found.");
                                    }
                                }
                                else
                                {
                                    throw new Exception("Interface [" + businessInterface.interfaceName + "] not found.");
                                }
                            }
                        }
                        dataObject.dataRelationships.Add(dataRelationship);
                    }
                }
            }
            return(dataObject);
        }
Exemplo n.º 34
0
        private DataObject CreateDataObject(BusinessObject businessObject)
        {
            string propertyName = string.Empty;
              string keyPropertyName = string.Empty;
              string relatedPropertyName = string.Empty;
              string relatedObjectName = string.Empty;
              string relationshipName = string.Empty;
              DataObject dataObject = new DataObject();
              string objectName = businessObject.objectName;
              dataObject.objectName = objectName;
              dataObject.objectNamespace = projectNameSpace;
              dataObject.tableName = objectName;
              dataObject.keyProperties = new List<KeyProperty>();
              dataObject.dataProperties = new List<DataProperty>();
              dataObject.dataRelationships = new List<DataRelationship>();

              if (businessObject.dataFilter != null)
            dataObject.dataFilter = businessObject.dataFilter;

              foreach (BusinessKeyProperty businessKeyProerpty in businessObject.businessKeyProperties)
              {
            KeyProperty keyProperty = new KeyProperty();
            DataProperty dataProperty = new DataProperty();
            keyPropertyName = businessKeyProerpty.keyPropertyName;;
            keyProperty.keyPropertyName = keyPropertyName;
            dataProperty.propertyName = keyPropertyName;
            dataProperty.dataType = DataType.String;
            dataProperty.columnName = keyPropertyName;
            dataProperty.isNullable = false;
            dataProperty.keyType = KeyType.assigned;
            dataObject.keyProperties.Add(keyProperty);
            dataObject.dataProperties.Add(dataProperty);
              }

              foreach (BusinessInterface businessInterface in businessObject.businessInterfaces)
              {
            InterfaceInformation interfaceInfo = GetInterfaceInformation(businessInterface.interfaceName);

            foreach (BusinessProperty businessProperty in businessInterface.businessProperties)
            {
              propertyName = businessProperty.propertyName;

              if (interfaceInfo != null)
              {
            if (HasProperty(interfaceInfo, propertyName))
            {
              DataProperty dataProperty = new DataProperty();

              if (!String.IsNullOrEmpty(businessProperty.dbColumn))
                dataProperty.columnName = businessProperty.dbColumn;
              else
                dataProperty.columnName = propertyName;
              dataProperty.propertyName = propertyName;

              dataProperty.dataType = GetDatatype(businessProperty.dataType);
              dataProperty.isNullable = businessProperty.isNullable;
              dataProperty.isReadOnly = businessObject.isReadOnly;

              if (!String.IsNullOrEmpty(businessProperty.description) != null)
                dataProperty.description = businessObject.description;

              dataObject.dataProperties.Add(dataProperty);
            }
            else
            {
              throw new Exception("Property [" + propertyName + "] not found.");
            }
              }
              else
            throw new Exception("Interface [" + businessInterface.interfaceName + "] not found.");
            }
              }

              foreach (BusinessRelationship businessRelationship in businessObject.businessRelationships)
              {
            DataRelationship dataRelationship = new DataRelationship();
            relationshipName = businessRelationship.relationshipName;
            relatedObjectName = businessRelationship.relatedObjectName;

            if (IsRelated(relationshipName, relatedObjectName, objectName))
            {
              dataRelationship.relatedObjectName = businessRelationship.relatedObjectName;
              dataRelationship.relationshipName = businessRelationship.relationshipName;
              dataRelationship.propertyMaps = new List<PropertyMap>();

              if (businessRelationship.businessRelatedInterfaces != null)
              {
            foreach (BusinessInterface businessInterface in businessRelationship.businessRelatedInterfaces)
            {
              foreach (BusinessProperty businessRelationProperty in businessInterface.businessProperties)
              {
                InterfaceInformation interfaceInfo = GetInterfaceInformation(businessInterface.interfaceName);
                relatedPropertyName = businessRelationProperty.propertyName;

                if (interfaceInfo != null)
                {
                  if (HasProperty(interfaceInfo, relatedPropertyName))
                  {
                    DataProperty dataProperty = new DataProperty();
                    PropertyMap propertyMap = new PropertyMap();
                    propertyMap.relatedPropertyName = relatedPropertyName;
                    dataProperty.propertyName = dataRelationship.relatedObjectName + "_" + relatedPropertyName;
                    dataProperty.dataType = GetDatatype(businessRelationProperty.dataType);

                    if (!String.IsNullOrEmpty(businessRelationProperty.dbColumn))
                      dataProperty.columnName = businessRelationProperty.dbColumn;
                    else
                      dataProperty.columnName = relatedPropertyName;

                    dataRelationship.propertyMaps.Add(propertyMap);
                    dataObject.dataProperties.Add(dataProperty);
                  }
                  else
                  {
                    throw new Exception("Property [" + relatedPropertyName + "] not found.");
                  }
                }
                else
                  throw new Exception("Interface [" + businessInterface.interfaceName + "] not found.");
              }
            }
            dataObject.dataRelationships.Add(dataRelationship);
              }
            }
              }
              return dataObject;
        }
Exemplo n.º 35
0
        public String CreateConfig(Guid new_config_allid, Config config)
        {
            Guid configid = new_config_allid;

            try
            {
                DynamicEntity conf = new DynamicEntity("new_reestr");
                conf.Name = "new_reestr";

                CrmConnection crmc       = new CrmConnection("Crm");
                CrmService    crmService = crmc.CreateCrmService();

                if (new_config_allid == new Guid("{00000000-0000-0000-0000-000000000000}"))
                {
                    configid = crmService.Create(conf);
                }

                // Создаем экземпляр динамческого объекта и указываем его имя
                DynamicEntity myDEUpdate = new DynamicEntity();
                myDEUpdate.Name = "new_config_allid";


                // Создаем KeyProperty для хранения GUID’а обновляемой записи
                KeyProperty myConfigGuid = new KeyProperty();
                myConfigGuid.Name = "new_config_allid";

                // Указываем GUID обновляемой записи
                Key myConfigKey = new Key();
                myConfigKey.Value  = configid;
                myConfigGuid.Value = myConfigKey;
                myDEUpdate.Properties.Add(myConfigGuid);


                //if (conf.new_count != 0)
                //    myDEUpdate.Properties.Add(new CrmNumberProperty("new_count", new CrmNumber(conf.new_count)));


                ////Кем выдан
                //if (conf.new_giveoutby != null)
                //    myDEUpdate.Properties.Add(new StringProperty("new_giveoutby", contact.new_giveoutby));



                ////День рождения
                //if (contact.birthdate != null)
                //    myDEUpdate.Properties.Add(new CrmDateTimeProperty("birthdate", CrmDateTime.FromUser(DateTime.ParseExact(contact.birthdate, "yyyyMMddHHmmss", CultureInfo.InvariantCulture))));

                crmService.Update(myDEUpdate);


                //поиск контакта для переназначения ответственного, если таковой меняется
                Owner ownerID = new Owner();
                if (new_config_allid != new Guid("{00000000-0000-0000-0000-000000000000}"))
                {
                    try
                    {
                        string ln = ""; //фамилия
                        BusinessEntityCollection fcontact = searchContact(new_config_allid.ToString());
                        foreach (DynamicEntity cont1 in fcontact.BusinessEntities)
                        {
                            ln = cont1["lastname"].ToString();
                            if (cont1.Properties.Contains("ownerid"))
                            {
                                ownerID = (Owner)cont1["ownerid"];
                            }
                        }

                        logger.Info($"Нашли контакт {ln}. ownerid={ownerID.Value.ToString()}");
                    }
                    catch (Exception ex)
                    {
                        logger.Error($"Ошибка: {ex.ToString()}");
                    }
                }

                return(configid.ToString());
            }
            catch (SoapException ex)
            {
                logger.Error($"Ошибка: {ex.Detail.InnerText}");
                return(ex.Detail.InnerText);
            }
        }
Exemplo n.º 36
0
 set => SetValue(KeyProperty, value);
Exemplo n.º 37
0
        public ActionResult ObjectsTreeSql(FormCollection form)
        {
            try
            {
                string scope          = form["scope"];
                string app            = form["app"];
                string selectedTables = form["selectedTables"];
                //for edit sqlconfiguration
                string dbProvider1 = Convert.ToString(form["dbProvider"].ToLower().IndexOf("mssql"));
                string dbServer    = form["dbServer"];
                string dbInstance  = form["dbInstance"];
                string dbName      = form["dbName"];
                string portNumber  = form["portNumber"];
                string serName     = form["serName"];
                string dbUserName  = form["dbUserName"];
                string dbPassword  = form["dbPassword"];
                string dbSchema    = form["dbSchema"];

                var connStr = (dbProvider1 != "-1") ? "Data Source=" + dbServer + "\\" + dbInstance + ";" + "Initial Catalog=" +
                              dbName + ";User ID=" + dbUserName + ";Password="******"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=" + dbServer + ")(PORT=" +
                              portNumber + "))(CONNECT_DATA=(" + serName + "=" + dbInstance +
                              ")));User Id=" + dbUserName + ";Password="******"Data Objects",
                    type       = "dataObjects",
                    iconCls    = "folder",
                    expanded   = true,
                    children   = new List <Node>(),
                    properties = new Dictionary <string, object>()
                };

                objectsTree.Add(root);

                DatabaseDictionary dictionary = _repository.GetDBDictionary(scope, app);

                Dictionary <string, string> conElts = null;
                if (dictionary != null && !string.IsNullOrEmpty(dictionary.ConnectionString))
                {
                    string dbProvider = dictionary.Provider;
                    string conStr     = Utility.DecodeFrom64(dictionary.ConnectionString);

                    if (connStr == "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=)(PORT=))(CONNECT_DATA=(=)));User Id=;Password="******"dbSchema"] = dictionary.SchemaName;
                        root.properties.Add("connectionInfo", conElts);
                    }
                    else
                    {
                        conElts             = GetConnectionElements(dbProvider, connStr);
                        conElts["dbSchema"] = dictionary.SchemaName;
                        root.properties.Add("connectionInfo", conElts);
                    }
                }
                else
                {
                    conElts = new Dictionary <string, string>();
                    conElts.Add("dbProvider", form["dbProvider"]);
                    conElts.Add("dbServer", form["dbServer"]);
                    conElts.Add("dbInstance", form["dbInstance"]);
                    conElts.Add("serName", form["serName"]);
                    conElts.Add("dbName", form["dbName"]);
                    conElts.Add("dbSchema", form["dbSchema"]);
                    conElts.Add("dbUserName", form["dbUserName"]);
                    conElts.Add("dbPassword", form["dbPassword"]);
                    conElts.Add("portNumber", form["portNumber"]);
                }

                List <DataObject> dbObjects = null;
                if (!string.IsNullOrEmpty(conElts["dbServer"]))
                {
                    //
                    // get available tables
                    //
                    List <string> availTables = _repository.GetTableNames(scope, app, conElts);
                    root.properties.Add("tableNames", availTables);

                    //
                    // get selected tables metadata
                    //
                    List <string> configTables = null;

                    if (!string.IsNullOrEmpty(selectedTables))
                    {
                        string[] array = selectedTables.Split(',');
                        configTables = new List <string>(array);
                    }
                    else if (dictionary != null && dictionary.dataObjects.Count > 0)
                    {
                        configTables = new List <string>();

                        foreach (DataObject dataObject in dictionary.dataObjects)
                        {
                            configTables.Add(dataObject.tableName);
                        }
                    }

                    if (configTables != null && configTables.Count > 0)
                    {
                        dbObjects = _repository.GetDBObjects(scope, app, conElts, configTables);
                    }
                }

                if (dbObjects != null)
                {
                    bool        checkDictionary = (dictionary != null && dictionary.dataObjects != null && dictionary.dataObjects.Count > 0);
                    List <Node> objectNodes     = root.children;

                    List <string> availTables = new List <string>();

                    foreach (DataObject dbObject in dbObjects)
                    {
                        availTables.Add(dbObject.tableName);

                        Node keyPropertiesNode = new Node()
                        {
                            text     = "Keys",
                            type     = "keys",
                            iconCls  = "folder",
                            expanded = true,
                            children = new List <Node>()
                        };

                        Node dataPropertiesNode = new Node()
                        {
                            text     = "Properties",
                            type     = "properties",
                            iconCls  = "folder",
                            expanded = true,
                            children = new List <Node>()
                        };

                        //Extention Properties___Starts
                        Node extensionPropertiesNode = new Node()
                        {
                            text     = "Extension",
                            type     = "extension",
                            iconCls  = "folder",
                            expanded = true,
                            children = new List <Node>()
                        };
                        //Extention Properties___Ends

                        Node relationshipsNode = new Node()
                        {
                            text     = "Relationships",
                            type     = "relationships",
                            iconCls  = "folder",
                            expanded = true,
                            children = new List <Node>()
                        };

                        //Creating list to contain data and key properties names
                        DataObject    tempDataObject = dictionary.dataObjects.Find(dObj => dObj.objectName == dbObject.objectName);
                        List <string> dataPropertyNamesCollection = new List <string>();
                        List <string> keyPropertyNamesCollection  = new List <string>();

                        if (tempDataObject != null && tempDataObject.dataProperties != null && tempDataObject.dataProperties.Count > 0)
                        {
                            foreach (DataProperty dProp in tempDataObject.dataProperties)
                            {
                                KeyProperty commonProperties = tempDataObject.keyProperties.Find(kProp => kProp.keyPropertyName == dProp.propertyName);

                                if (commonProperties == null)
                                {
                                    dataPropertyNamesCollection.Add(dProp.columnName);
                                }
                                else
                                {
                                    keyPropertyNamesCollection.Add(dProp.columnName);
                                }
                            }
                        }

                        // create object node
                        Node dataObjectNode = new Node()
                        {
                            text     = dbObject.tableName,
                            type     = "dataObject",
                            iconCls  = "treeObject",
                            children = new List <Node>()
                            {
                                keyPropertiesNode, dataPropertiesNode, extensionPropertiesNode, relationshipsNode
                            },
                            properties = new Dictionary <string, object>()
                            {
                                { "keyProperties", keyPropertyNamesCollection }, { "dataProperties", dbObject.dataProperties }, { "aliasDataProperties", dataPropertyNamesCollection }
                            }
                        };

                        DataObject dictObject = null;

                        //
                        // apply what has been configured in dictionary to db object
                        //
                        if (checkDictionary)
                        {
                            dictObject = dictionary.dataObjects.Find(x => x.tableName == dbObject.tableName);
                        }

                        if (dictObject == null)  // has not been configured
                        {
                            dataObjectNode.properties.Add("objectNamespace", ONS_PREFIX + scope + "." + app);
                            dataObjectNode.properties.Add("objectName", dbObject.objectName);
                            dataObjectNode.properties.Add("tableName", dbObject.tableName);
                            dataObjectNode.properties.Add("keyDelimiter", dbObject.keyDelimeter);
                            dataObjectNode.properties.Add("description", dbObject.description);

                            if (dbObject.aliasDictionary != null && dbObject.aliasDictionary.Count > 0)
                            {
                                dataObjectNode.properties.Add("aliasDictionary", dbObject.aliasDictionary["TABLE_NAME_IN"]);
                            }
                        }
                        else  // has been configured, apply object configurations
                        {
                            dataObjectNode.properties.Add("objectNamespace", ONS_PREFIX + scope + "." + app);
                            dataObjectNode.properties.Add("objectName", dictObject.objectName);
                            dataObjectNode.properties.Add("tableName", dictObject.tableName);
                            dataObjectNode.properties.Add("keyDelimiter", dictObject.keyDelimeter);
                            dataObjectNode.properties.Add("description", dictObject.description);

                            if (dictObject.aliasDictionary != null && dictObject.aliasDictionary.Count > 0)
                            {
                                dataObjectNode.properties.Add("aliasDictionary", dictObject.aliasDictionary["TABLE_NAME_IN"]);
                            }

                            // apply relationship configurations
                            foreach (DataRelationship relationship in dictObject.dataRelationships)
                            {
                                Node relationshipNode = new Node()
                                {
                                    text       = relationship.relationshipName,
                                    type       = "relationship",
                                    iconCls    = "relationship",
                                    leaf       = true,
                                    properties = new Dictionary <string, object>()
                                    {
                                        { "name", relationship.relationshipName },
                                        { "type", relationship.relationshipType.ToString() },
                                        { "sourceObject", dictObject.objectName },
                                        { "relatedObject", relationship.relatedObjectName },
                                        { "propertyMaps", relationship.propertyMaps }
                                    }
                                };

                                relationshipsNode.children.Add(relationshipNode);
                            }
                        }

                        foreach (DataProperty dbProperty in dbObject.dataProperties)
                        {
                            if (dictObject != null)
                            {
                                DataProperty dictProperty = dictObject.dataProperties.Find(x => x.columnName == dbProperty.columnName);

                                if (dictProperty != null)   // property has been configured
                                {
                                    Dictionary <string, object> properties = new Dictionary <string, object>()
                                    {
                                        { "columnName", dictProperty.columnName },
                                        { "propertyName", dictProperty.propertyName },
                                        { "aliasDictionary", dictProperty.aliasDictionary != null && dictProperty.aliasDictionary.ContainsKey("COLUMN_NAME_IN") ? dictProperty.aliasDictionary["COLUMN_NAME_IN"] : null },
                                        { "dataType", dictProperty.dataType },
                                        { "dataLength", dictProperty.dataLength },
                                        { "isNullable", dictProperty.isNullable },
                                        { "keyType", dictProperty.keyType },
                                        { "numberOfDecimals", dictProperty.numberOfDecimals },
                                        { "isReadOnly", dictProperty.isReadOnly },
                                        { "showOnIndex", dictProperty.showOnIndex },
                                        { "showOnSearch", dictProperty.showOnSearch },
                                        { "isHidden", dictProperty.isHidden },
                                        { "isVirtual", dictProperty.isVirtual },
                                        { "precision", dictProperty.precision },
                                        { "scale", dictProperty.scale }
                                    };

                                    bool isKey = false;

                                    if (dictObject.isKeyProperty(dictProperty.columnName))
                                    {
                                        Node keyPropertyNode = new Node()
                                        {
                                            text       = dictProperty.columnName,
                                            type       = "keyProperty",
                                            iconCls    = "treeKey",
                                            leaf       = true,
                                            properties = properties
                                        };

                                        keyPropertiesNode.children.Add(keyPropertyNode);
                                        isKey = true;
                                    }
                                    else if (!isKey)
                                    {
                                        Node dataPropertyNode = new Node()
                                        {
                                            text       = dictProperty.columnName,
                                            type       = "dataProperty",
                                            iconCls    = "treeProperty",
                                            leaf       = true,
                                            properties = properties
                                        };

                                        dataPropertiesNode.children.Add(dataPropertyNode);
                                    }
                                }
                            }
                        }

                        //Extension Properties___Starts
                        if (dictObject != null && dictObject.extensionProperties != null)
                        {
                            foreach (ExtensionProperty extProperty in dictObject.extensionProperties)
                            {
                                Dictionary <string, object> properties = new Dictionary <string, object>()
                                {
                                    { "columnName", extProperty.columnName },
                                    { "propertyName", extProperty.propertyName },
                                    { "dataType", extProperty.dataType },
                                    { "dataLength", extProperty.dataLength },
                                    { "isNullable", extProperty.isNullable },
                                    { "keyType", extProperty.keyType },
                                    { "showOnIndex", extProperty.showOnIndex },
                                    { "precision", extProperty.precision },
                                    { "scale", extProperty.scale },
                                    { "definition", extProperty.definition }  //[[By Deepak 12-Dec14,
                                    //{"parameters", extProperty.parameters}//Ends]]
                                };

                                Node extensionPropertyNode = new Node()
                                {
                                    text       = extProperty.columnName,
                                    type       = "extensionProperty",
                                    iconCls    = "treeExtension",
                                    leaf       = true,
                                    properties = properties
                                };

                                extensionPropertiesNode.children.Add(extensionPropertyNode);
                            }
                        }


                        objectNodes.Add(dataObjectNode);

                        List <string> extensionColoumn = new List <string>();
                        foreach (var extension in dbObject.dataProperties)
                        {
                            extensionColoumn.Add(extension.columnName);
                        }
                        dataObjectNode.properties.Add("extensionColoumn", extensionColoumn);
                        //Extension Properties___Ends
                    }

                    foreach (Node dataObjectNode in objectNodes)
                    {
                        dataObjectNode.properties.Add("tableNames", availTables);
                    }
                }

                return(Json(objectsTree));
            }
            catch (Exception e)
            {
                //return Json(new { success = false, message = e.ToString() });
                _logger.Error(e.ToString());
                _CustomErrorLog = new CustomErrorLog();
                _CustomError    = _CustomErrorLog.customErrorLogger(ErrorMessages.errUItree, e, _logger);
                return(Json(new { success = false, message = "[ Message Id " + _CustomError.msgId + "] - " + _CustomError.errMessage, stackTraceDescription = _CustomError.stackTraceDescription }, JsonRequestBehavior.AllowGet));
            }
        }