public void AddGetDeleteSingleEntityTest()
 {
     // Arrange
     ITableManager tableManager = new TableManager(new ConfigManagerHelper());
     const string testTableName = "Test";
     var entity = new DiscoveredKeywordEntity
     {
         PartitionKey = Guid.NewGuid().ToString(),
         RowKey = Guid.NewGuid().ToString(),
         OccurrenceInFeed = 2,
         Text = Guid.NewGuid().ToString(),
         Volume = 10
     };
     // Act
     tableManager.InsertOrMerge(testTableName, entity);
     var entityRetrieved = tableManager.Get<DiscoveredKeywordEntity>(testTableName, entity.PartitionKey, entity.RowKey);
     // Cleanup
     tableManager.Delete(testTableName, entity);
     var entityRetrievedAfterDelete = tableManager.Get<DiscoveredKeywordEntity>(testTableName, entity.PartitionKey, entity.RowKey);
     // Assert
     Assert.IsNotNull(entityRetrieved);
     Assert.IsNull(entityRetrievedAfterDelete);
     Assert.AreEqual(entity.PartitionKey, entityRetrieved.PartitionKey);
     Assert.AreEqual(entity.RowKey, entityRetrieved.RowKey);
     Assert.AreEqual(entity.OccurrenceInFeed, entityRetrieved.OccurrenceInFeed);
     Assert.AreEqual(entity.Volume, entityRetrieved.Volume);
     Assert.AreEqual(entity.Text, entityRetrieved.Text);
 }
    /// <summary>
    /// Generates default form definition.
    /// </summary>
    private void GenerateDefinition()
    {
        // Get info on the class
        var classInfo = DataClassInfoProvider.GetDataClassInfo(QueryHelper.GetInteger("classid", 0));
        if (classInfo == null)
        {
            return;
        }

        var manager = new TableManager(classInfo.ClassConnectionString);

        // Update schema and definition for existing class
        classInfo.ClassXmlSchema = manager.GetXmlSchema(classInfo.ClassTableName);

        var fi = new FormInfo();
        try
        {
            fi.LoadFromDataStructure(classInfo.ClassTableName, manager, true);
        }
        catch (Exception ex)
        {
            // Show error message if something caused unhandled exception
            LogAndShowError("ClassFields", "GenerateDefinition", ex);
            return;
        }

        classInfo.ClassFormDefinition = fi.GetXmlDefinition();
        DataClassInfoProvider.SetDataClassInfo(classInfo);

        URLHelper.Redirect(URLHelper.AddParameterToUrl(RequestContext.CurrentURL, "gen", "1"));
    }
Esempio n. 3
0
        public async Task<HttpResponseMessage> AddCard()
        {
            string requestContent = (string)HttpContext.Current.Items["requestContent"];
            AddCardRequest addCardRequest = JsonConvert.DeserializeObject<AddCardRequest>(requestContent);

            CardEntity card = new CardEntity(addCardRequest);
            TableManager tableManager = new TableManager(DBConfig.CardTableName);
            tableManager.InsertOrReplaceData<UserEntity>(card);
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

            return response;
        }
Esempio n. 4
0
        public async Task<HttpResponseMessage> SignUp()
        {
            string requestContent = (string)HttpContext.Current.Items["requestContent"];
            SignUpRequest registerRequest = JsonConvert.DeserializeObject<SignUpRequest>(requestContent);

            UserEntity user = new UserEntity(registerRequest);
            TableManager tableManager = new TableManager(DBConfig.UserTableName);
            tableManager.InsertOrReplaceData<UserEntity>(user);
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

            return response;
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        lblTableName.ToolTip = GetString("clonning.settings.class.tablename.tooltip");
        lblCloneAlternativeForms.ToolTip = GetString("clonning.settings.class.alternativeform");

        if (!RequestHelper.IsPostBack())
        {
            TableManager tm = new TableManager(null);

            txtTableName.Text = tm.GetUniqueTableName(InfoToClone.GetStringValue("ClassTableName", ""));
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!QueryHelper.ValidateHashString(QueryHelper.GetString("objname", null), QueryHelper.GetString("hash", null)))
        {
            ShowError(GetString("sysdev.views.corruptedparameters"));
            return;
        }

        // Ensure suffix
        UIHelper.SetBreadcrumbsSuffix(GetString("sysdev.view"));

        if (!RequestHelper.IsPostBack())
        {
            drpItems.Items.Add(new ListItem("25", "25"));
            drpItems.Items.Add(new ListItem("100", "100"));
            drpItems.Items.Add(new ListItem("1000", "1000"));
            drpItems.Items.Add(new ListItem(GetString("general.selectall"), "-1"));
        }

        string objName = QueryHelper.GetString("objname", null);

        // Check if edited view exists and redirect to error page if not
        TableManager tm = new TableManager(null);

        if (String.IsNullOrEmpty(objName) || !tm.ViewExists(objName))
        {
            EditedObject = null;
        }

        if (objName != null)
        {
            string top = "";

            int items = ValidationHelper.GetInteger(drpItems.SelectedValue, 25);
            if (items != -1)
            {
                top = "TOP " + items;
            }

            DataSet ds = ConnectionHelper.ExecuteQuery("SELECT " + top + " * FROM " + objName, null, QueryTypeEnum.SQLQuery);

            if (DataHelper.DataSourceIsEmpty(ds))
            {
                lblNoDataFound.Visible = true;
            }
            else
            {
                grdData.DataSource = ds;
                grdData.DataBind();
            }
        }
    }
    /// <summary>
    /// OnAfterSave event handler.
    /// </summary>
    protected void editElem_OnAfterSave(object sender, EventArgs e)
    {
        if (TableNameChanged)
        {
            // Rename existing class table for actual connection string
            TableManager tm = new TableManager(editElem.GetFieldValue("ClassConnectionString").ToString());
            tm.RenameTable(mOldTableName, CurrentClass.ClassTableName);

            // Clear default queries
            QueryInfoProvider.ClearDefaultQueries(CurrentClass, true, true);

            editElem.RedirectUrlAfterSave = URLHelper.AddParameterToUrl(RequestContext.CurrentURL, "tablechanged", "1");
        }
    }
    /// <summary>
    /// Refresh all views.
    /// </summary>
    public void RefresViews()
    {
        if (Views)
        {
            DataSet ds = (DataSet)gridViews.DataSource;
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                TableManager tm = new TableManager(null);

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    tm.RefreshView(ValidationHelper.GetString(dr["TABLE_NAME"], null));
                }
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        lblCloneItems.ToolTip = GetString("clonning.settings.form.tooltip");
        lblCloneAlternativeForms.ToolTip = GetString("clonning.settings.class.alternativeform");

        if (!RequestHelper.IsPostBack())
        {
            DataClassInfo classInfo = DataClassInfoProvider.GetDataClassInfo(InfoToClone.GetIntegerValue("FormClassID", 0));
            if (classInfo != null)
            {
                TableManager tm = new TableManager(null);

                txtTableName.Text = tm.GetUniqueTableName(classInfo.ClassTableName);
            }
        }
    }
    /// <summary>
    /// Generates default form definition.
    /// </summary>
    private void GenerateDefinition()
    {
        // Get info on the class
        DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(QueryHelper.GetInteger("classid", 0));
        if (dci != null)
        {
            TableManager tm = new TableManager(dci.ClassConnectionString);

            // Get the XML schema
            dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName);
            dci.ClassFormDefinition = FormHelper.GetXmlFormDefinitionFromXmlSchema(dci.ClassXmlSchema, true);
            DataClassInfoProvider.SetDataClassInfo(dci);

            URLHelper.Redirect(URLHelper.AddParameterToUrl(RequestContext.CurrentURL, "gen", "1"));
        }
    }
Esempio n. 11
0
 /// <summary>
 /// Adds two new columns (AttendeeOrderId, AttendeePaymentCompleted) to the table Events_Attendee
 /// </summary>
 public static void AddAttendeeTableColumns()
 {
     const string className = "cms.eventattendee";
     const string tableName = "Events_Attendee";
     var dc = DataClassInfoProvider.GetDataClassInfo(className);
     if (dc != null)
     {
         // Add new table columns        
         var tm = new TableManager("CMSConnectionString"); 
         tm.AddTableColumn(tableName, COLUMN_ATTENDEE_ORDERID, "int", true, null);
         tm.AddTableColumn(tableName, COLUMN_ATTENDEE_PAYMENTCOMPLETED, "bit", true, null);
         
         // Update XML schema
         dc.ClassXmlSchema = tm.GetXmlSchema(tableName);
         DataClassInfoProvider.SetDataClassInfo(dc);
         
     }
 }
 public void AddGetDeleteMultipleEntityTest()
 {
     // Arrange
     ITableManager tableManager = new TableManager(new ConfigManagerHelper());
     const string testTableName = "Test";
     var partitionKey = Guid.NewGuid().ToString();
     var entities = new List<DiscoveredKeywordEntity>
     {
         new DiscoveredKeywordEntity
         {
             PartitionKey = partitionKey,
             RowKey = Guid.NewGuid().ToString(),
             OccurrenceInFeed = 2,
             Text = Guid.NewGuid().ToString(),
             Volume = 10
         },
         new DiscoveredKeywordEntity
         {
             PartitionKey = partitionKey,
             RowKey = Guid.NewGuid().ToString(),
             OccurrenceInFeed = 2,
             Text = Guid.NewGuid().ToString(),
             Volume = 10
         }
     };
     // Act
     tableManager.InsertOrMerge<DiscoveredKeywordEntity>(testTableName, entities);
     var entitiesRetrieved = tableManager.Get<DiscoveredKeywordEntity>(testTableName, partitionKey).ToList();
     // Cleanup
     tableManager.Delete<DiscoveredKeywordEntity>(testTableName, entities);
     var entitiesRetrievedAfterDelete = tableManager.Get<DiscoveredKeywordEntity>(testTableName, partitionKey).ToList();
     // Assert
     Assert.AreEqual(entities.Count, entitiesRetrieved.Count());
     Assert.AreEqual(0, entitiesRetrievedAfterDelete.Count());
     for (var x = 0; x < entities.Count; x++)
     {
         Assert.AreEqual(entities[x].PartitionKey, entitiesRetrieved[x].PartitionKey);
         Assert.AreEqual(entities[x].RowKey, entitiesRetrieved[x].RowKey);
         Assert.AreEqual(entities[x].OccurrenceInFeed, entitiesRetrieved[x].OccurrenceInFeed);
         Assert.AreEqual(entities[x].Volume, entitiesRetrieved[x].Volume);
         Assert.AreEqual(entities[x].Text, entitiesRetrieved[x].Text);
     }
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        lblTableName.ToolTip = GetString("clonning.settings.class.tablename.tooltip");
        lblIcons.ToolTip = GetString("clonning.settings.documenttype.icons.tooltip");
        lblCloneAlternativeForms.ToolTip = GetString("clonning.settings.class.alternativeform");

        if (!RequestHelper.IsPostBack())
        {
            TableManager tm = new TableManager(null);

            string originalTableName = InfoToClone.GetStringValue("ClassTableName", "");
            if (string.IsNullOrEmpty(originalTableName))
            {
                plcTableName.Visible = false;
                plcAlternativeForms.Visible = false;
            }
            else
            {
                txtTableName.Text = tm.GetUniqueTableName(InfoToClone.GetStringValue("ClassTableName", ""));
            }
        }
    }
Esempio n. 14
0
    void UpdateLockShowInfo()
    {
        if (m_ShenQiItem == null)
        {
            m_ShowLockInfLable.text = StrDictionary.GetClientDictionaryString("#{4965}", 0, 0);
            return;
        }
        if (m_ShenQiItem.IsValid() == false)
        {
            m_ShowLockInfLable.text = StrDictionary.GetClientDictionaryString("#{4965}", 0, 0);
            return;
        }
        Tab_ShenQiInfo _ShenQiInfo = TableManager.GetShenQiInfoByID(m_ShenQiItem.DataID, 0);

        if (_ShenQiInfo != null)
        {
            m_ShowLockInfLable.text = StrDictionary.GetClientDictionaryString("#{4965}", m_nLockNum, m_nLockNum * _ShenQiInfo.LockNeedItemNum);
        }
        else
        {
            m_ShowLockInfLable.text = StrDictionary.GetClientDictionaryString("#{4965}", 0, 0);
        }
    }
Esempio n. 15
0
    int GetSameBaseSkill(List <int> ownSkillList, int skillid)
    {
        Tab_MasterSkill skillLine = TableManager.GetMasterSkillByID(skillid, 0);

        if (skillLine != null)
        {
            for (int index = 0; index < ownSkillList.Count; index++)
            {
                if (ownSkillList[index] >= 0)
                {
                    Tab_MasterSkill tempLine = TableManager.GetMasterSkillByID(ownSkillList[index], 0);
                    if (tempLine != null)
                    {
                        if (tempLine.BaseSkill == skillLine.BaseSkill)
                        {
                            return(ownSkillList[index]);
                        }
                    }
                }
            }
        }
        return(-1);
    }
Esempio n. 16
0
    public void SetSquadInfor(CObjInfor tObjInfor)
    {
        mID              = tObjInfor.id;
        mSquadCamp       = (SquadCamp)tObjInfor.camp;
        mUnitCount       = tObjInfor.unitcount;
        mHP              = tObjInfor.hp;
        mHPMax           = tObjInfor.maxhp;
        mSquadAttack     = tObjInfor.attack;
        mSquadDefence    = tObjInfor.defence;
        mSp              = tObjInfor.sp;
        mlevel           = tObjInfor.level;
        mBornPosionX     = tObjInfor.posx;
        mBornPosionZ     = tObjInfor.posz;
        mSquadTemplateID = tObjInfor.unitDataId;
        mBornPosionIndex = tObjInfor.arrangeindex;
        Tab_RoleBaseAttr tRoleBaseAttr = TableManager.GetRoleBaseAttrByID(tObjInfor.unitDataId)[0];

        mUnitTemplateID = tRoleBaseAttr.UnitDataID;
        mSkillIDList    = tObjInfor.skilldataid;
        Tab_SkillEx tSkillEx = TableManager.GetSkillExByID(mSkillIDList[0])[0];

        SkillTemplateID = tSkillEx.SkillDataID;
    }
Esempio n. 17
0
    void OnClickShopItem()
    {
        if (null == m_Parent)
        {
            LogModule.ErrorLog("OnClickShopItem::m_Parent null");
            return;
        }
        Tab_SwordsManAttr SwordsManAttrTable = TableManager.GetSwordsManAttrByID(m_SwordsManDataID, 0);

        if (null == SwordsManAttrTable)
        {
            LogModule.ErrorLog("OnClickShopItem::SwordsManAttrTable is null");
            return;
        }
        SwordsMan oSwordsMan = new SwordsMan();

        oSwordsMan.DataId  = m_SwordsManDataID;
        oSwordsMan.Name    = SwordsManAttrTable.Name;
        oSwordsMan.Quality = SwordsManAttrTable.Quality;
        oSwordsMan.Level   = 1;
        SwordsManToolTipsLogic.ShowSwordsManTooltip(oSwordsMan, SwordsManToolTipsLogic.SwordsMan_ShowType.ScoreShop);
        m_Parent.OnShopSwordsManClick(this);
    }
Esempio n. 18
0
    Tab_StoryCopySceneAward GetChapterAwardTab()
    {
        Tab_StoryCopySceneChapter tabChapter = TableManager.GetStoryCopySceneChapterByID(m_ChapterId, 0);

        if (tabChapter == null)
        {
            return(null);
        }

        int nAwardId = GlobeVar.INVALID_ID;

        if (m_AwardIndex < 0 || m_AwardIndex >= tabChapter.getAwardCount())
        {
            return(null);
        }

        nAwardId = tabChapter.GetAwardbyIndex(m_AwardIndex);


        Tab_StoryCopySceneAward tabAward = TableManager.GetStoryCopySceneAwardByID(nAwardId, 0);

        return(tabAward);
    }
Esempio n. 19
0
        public static int isHavebusinessAlert()
        {
            try
            {
                using (DbHelper db = new DbHelper())
                {
                    DateTime serverTime = TableManager.DBServerTime().Date;
                    string   sql        = "select COUNT(1) "
                                          + " from cable as c left join tb_user u on c.userid=u.id and c.userRemindTime<='" + serverTime + "' "
                                          + " left join customer as cu on c.customerid=cu.id where c.isDeleted =@del and u.isdeleted=@del and cu.isdeleted=@del "
                                          + "And Controluserid=@Controluserid";

                    DbParameter[] paramlist = { db.CreateParameter("@del", (int)EnmIsdeleted.使用中), db.CreateParameter("Controluserid", Global.g_userid) };

                    return(Utils.NvInt(db.GetDataSet(sql, paramlist).Tables[0].Rows[0][0].ToString()));
                }
            }
            catch (Exception ex)
            {
                MessageHelper.ShowMessage("E999", "获取电路到期提醒信息失败。");
                return(-1);
            }
        }
Esempio n. 20
0
    public void SetCardTemplateID(int id)
    {
        if (TableManager.GetCardByID(id) == null || TableManager.GetAppearanceByID(TableManager.GetCardByID(id).Appearance) == null)
        {
            Debug.LogError("SetCardTemplateID(), no such template id: " + id);
            return;
        }

        AtlasManager.Instance.setBodyByTempletID(cardIcon, id);
        cardFrame.spriteName = UserCardItem.cardFrameName[TableManager.GetCardByID(id).Star];
        cardFrame.MakePixelPerfect();

        category.spriteName = UserCardItem.elementTypeName[TableManager.GetCardByID(id).Element];
        category.MakePixelPerfect();

        cardBorder.spriteName = UserCardItem.largeCardBorderName[TableManager.GetCardByID(id).Star];
        cardBorder.MakePixelPerfect();

        cardNameBg.spriteName = UserCardItem.largeCardNameBg[TableManager.GetCardByID(id).Star];
        cardNameBg.MakePixelPerfect();

        cardName.text = LanguageManger.GetWords(TableManager.GetAppearanceByID(TableManager.GetCardByID(id).Appearance).Name);
    }
Esempio n. 21
0
 private void LoadCache()
 {
     if (CatLikes.IsEmpty)
     {
         lock (Lock)
         {
             if (CatLikes.IsEmpty)
             {
                 var cats    = GetCats();
                 var catData = TableManager.GetAll <CatEntity>(TableName).ToDictionary(x => x.Id, x => x.Likes);
                 foreach (var cat in cats)
                 {
                     int likes;
                     if (catData.TryGetValue(cat.Id, out likes))
                     {
                         cat.Likes = likes;
                     }
                     CatLikes.TryAdd(cat.Id, cat);
                 }
             }
         }
     }
 }
Esempio n. 22
0
    public UICheckbox checkbox;           //选择标识

    public bool InitTeamMemberLeaderWithCard(UserCardItem card)
    {
        transform.localPosition = new Vector3(0, 0, -1);
        transform.localScale    = new Vector3(1, 1, 1);
        SetMemberItem(card, true);
        //------------------------卡牌背景及外框--------------------------------
        //2013-10-12 Jack Wen
        int icon_star = TableManager.GetCardByID(card.templateID).Star;

        cardIconSpriteFrame.spriteName = UserCardItem.littleCardFrameName[icon_star];
        cardIconSpriteBG.spriteName    = UserCardItem.littleCardBorderName[icon_star];
        //--------------------------------------------------------------------
        spriteSpriteHeader.SetActive(true);
        checkboxCheckmark.spriteName = "xiashi_suo";

        checkboxCheckmark.transform.localPosition = new Vector3(-2, 0, -5);
        checkboxCheckmark.MakePixelPerfect();
        checkbox.isChecked       = true;
        bG.isEnabled             = false;
        spriteSpriteNameBG.alpha = 0.5f;

        return(true);
    }
Esempio n. 23
0
    void ClickSkillBackInfo()
    {
        if (m_ShenQiItem == null)
        {
            return;
        }
        if (m_ShenQiItem.IsEquipMent() == false)
        {
            return;
        }
        int SkillInfIndex = (int)ShenQiDyData.SkillId;

        if (SkillInfIndex >= 0 && SkillInfIndex < m_ShenQiItem.DynamicData.Length)
        {
            Tab_SkillEx _skillEx = TableManager.GetSkillExByID(m_ShenQiItem.DynamicData[(int)ShenQiDyData.SkillId], 0);
            if (_skillEx != null)
            {
                m_ShenQiSkillDecLable.text = _skillEx.SkillDesc;
                m_ShowSkillInfoBackBt.SetActive(false);
                m_ShowSkillInfoNextBt.SetActive(true);
            }
        }
    }
Esempio n. 24
0
    /// <summary>
    /// Returns true if custom settings are valid against given clone setting.
    /// </summary>
    /// <param name="settings">Clone settings</param>
    public override bool IsValid(CloneSettings settings)
    {
        if (!ValidationHelper.IsIdentifier(txtTableName.Text))
        {
            ShowError(GetString("BizForm_Edit.ErrorFormTableNameInIdentifierFormat"));
            return(false);
        }

        if (!ValidationHelper.IsIdentifier(settings.CodeName))
        {
            ShowError(GetString("bizform_edit.errorformnameinidentifierformat"));
            return(false);
        }

        TableManager tm = new TableManager(null);

        if (tm.TableExists(txtTableName.Text))
        {
            ShowError(GetString("sysdev.class_edit_gen.tablenameunique"));
            return(false);
        }
        return(true);
    }
Esempio n. 25
0
    // 添加物品UI
    public void AddItemUI(int nItemID, int nCount)
    {
        Tab_CommonItem Item   = TableManager.GetCommonItemByID(nItemID, 0);
        int            nIndex = m_ItemKind;

        if (null != Item && nCount > 0 && nIndex >= 4 && nIndex < 6)
        {
            m_ItemKind++;
            if (m_Items[nIndex] && m_ItemsDecText[nIndex])
            {
                m_ItemID[nIndex] = nItemID;
                m_Items[nIndex].SetActive(true);
                m_ItemsSprite[nIndex].spriteName        = Item.Icon;
                m_ItemsDecText[nIndex].text             = Item.Name + "*" + nCount.ToString();
                m_ItemsQualitySprite[nIndex].spriteName = GlobeVar.QualityColorGrid[Item.Quality - 1];
                m_ItemDataID[nIndex] = nItemID;
                m_ItemType[nIndex]   = ItemType.ITEM_ITEM;
                m_ItemCount[nIndex]  = nCount;
            }
        }

        m_ItemGrid.repositionNow = true;
    }
Esempio n. 26
0
    void UpdateMasterShopGoodsInfo()
    {
        Utils.CleanGrid(m_MasterShopGrid);

        if (null == m_MasterShopItem)
        {
            return;
        }

        for (int i = 0; i < TableManager.GetMasterShop().Count; i++)
        {
            Tab_MasterShop tabMasterShop = TableManager.GetMasterShopByID(i, 0);
            if (tabMasterShop == null || tabMasterShop.ConsumItemID <= 0 || tabMasterShop.Price <= 0)
            {
                continue;
            }

            if (m_nQingYiItemID <= 0)
            {
                m_nQingYiItemID = tabMasterShop.ConsumItemID;
            }

            // 加载对应商品
            GameObject MasterShopItem = Utils.BindObjToParent(m_MasterShopItem, m_MasterShopGrid, i.ToString());
            if (MasterShopItem == null)
            {
                continue;
            }

            if (null != MasterShopItem.GetComponent <MasterShopItemLogic>())
            {
                MasterShopItem.GetComponent <MasterShopItemLogic>().Init(tabMasterShop);
            }
        }
        m_MasterShopGrid.GetComponent <UIGrid>().Reposition();
        m_MasterShopGrid.GetComponent <UITopGrid>().Recenter(true);
    }
Esempio n. 27
0
    //通过Slot设置兵营数据位置
    public void SetBarrackData(int slot)
    {
        curSlot = slot;
        //获取当前兵营Slot在所有兵营中的index
        Dictionary <int, List <Tab_CityBuildingSlot> > slotDic = TableManager.GetCityBuildingSlot();
        int indx = -1;

        foreach (KeyValuePair <int, List <Tab_CityBuildingSlot> > k in slotDic)
        {
            if (k.Value[0].BuildingType == slotDic[slot][0].BuildingType)
            {
                indx++;
                if (k.Key == slot)
                {
                    break;
                }
            }
        }
        curSlotIndex = indx;

        //获取当前槽位建筑物的Guid
        for (int i = 0; i < playerProxy.city.buildList.Count; i++)
        {
            BuildingVo data = playerProxy.city.buildList [i];
            if (data.slot == curSlot)
            {
                curBuildingGuid = data.guid;
                break;
            }
        }

        SetCurTroopIndex();
        SetCurHeroIndex();

        //更新界面
        EventManager.GetInstance().SendEvent("Private_TroopTrainRefreshAll");
    }
Esempio n. 28
0
        //创建伙伴
        public static void CreateFellowModel(Obj_Init_Data initData)
        {
            if (null == initData)
            {
                return;
            }

            Tab_CabalFellowAttr fellowAttr = TableManager.GetCabalFellowAttrByID(initData.m_RoleBaseID, 0);

            if (null == fellowAttr)
            {
                return;
            }
            //根据ModelId找到CharModel资源
            Tab_CharModel charModel = TableManager.GetCharModelByID(fellowAttr.ModelId, 0);

            if (null == charModel)
            {
                return;
            }
            GameObject fellow = ResourceManager.InstantiateResource("Prefab/Model/FellowRoot", initData.m_ServerID.ToString()) as GameObject;

            if (null != fellow)
            {
                //加载逻辑体,同时异步加载渲染体
                Obj_Fellow objFellow = fellow.AddComponent <Obj_Fellow>();

                if (objFellow && objFellow.Init(initData))
                {
                    objFellow.CanLogic = true;
                    Singleton <ObjManager> .Instance.AddPoolObj(objFellow.ServerID.ToString(), objFellow);
                }
                LoadModelToRoot(fellowAttr.ModelId, EResourceType.CharacterModel, LoadModelComplete, fellow, charModel,
                                null);
                //ReloadModel(fellow, charModel.ResPath, AsycCreateFellowOver, initData);
            }
        }
    /// <summary>
    /// 填充阵型列表
    /// </summary>
    /// <param name="item"></param>
    public void FillMatrixList()
    {
        if (null == m_belleMatrixItem)
        {
            LogModule.ErrorLog("m_belleMatrixItem is not found!");
        }

        for (int i = 0; i < TableManager.GetBelleMatrix().Count; i++)
        {
            Tab_BelleMatrix belleMatrixTab = TableManager.GetBelleMatrixByID(i, 0);
            if (null == belleMatrixTab)
            {
                continue;
            }

            GameObject curItem = Utils.BindObjToParent(m_belleMatrixItem, m_matrixGrid);
            if (curItem != null && curItem.GetComponent <BelleMatrixInfoItem>() != null)
            {
                curItem.GetComponent <BelleMatrixInfoItem>().SetData(this, i, belleMatrixTab);
            }
        }

        m_matrixGrid.GetComponent <UICabalGrid>().repositionNow = true;

        Transform curMatrix = m_matrixGrid.transform.FindChild("0");

        if (null != curMatrix)
        {
            m_curSelectMatrix = curMatrix.GetComponent <BelleMatrixInfoItem>();
            if (m_curSelectMatrix != null)
            {
                m_curSelectMatrix.SetClickHighLight(true);
            }

            ShowMatrixByItem();
        }
    }
Esempio n. 30
0
        private void BtnAdd_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            RequestManager.getInstance().showLoading();
            Action <NetworkResponse> cbSuccessSent =
                delegate(NetworkResponse networkResponse) {
                if (!networkResponse.Successful)
                {
                    WindownsManager.getInstance().showMessageBoxSomeThingWrong();
                }
                else
                {
                    reloadLVTable();
                }
                RequestManager.getInstance().hideLoading();
            };

            Action <string> cbError =
                delegate(string err) {
                WindownsManager.getInstance().showMessageBoxErrorNetwork();
                RequestManager.getInstance().hideLoading();
            };
            var tableIdCreate = 0;

            while (true)
            {
                if (!TableManager.getInstance().TableList.ContainsKey(tableIdCreate))
                {
                    break;
                }
                tableIdCreate++;
            }
            TableManager.getInstance().createTableFromServerAndUpdate(
                tableIdCreate,
                cbSuccessSent,
                cbError
                );
        }
Esempio n. 31
0
    public void InitAutoFight()
    {
        m_HpItemCDPic.fillAmount = 1;
        m_MpItemCDPic.fillAmount = 1;
//         HpItemCDTime = 0;
//         HpItemCDTime = 0;
        GameItemContainer BackPack = GameManager.gameManager.PlayerDataPool.BackPack;
        Obj_MainPlayer    User     = Singleton <ObjManager> .Instance.MainPlayer;

        if (User)  //更新信息
        {
            if (User.AutoHpID != -1)
            {
                Tab_CommonItem curItem = TableManager.GetCommonItemByID(User.AutoHpID, 0);
                if (curItem != null)
                {
                    if (BackPack.GetItemCountByDataId(User.AutoHpID) <= 0)
                    {
                        m_HpItemCDPic.fillAmount = 1;
                        GameManager.gameManager.PlayerDataPool.HpItemCDTime = 0;
                    }
                }
            }
            if (User.AutoMpID != -1)
            {
                Tab_CommonItem curItem = TableManager.GetCommonItemByID(User.AutoMpID, 0);
                if (curItem != null)
                {
                    if (BackPack.GetItemCountByDataId(User.AutoMpID) <= 0)
                    {
                        m_MpItemCDPic.fillAmount = 1;
                        GameManager.gameManager.PlayerDataPool.MpItemCDTime = 0;
                    }
                }
            }
        }
    }
Esempio n. 32
0
        private void ItemAddTag_Click(object sender, EventArgs e)
        {
            try
            {
                if (treeViewSI.SelectedNode == null)
                {
                    return;
                }

                Server     chCurrent = objServerManager.GetBySQLServerName(treeViewSI.SelectedNode.Parent.Parent.Text);
                DataBase   dvCurrent = DataBaseManager.GetByDataBaseName(chCurrent, treeViewSI.SelectedNode.Parent.Text);
                Table      dbCurrent = TableManager.GetByTableName(dvCurrent, treeViewSI.SelectedNode.Text);
                XAddColumn tgFrm     = new XAddColumn(chCurrent, dvCurrent, dbCurrent);
                tgFrm.eventColumnChanged += tg =>
                {
                    try
                    {
                        DGMonitorForm.Rows.Clear();
                        foreach (Column item in dbCurrent.Columns)
                        {
                            string[] row = { string.Format("{0}", item.ColumnId), item.ColumnName, item.TagName, item.DataBlock, item.Device, item.Channel, item.Cycle, item.Description };

                            DGMonitorForm.Rows.Add(row);
                        }
                    }
                    catch (Exception ex)
                    {
                        EventscadaException?.Invoke(GetType().Name, ex.Message);
                    }
                };
                tgFrm.ShowDialog();
            }
            catch (Exception ex)
            {
                EventscadaException?.Invoke(GetType().Name, ex.Message);
            }
        }
Esempio n. 33
0
        //行走状态处理
        void ProcessDeathAnimState()
        {
            if (AnimLogic != null && m_Objanimation != null)
            {
                //是否在播放动作
                if (m_Objanimation.isPlaying && AnimLogic.CurAnimData != null)
                {
                    //击飞是不播死亡动画
                    if (AnimLogic.CurAnimData.AnimID != (int)CharacterDefine.CharacterAnimId.Knockback_01 &&
                        AnimLogic.CurAnimData.AnimID != (int)CharacterDefine.CharacterAnimId.Knockback_02)
                    {
                        m_AnimLogic.Stop();
                        m_AnimLogic.Play((int)(CharacterDefine.CharacterAnimId.Die));
                    }
                }
                else
                {
                    m_AnimLogic.Stop();
                    m_AnimLogic.Play((int)(CharacterDefine.CharacterAnimId.Die));
                }
            }
            Tab_RoleBaseAttr roleBaseAttr = TableManager.GetRoleBaseAttrByID(BaseAttr.RoleBaseID, 0);

            if (roleBaseAttr != null)
            {
                Tab_CharModel charModel = TableManager.GetCharModelByID(roleBaseAttr.CharModelID, 0);
                if (charModel != null)
                {
                    int nDeadSoundCount = charModel.getDeadSoundCount();
                    int nRandNum        = Random.Range(0, nDeadSoundCount - 1);
                    if (charModel.GetDeadSoundbyIndex(nRandNum) >= 0)
                    {
                        PlaySoundAtPos(ObjType, charModel.GetDeadSoundbyIndex(nRandNum), Position);
                    }
                }
            }
        }
Esempio n. 34
0
    // 增加购买物品
    void onClickBuyAddItem()
    {
        Tab_PvpShop tabPvp = TableManager.GetPvpShopByID(m_BuyPvpId, 0);

        if (tabPvp == null)
        {
            return;
        }

        Tab_CommonItem tabCommonItem = TableManager.GetCommonItemByID(tabPvp.ItemId, 0);

        if (tabCommonItem == null)
        {
            return;
        }

        //int count = GameManager.gameManager.PlayerDataPool.PvpShopItemBuyNum[tabPvp.ItemId];
        if (GameManager.gameManager.PlayerDataPool.PvpShopItemBuyNum.ContainsKey(tabPvp.ItemId))
        {
            if (m_BuyItemNum + 1 <= GameManager.gameManager.PlayerDataPool.PvpShopItemBuyNum[tabPvp.ItemId])
            {
                int cellprice = 0;
                if (m_BuyItemNum == 0)
                {
                    cellprice = int.Parse(m_BuyItemPrice.text);
                }
                else
                {
                    cellprice = int.Parse(m_BuyItemPrice.text) / m_BuyItemNum;
                }

                m_BuyItemNum       += 1;
                m_BuyItemCount.text = m_BuyItemNum.ToString();
                m_BuyItemPrice.text = (cellprice * m_BuyItemNum).ToString();
            }
        }
    }
    //相应刮卡点击事件
    void OnGGLClick(GameObject cardBtn)
    {
        if (bLock)
        {
            return;
        }

        //点击单个卡牌时判断是否已经翻开可点
        if (nCountShowCardNum < 9 && ChechIFCardOpen(cardBtn))
        {
            return;
        }

        //全部翻开时,点击重置
        if (nCountShowCardNum >= 9)
        {
            this.ResetCard();
            return;
        }

        curTouchCard = cardBtn;

        //刚开始时的提示
        if (!CheckIfCanFree() && CheckIfCardsAreUnopen())
        {
            if (bTodayTip)
            {
                int cost = TableManager.GetScratchCostByID(2).Cost;
                BoxManager.showMessageByID((int)MessageIdEnum.Msg177, cost.ToString());
                UIEventListener.Get(BoxManager.getYesButton()).onClick += processTouchCard;

                return;
            }
        }

        processTouchCard(curTouchCard);
    }
Esempio n. 36
0
        public void HandlePacket(GC_SYNC_STORYCOPYSCENEAWARDINFO packet)
        {
            for (int i = 0; i < packet.nStoryCopySceneChapterIDCount; i++)
            {
                StoryCopySceneChapterInfo info;
                info.m_nID = packet.GetNStoryCopySceneChapterID(i);
                if (info.m_nID <= 0)
                {
                    continue;
                }

                info.m_bAwardGot = new List <bool>();
                for (int j = i * ChapterLevelNum; j < (i + 1) * ChapterLevelNum && j < packet.nAwardGotCount; j++)
                {
                    info.m_bAwardGot.Add(packet.nAwardGotList[j] == 1);
                }

                info.m_bLevelAwardGot = new List <bool>();
                for (int j = i * (ChapterLevelNum - 1); j < (i + 1) * (ChapterLevelNum - 1) && j < packet.LevelAwardGotCount; j++)
                {
                    info.m_bLevelAwardGot.Add(packet.LevelAwardGotList[j] == 1);
                }

                info._ContaindLevelList = new List <int>();
                var storyCopySceneDic = TableManager.GetStoryCopyScene();
                foreach (var pair in storyCopySceneDic)
                {
                    if (pair.Value != null && pair.Value.Count != 0 && pair.Value[0].BelongToChapterID == info.m_nID)
                    {
                        info._ContaindLevelList.Add(pair.Value[0].Id);
                    }
                }
                m_ChapterInfoDic[info.m_nID] = info;
            }
            // 通知界面
            Messenger.Broadcast(MessengerConst.OnUpdateJuQingCopySceneChapterInfo);
        }
Esempio n. 37
0
        public ActionResult Index(FormCollection collection, HttpPostedFileBase file)
        {
            foreach (string files in Request.Files)
            {
                file = Request.Files[files];
            }
            string Firstname = collection[Constants.FirstName];
            string LastName  = collection[Constants.LastName];
            string Address   = collection[Constants.Address];

            if (!String.IsNullOrEmpty(Firstname) && !String.IsNullOrEmpty(LastName))
            {
                BlobManager blobManager     = new BlobManager(Constants.ContainerName);
                string      FileAbsoluteUri = blobManager.UploadFile(file);
                ChiragInfo  employee        = new ChiragInfo(Firstname, LastName);
                employee.Email     = collection[Constants.Email];
                employee.Number    = collection[Constants.PhoneNumber];
                employee.Address   = Address;
                employee.ResumeUrl = FileAbsoluteUri;
                TableManager tableManager = new TableManager(Constants.TableName);
                ChiragInfo   emp          = tableManager.InsertOrMergeEntity(employee);
                if (emp == null)
                {
                    ViewBag.TableError = Constants.TableError;
                    return(View());
                }
                if (String.IsNullOrEmpty(FileAbsoluteUri))
                {
                    ViewBag.BlobError = Constants.BlobError;
                    return(View());
                }
                TempData["SuccessMsg"] = "Details of " + emp.PartitionKey + " " + emp.RowKey + " Uploaded Successfully";
                return(RedirectToAction("GetMyData"));
            }
            ViewBag.RequiredError = Constants.RequiredError;
            return(View());
        }
Esempio n. 38
0
    /*
     * 获得副本剩余可购买次数,包括剧情幅本
     */
    public static int GetVipCopySceneRemainBuyNum(int sceneid, bool bIsSingle)
    {
        Tab_VipBook pVipBook = TableManager.GetVipBookByID(GetVipLv(), 0);

        if (pVipBook == null)
        {
            return(GlobeVar.INVALID_ID);
        }

        if (GCGame.Utils.GetSceneType(sceneid) == (int)Games.GlobeDefine.GameDefine_Globe.SCENE_TYPE.SCENETYPE_STORYCOPYSCENE)
        {
            return(GameManager.gameManager.PlayerDataPool.CommonData.GetCommonData((int)Games.UserCommonData.USER_COMMONDATA.CD_VIP_STORY_COPYSCENE));
        }
        else if (GCGame.Utils.GetSceneType(sceneid) == (int)Games.GlobeDefine.GameDefine_Globe.SCENE_TYPE.SCENETYPE_COPYSCENE)
        {
            if (pVipBook.getBuyCountCount() != s_nVipCopySceneArray.Length)
            {
                return(0);
            }
            if (bIsSingle)
            {
                for (int i = 0; i < pVipBook.getSceneIdCount(); ++i)
                {
                    if (pVipBook.GetSceneIdbyIndex(i) == sceneid)
                    {
                        return(GameManager.gameManager.PlayerDataPool.CommonData.GetCommonData(s_nVipCopySceneArray[i]));
                    }
                }
            }
            else
            {
                //这里还没有找到场景,去组队幅本里找
                return(GetVipTeamCopySceneNum(sceneid));
            }
        }
        return(GlobeVar.INVALID_ID);
    }
Esempio n. 39
0
    void TrainingSubmitClick()
    {
        if (m_TrainingExp <= GameManager.gameManager.PlayerDataPool.CommonData.GetCommonData((int)Games.UserCommonData.USER_COMMONDATA.CD_TRAINING_EXP))
        {
            GUIData.AddNotifyData("#{5537}");
            return;
        }

        Tab_TrainingBook tabTraining = TableManager.GetTrainingBookByID(m_TrainingLevel, 0);

        if (tabTraining == null)
        {
            return;
        }

        Tab_TrainingBook tabNextTraining = TableManager.GetTrainingBookByID(m_TrainingLevel + 1, 0);

        if (tabNextTraining == null)
        {
            return;
        }

        if (m_TrainingExp >= tabTraining.Cost && tabNextTraining.Branch != GlobeVar.INVALID_ID)
        {
            if (m_ChoosePoint != m_TrainingLevel + 1 && m_ChoosePoint != tabNextTraining.Branch)
            {
                GUIData.AddNotifyData("#{5540}");
                return;
            }

            MessageBoxLogic.OpenOKCancelBox(StrDictionary.GetClientDictionaryString("#{5509}"), null, TrainingOK);
        }
        else
        {
            MessageBoxLogic.OpenOKCancelBox(StrDictionary.GetClientDictionaryString("#{5509}"), null, TrainingOK);
        }
    }
Esempio n. 40
0
    void SetEnchanceAndStarAttr(GameItem item, int index, float attr, bool extraAddAttr = false)
    {
        int EnchanceAndStarValue = 0;

        //强化属性
        if (item.EnchanceLevel > 0)
        {
            Tab_EquipEnchance enchanceline = TableManager.GetEquipEnchanceByID(item.EnchanceLevel, 0);
            if (enchanceline != null)
            {
                float rate = enchanceline.EnchanceRate;
                if (rate > 0)
                {
                    EnchanceAndStarValue += (int)(attr * rate) + 1;
                }
            }
        }
        //打星属性
        if (item.StarLevel > 0 && extraAddAttr == false)
        {
            Tab_EquipStar starline = TableManager.GetEquipStarByID(item.StarLevel, 0);
            if (starline != null)
            {
                float rate = starline.AttrRate;
                if (rate > 0)
                {
                    EnchanceAndStarValue += (int)(attr * rate) + 1;
                }
            }
        }
        if (EnchanceAndStarValue > 0)
        {
            m_EnchanceAttr[index].text = string.Format("+{0}", EnchanceAndStarValue);
            m_EnchanceAttr[index].gameObject.SetActive(true);
        }
    }
Esempio n. 41
0
        //GET api/Poster?n={movie name}
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();

            try
            {
                var tableMgr = new TableManager();

                // get query string parameters
                var qpParams = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);

                if (string.IsNullOrEmpty(qpParams["n"]))
                {
                    throw new ArgumentException(Constants.API_EXC_MOVIE_NAME_NOT_EXIST);
                }

                string movieUniqueName = qpParams["n"].ToString();

                //get movie object by movie's unique name
                var movie = tableMgr.GetMovieByUniqueName(movieUniqueName);

                if (movie != null)
                {
                    // if movie is not null then return poster string (in json)
                    return(movie.Posters);
                }
            }
            catch (Exception ex)
            {
                // if any error occured then return User friendly message with system error message
                return(json.Serialize(new { Status = "Error", UserMessage = Constants.UM_WHILE_SEARCHING_MOVIES_POSTER, ActualError = ex.Message }));
            }

            // if movie is null then return single object.
            return(string.Empty);
        }
Esempio n. 42
0
    void Start()
    {
        var tableManager = new TableManager();

        tableManager.Initialize();

        var userManager = new UserManager();

        userManager.Initialize(new UserManagerInitData()
        {
            TableManager = tableManager,
            CardListSO   = CardListSO
        });
        //userManager.Load();

        var startScene = GenericPrefab.Instantiate <MainScene>();

        startScene.Initialize(new MainSceneInitData()
        {
            TableManager = tableManager,
            UserManager  = userManager,
            CardListSO   = CardListSO
        });
    }
Esempio n. 43
0
    // 创建坐骑 fakeobj
    private bool CreateMountFakeObj(int nCurMountID)
    {
        if (null != m_MountFakeObj)
        {
            DestroyMountFakeObj();
        }
        Tab_MountBase MountBase = TableManager.GetMountBaseByID(nCurMountID, 0);

        if (MountBase == null)
        {
            return(false);
        }

        Tab_CharMount MountTable = TableManager.GetCharMountByID(MountBase.ModelID, 0);

        if (MountTable == null)
        {
            return(false);
        }

        m_MountFakeObj = new FakeObject();
        if (m_MountFakeObj == null)
        {
            return(false);
        }

        if (false == m_MountFakeObj.initFakeObject(MountTable.FakeObjID, GameManager.gameManager.ActiveScene.FakeObjTrans))
        {
            return(false);
        }
        m_ModelDrag.ModelTrans = m_MountFakeObj.ObjAnim.transform;

        GameManager.gameManager.ActiveScene.InitFakeObjRoot(m_FakeObjTopLeft, m_FakeObjBottomRight);
        GameManager.gameManager.ActiveScene.ShowFakeObj();
        return(true);
    }
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (!BizFormInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.BizForms, ObjectActionEnum.Insert))
        {
            ShowError(GetString("LicenseVersion.BizForm"));
            return;
        }

        DataClassInfo dci = null;
        BizFormInfo bizFormObj = null;

        string errorMessage = new Validator().NotEmpty(txtFormDisplayName.Text, rfvFormDisplayName.ErrorMessage).
            NotEmpty(txtFormName.Text, rfvFormName.ErrorMessage).
            NotEmpty(txtTableName.Text, rfvTableName.ErrorMessage).
            IsIdentifier(txtFormName.Text, GetString("bizform_edit.errorformnameinidentifierformat")).
            IsIdentifier(txtTableName.Text, GetString("BizForm_Edit.ErrorFormTableNameInIdentifierFormat")).Result;

        if (String.IsNullOrEmpty(errorMessage))
        {
            using (var tr = new CMSTransactionScope())
            {
                // Prepare the values
                string formDisplayName = txtFormDisplayName.Text.Trim();

                bizFormObj = new BizFormInfo();
                bizFormObj.FormDisplayName = formDisplayName;
                bizFormObj.FormName = txtFormName.Text.Trim();
                bizFormObj.FormSiteID = SiteContext.CurrentSiteID;
                bizFormObj.FormEmailAttachUploadedDocs = true;
                bizFormObj.FormItems = 0;
                bizFormObj.FormClearAfterSave = false;
                bizFormObj.FormLogActivity = true;

                // Ensure the code name
                bizFormObj.Generalized.EnsureCodeName();

                // Table name is combined from prefix ('BizForm_<sitename>_') and custom table name
                string safeFormName = ValidationHelper.GetIdentifier(bizFormObj.FormName);
                bizFormObj.FormName = safeFormName;

                string className = bizFormNamespace + "." + safeFormName;

                // Generate the table name
                string tableName = txtTableName.Text.Trim();
                if (String.IsNullOrEmpty(tableName) || (tableName == InfoHelper.CODENAME_AUTOMATIC))
                {
                    tableName = safeFormName;
                }
                tableName = FormTablePrefix + tableName;

                TableManager tm = new TableManager(null);

                // TableName wont be longer than 60 letters and will be unique
                if (tableName.Length > 60)
                {
                    int x = 1;

                    while (tm.TableExists(tableName.Substring(0, 59) + x.ToString()))
                    {
                        x++;
                    }

                    tableName = tableName.Substring(0, 59) + x.ToString();
                }

                // If first letter of safeFormName is digit, add "PK" to beginning
                string primaryKey = BizFormInfoProvider.GenerateFormPrimaryKeyName(bizFormObj.FormName);

                try
                {
                    // Create new table in DB
                    tm.CreateTable(tableName, primaryKey);
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;

                    // Table with the same name already exists
                    ShowError(string.Format(GetString("bizform_edit.errortableexists"), tableName));
                    return;
                }

                // Change table owner
                try
                {
                    string owner = SqlHelper.GetDBSchema(SiteContext.CurrentSiteName);
                    if ((!String.IsNullOrEmpty(owner)) && (owner.ToLowerCSafe() != "dbo"))
                    {
                        tm.ChangeDBObjectOwner(tableName, owner);
                        tableName = owner + "." + tableName;
                    }
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("BIZFORM_NEW", "E", ex);
                }

                // Convert default datetime to string in english format
                string defaultDateTime = DateTime.Now.ToString(CultureHelper.EnglishCulture.DateTimeFormat);

                try
                {
                    // Add FormInserted and FormUpdated columns to the table
                    tm.AddTableColumn(tableName, "FormInserted", "datetime", false, defaultDateTime);
                    tm.AddTableColumn(tableName, "FormUpdated", "datetime", false, defaultDateTime);
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;

                    // Column wasn't added successfully
                    ShowError(errorMessage);

                    return;
                }

                // Create the BizForm class
                dci = BizFormInfoProvider.CreateBizFormDataClass(className, formDisplayName, tableName, primaryKey);

                try
                {
                    // Create new bizform dataclass
                    using (CMSActionContext context = new CMSActionContext())
                    {
                        // Disable logging of tasks
                        context.DisableLogging();

                        // Set default search settings
                        dci.ClassSearchEnabled = true;

                        DataClassInfoProvider.SetDataClassInfo(dci);

                        // Create default search settings
                        dci.ClassSearchSettings = SearchHelper.GetDefaultSearchSettings(dci);
                        dci.ClassSearchCreationDateColumn = "FormInserted";
                        DataClassInfoProvider.SetDataClassInfo(dci);
                    }
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;

                    // Class with the same name already exists
                    ShowError(errorMessage);

                    return;
                }

                // Create new bizform
                bizFormObj.FormClassID = dci.ClassID;

                try
                {
                    // Create new bizform
                    BizFormInfoProvider.SetBizFormInfo(bizFormObj);
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;

                    ShowError(errorMessage);

                    return;
                }

                tr.Commit();

                if (String.IsNullOrEmpty(errorMessage))
                {
                    // Redirect to Form builder tab
                    string url = UIContextHelper.GetElementUrl("CMS.Form", "Forms.Properties", false, bizFormObj.FormID);
                    url = URLHelper.AddParameterToUrl(url, "tabname", "Forms.FormBuldier");
                    URLHelper.Redirect(url);
                }
            }
        }
        else
        {
            ShowError(errorMessage);
        }
    }
    public static void Update60()
    {
        EventLogProvider evp = new EventLogProvider();
        evp.LogEvent("I", DateTime.Now, "Upgrade to 6.0", "Upgrade - Start");

        DataClassInfo dci = null;

        #region "CMS.UserSettings"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("cms.usersettings");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "UserAuthenticationGUID";
                    ffi.DataType = FormFieldDataTypeEnum.GUID;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "UserBounces";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.TextBoxControl;
                    ffi.Visible = false;
                    ffi.Caption = "UserBounces";

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "UserLinkedInID";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 100;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "UserLogActivities";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "UserPasswordRequestHash";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 100;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("CMS_UserSettings");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("CMS_UserSettings");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("CMS.UserSettings - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - Customer"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.customer");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "CustomerSiteID";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.TextBoxControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    TableManager tm = new TableManager(dci.ClassConnectionString);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_Customer");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);

                    tm.RefreshCustomViews("COM_Customer");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.Customer - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - Order"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.order");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "OrderCulture";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 10;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderIsPaid";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderTotalPriceInMainCurrency";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = fi.GetFormField("OrderStatusID");
                    if (ffi != null)
                    {
                        ffi.AllowEmpty = true;
                        fi.UpdateFormField("OrderStatusID", ffi);
                    }

                    ffi = fi.GetFormField("OrderShippingAddressID");
                    if (ffi != null)
                    {
                        ffi.AllowEmpty = true;
                        fi.UpdateFormField("OrderShippingAddressID", ffi);
                    }

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_Order");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("COM_Order");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.Order - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - OrderItem"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.orderitem");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemBundleGUID";
                    ffi.DataType = FormFieldDataTypeEnum.GUID;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemIsPrivate";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemPrice";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemSendNotification";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemSKU";
                    ffi.DataType = FormFieldDataTypeEnum.LongText;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemText";
                    ffi.DataType = FormFieldDataTypeEnum.LongText;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemTotalPriceInMainCurrency";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemValidTo";
                    ffi.DataType = FormFieldDataTypeEnum.DateTime;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_OrderItem");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("COM_OrderItem");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.OrderItem - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - Shopping cart item"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.shoppingcartitem");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "CartItemBundleGUID";
                    ffi.DataType = FormFieldDataTypeEnum.GUID;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "CartItemIsPrivate";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "CartItemPrice";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "CartItemText";
                    ffi.DataType = FormFieldDataTypeEnum.LongText;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "CartItemValidTo";
                    ffi.DataType = FormFieldDataTypeEnum.DateTime;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = fi.GetFormField("CartItemGuid");
                    if (ffi != null)
                    {
                        ffi.AllowEmpty = true;
                        fi.UpdateFormField("CartItemGuid", ffi);
                    }

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_ShoppingCartSKU");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("COM_ShoppingCartSKU");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.ShoppingCartItem - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - SKU"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.sku");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "SKUBundleInventoryType";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 50;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUConversionName";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 100;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUConversionValue";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 200;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMaxDownloads";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMaxItemsInOrder";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMaxPrice";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMembershipGUID";
                    ffi.DataType = FormFieldDataTypeEnum.GUID;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMinPrice";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUNeedsShipping";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUPrivateDonation";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUProductType";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 50;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUSiteID";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUValidFor";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUValidity";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 50;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUValidUntil";
                    ffi.DataType = FormFieldDataTypeEnum.DateTime;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = fi.GetFormField("SKUDepartmentID");
                    if (ffi != null)
                    {
                        ffi.AllowEmpty = true;
                        fi.UpdateFormField("SKUDepartmentID", ffi);
                    }

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_SKU");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("COM_SKU");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.SKU - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Community - Group"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("Community.Group");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "GroupLogActivity";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.CheckBoxControl;
                    ffi.Visible = true;
                    ffi.DefaultValue = "true";
                    ffi.Caption = "GroupLogActivity";

                    fi.AddFormField(ffi);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("Community_Group");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("Community_Group");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Community.Group - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Newsletter - Subscriber"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("newsletter.subscriber");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "SubscriberBounces";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("Newsletter_Subscriber");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("Newsletter_Subscriber");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Newsletter.Subscriber - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "CMS.Document"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("cms.document");
            if (dci != null)
            {
                SearchSettings ss = dci.ClassSearchSettingsInfos;
                SearchSettingsInfo ssi = ss.GetSettingsInfo("42f446ee-9818-4596-8124-54a38f64aa05");
                if (ssi != null)
                {
                    ssi.Searchable = true;
                    ss.SetSettingsInfo(ssi);
                }

                DataClassInfoProvider.SetDataClass(dci);
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("CMS.Document - Upgrade", "Upgrade", ex);
        }

        #endregion

        // Set the path to the upgrade package
        mUpgradePackagePath = HttpContext.Current.Server.MapPath("~/CMSSiteUtils/Import/upgrade_55R2_60.zip");

        mWebsitePath = HttpContext.Current.Server.MapPath("~/");

        TableManager dtm = new TableManager(null);

        // Update all views
        dtm.RefreshDocumentViews();

        // Set data version
        ObjectHelper.SetSettingsKeyValue("CMSDataVersion", "6.0");

        // Clear hashtables
        CMSObjectHelper.ClearHashtables();

        // Clear the cache
        CacheHelper.ClearCache(null, true);

        // Drop the routes
        CMSMvcHandler.DropAllRoutes();

        // Init the Mimetype helper (required for the Import)
        MimeTypeHelper.LoadMimeTypes();

        CMSThread thread = new CMSThread(Upgrade60Import);
        thread.Start();
    }
    /// <summary>
    /// Initializes the controls. Returns false if parsing code of existing view/procedure failed.
    /// </summary>
    private bool SetupControl(string objectCreateCode, string indexesCreateCode)
    {
        bool result = true;

        if (!String.IsNullOrEmpty(ObjectName) && String.IsNullOrEmpty(objectCreateCode))
        {
            if (IsView != null)
            {
                var tm = new TableManager(null);

                objectCreateCode = tm.GetCode(ObjectName);

                DataSet indexesDs = tm.GetIndexes(ObjectName);
                if (!DataHelper.DataSourceIsEmpty(indexesDs))
                {
                    indexesCreateCode =
                        indexesDs.Tables[0].Rows
                            .Cast<DataRow>()
                            .Select(dr => ValidationHelper.GetString(dr["CreateScript"], "").Trim())
                            .ToArray().Join(Environment.NewLine + Environment.NewLine);
                }
            }
        }

        if (IsView == true)
        {
            chkWithBinding.Visible = true;
            plcGenerate.Visible = true;

            if (objectCreateCode == null)
            {
                lblCreateLbl.Text = "CREATE VIEW " + (!SystemContext.DevelopmentMode ? VIEW_CUSTOM_PREFIX : String.Empty);
                plcGenerate.Visible = true;

                State = SqlEditModeEnum.CreateView;
            }
            else
            {
                lblCreateLbl.Text = "ALTER VIEW";
                plcGenerate.Visible = false;

                string name, body;
                bool withbinding;
                result = ParseView(objectCreateCode, out name, out body, out withbinding);

                txtObjName.Enabled = false;
                txtObjName.ReadOnly = true;
                if (result)
                {
                    txtObjName.Text = name.Trim();
                    txtSQLText.Text = body.Trim();
                }
                if (!string.IsNullOrEmpty(indexesCreateCode))
                {
                    txtIndexes.Text = indexesCreateCode.Trim();
                }

                chkWithBinding.Checked = withbinding;

                State = SqlEditModeEnum.AlterView;
            }

            plcParams.Visible = false;
            chkWithBinding_CheckedChanged(null, null);

            lblBegin.Text = "AS";
        }
        else
        {
            if (objectCreateCode == null)
            {
                lblCreateLbl.Text = "CREATE PROCEDURE " + (!SystemContext.DevelopmentMode ? PROCEDURE_CUSTOM_PREFIX : String.Empty);
                plcGenerate.Visible = true;
                State = SqlEditModeEnum.CreateProcedure;
            }
            else
            {
                plcGenerate.Visible = false;
                lblCreateLbl.Text = "ALTER PROCEDURE";
                string name, param, body;
                result = ParseProcedure(objectCreateCode, out name, out param, out body);
                txtObjName.Enabled = false;
                txtObjName.ReadOnly = true;
                if (result)
                {
                    txtObjName.Text = name.Trim();
                    txtParams.Text = param.Trim();
                    txtSQLText.Text = body.Trim();
                }
                State = SqlEditModeEnum.AlterProcedure;
            }
            plcParams.Visible = true;
            lblBegin.Text = "AS<br/>BEGIN";
            lblEnd.Text = "END";
        }

        if (!result)
        {
            // Parsing code failed => disable all controls
            DisableControl(txtObjName);
            DisableControl(txtParams);
            txtSQLText.EditorMode = EditorModeEnum.Basic;
            DisableControl(txtSQLText);
            btnGenerate.Enabled = false;

            ShowWarning(GetString((IsView == true) ? "systbl.view.parsingfailed" : "systbl.proc.parsingfailed"));
        }

        FailedToLoad = !result;
        return result;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Query param validation
        string hash = QueryHelper.GetString("hash", null);

        string paramName = "new";
        string newView = QueryHelper.GetString(paramName, null);
        if (String.IsNullOrEmpty(newView))
        {
            paramName = "objname";
        }

        if (!QueryHelper.ValidateHashString(QueryHelper.GetString(paramName, null), hash))
        {
            ShowError(GetString("sysdev.views.corruptedparameters"));
            editSQL.Visible = false;
            return;
        }

        if (QueryHelper.GetInteger("saved", 0) == 1)
        {
            ShowChangesSaved();
        }

        objName = QueryHelper.GetString("objname", null);

        TableManager tm = new TableManager(null);

        if (!String.IsNullOrEmpty(objName) && !tm.StoredProcedureExists(objName))
        {
            EditedObject = null;
        }

        // Init edit area
        editSQL.ObjectName = objName;
        editSQL.HideSaveButton = objName != null;
        editSQL.IsView = false;
        editSQL.OnSaved += editSQL_OnSaved;
        bool loadedCorrectly = true;
        if (!RequestHelper.IsPostBack())
        {
            loadedCorrectly = editSQL.SetupControl();
        }

        // Create breadcrumbs
        CreateBreadcrumbs();

        // Edit menu
        if (objName != null)
        {
            // Save button
            HeaderActions.AddAction(new SaveAction(Page)
            {
                Enabled = loadedCorrectly,
                RegisterShortcutScript = loadedCorrectly
            });

            // Restore button
            if(editSQL.RollbackAvailable){
            HeaderActions.AddAction(new HeaderAction
            {
                Text = GetString("dbobjects.restoredefault"),
                CommandName = "restoredefault"
            });
            }

            HeaderActions.ActionPerformed += HeaderActions_ActionPerformed;
        }
    }
    /// <summary>
    /// Initializes the custom table
    /// </summary>
    /// <param name="dci">DataClassInfo of the custom table</param>
    /// <param name="fi">Form info</param>
    /// <param name="tm">Table manager</param>
    private void InitCustomTable(DataClassInfo dci, FormInfo fi, TableManager tm)
    {
        // Created by
        if (chkItemCreatedBy.Checked && !fi.FieldExists("ItemCreatedBy"))
        {
            FormFieldInfo ffi = new FormFieldInfo();

            // Fill FormInfo object
            ffi.Name = "ItemCreatedBy";
            ffi.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "Created by");
            ffi.DataType = FieldDataType.Integer;
            ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, string.Empty);
            ffi.SetPropertyValue(FormFieldPropertyEnum.FieldDescription, string.Empty);
            ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl;
            ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe();
            ffi.PrimaryKey = false;
            ffi.System = true;
            ffi.Visible = false;
            ffi.Size = 0;
            ffi.AllowEmpty = true;

            fi.AddFormItem(ffi);
        }

        // Created when
        if (chkItemCreatedWhen.Checked && !fi.FieldExists("ItemCreatedWhen"))
        {
            FormFieldInfo ffi = new FormFieldInfo();

            // Fill FormInfo object
            ffi.Name = "ItemCreatedWhen";
            ffi.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "Created when");
            ffi.DataType = FieldDataType.DateTime;
            ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, string.Empty);
            ffi.SetPropertyValue(FormFieldPropertyEnum.FieldDescription, string.Empty);
            ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl;
            ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe();
            ffi.PrimaryKey = false;
            ffi.System = true;
            ffi.Visible = false;
            ffi.Size = 0;
            ffi.AllowEmpty = true;

            fi.AddFormItem(ffi);
        }

        // Modified by
        if (chkItemModifiedBy.Checked && !fi.FieldExists("ItemModifiedBy"))
        {
            FormFieldInfo ffi = new FormFieldInfo();

            // Fill FormInfo object
            ffi.Name = "ItemModifiedBy";
            ffi.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "Modified by");
            ffi.DataType = FieldDataType.Integer;
            ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, string.Empty);
            ffi.SetPropertyValue(FormFieldPropertyEnum.FieldDescription, string.Empty);
            ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl;
            ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe();
            ffi.PrimaryKey = false;
            ffi.System = true;
            ffi.Visible = false;
            ffi.Size = 0;
            ffi.AllowEmpty = true;

            fi.AddFormItem(ffi);
        }

        // Modified when
        if (chkItemModifiedWhen.Checked && !fi.FieldExists("ItemModifiedWhen"))
        {
            FormFieldInfo ffi = new FormFieldInfo();

            // Fill FormInfo object
            ffi.Name = "ItemModifiedWhen";
            ffi.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "Modified when");
            ffi.DataType = FieldDataType.DateTime;
            ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, string.Empty);
            ffi.SetPropertyValue(FormFieldPropertyEnum.FieldDescription, string.Empty);
            ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl;
            ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe();
            ffi.PrimaryKey = false;
            ffi.System = true;
            ffi.Visible = false;
            ffi.Size = 0;
            ffi.AllowEmpty = true;

            fi.AddFormItem(ffi);
        }

        // Item order
        if (chkItemOrder.Checked && !fi.FieldExists("ItemOrder"))
        {
            FormFieldInfo ffi = new FormFieldInfo();

            // Fill FormInfo object
            ffi.Name = "ItemOrder";
            ffi.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "Order");
            ffi.DataType = FieldDataType.Integer;
            ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, string.Empty);
            ffi.SetPropertyValue(FormFieldPropertyEnum.FieldDescription, string.Empty);
            ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl;
            ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe();
            ffi.PrimaryKey = false;
            ffi.System = true;
            ffi.Visible = false;
            ffi.Size = 0;
            ffi.AllowEmpty = true;

            fi.AddFormItem(ffi);
        }

        // GUID
        if (chkItemGUID.Checked && !fi.FieldExists("ItemGUID"))
        {
            var ffiGuid = CreateGuidField();

            fi.AddFormItem(ffiGuid);
        }

        // Update table structure - columns could be added
        bool old = TableManager.UpdateSystemFields;

        TableManager.UpdateSystemFields = true;

        string schema = fi.GetXmlDefinition();
        tm.UpdateTableByDefinition(dci.ClassTableName, schema);

        TableManager.UpdateSystemFields = old;

        // Update xml schema and form definition
        dci.ClassFormDefinition = schema;
        dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName);

        using (CMSActionContext context = new CMSActionContext())
        {
            // Disable logging into event log
            context.LogEvents = false;

            DataClassInfoProvider.SetDataClassInfo(dci);
        }
    }
    private string UpdateFormField(TableManager tm, string tableName, FormFieldInfo updatedFieldInfo)
    {
        // Validate whether column with this name already exists
        string errorMessage = ValidateFieldColumn(updatedFieldInfo);
        if (!String.IsNullOrEmpty(errorMessage))
        {
            return errorMessage;
        }

        // Create or update form field
        errorMessage = IsNewItemEdited ? CreateDatabaseColumn(tm, tableName, updatedFieldInfo) : UpdateDatabaseColumn(tm, tableName, updatedFieldInfo);
        if (!String.IsNullOrEmpty(errorMessage))
        {
            return errorMessage;
        }

        if (IsNewItemEdited)
        {
            // Insert new field
            InsertFormItem(updatedFieldInfo);

            // Hide new field in alternative and inherited forms if necessary
            if (IsMainForm)
            {
                DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(ClassName);
                HideFieldInAlternativeForms(updatedFieldInfo, dci);
            }
        }
        else
        {
            // Update current field
            FormInfo.UpdateFormField(ffi.Name, updatedFieldInfo);
        }

        return null;
    }
    private string UpdateDependencies(DataClassInfo dci, TableManager tm, FormFieldInfo updatedFieldInfo, out bool updateInheritedForms)
    {
        updateInheritedForms = false;
        string error = null;

        if (dci != null)
        {
            // Update XML definition
            dci.ClassFormDefinition = FormDefinition;

            // When updating existing field
            if ((ffi != null) && (dci.ClassNodeNameSource == ffi.Name))
            {
                // Update ClassNodeNameSource field
                dci.ClassNodeNameSource = updatedFieldInfo.Name;
            }

            bool isNotDummyOrField = (SelectedItemType != FieldEditorSelectedItemEnum.Field) || !updatedFieldInfo.IsDummyField;
            if (isNotDummyOrField)
            {
                // Update XML schema
                dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName);
            }

            // Update changes in DB
            try
            {
                // Save the data class
                DataClassInfoProvider.SetDataClassInfo(dci);

                updateInheritedForms = true;
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException("FieldEditor", "SAVE", ex);
                error = ex.Message;
            }

            if ((SelectedItemType == FieldEditorSelectedItemEnum.Field) && !updatedFieldInfo.IsDummyField)
            {
                // Generate default view
                SqlGenerator.GenerateDefaultView(dci, mMode == FieldEditorModeEnum.BizFormDefinition ? SiteContext.CurrentSiteName : null);

                QueryInfoProvider.ClearDefaultQueries(dci, true, true);
            }

            // Updates custom views
            if (isNotDummyOrField && ((mMode == FieldEditorModeEnum.SystemTable) || (mMode == FieldEditorModeEnum.ClassFormDefinition)) && IsDatabaseChangeRequired(ffi, updatedFieldInfo))
            {
                error = RefreshViews(tm, dci);
            }
        }
        else
        {
            error = GetString("FieldEditor.ClassNotFound");
        }

        return error;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Query param validation
        if (!QueryHelper.ValidateHash("hash", "saved"))
        {
            ShowError(GetString("sysdev.views.corruptedparameters"));
            editSQL.Visible = false;
            return;
        }

        objName = HttpUtility.HtmlDecode(QueryHelper.GetString("objname", null));
        objType = QueryHelper.GetInteger("objtype", -1);

        // Check if edited view exists and redirect to error page if not
        TableManager tm = new TableManager(null);

        if (!String.IsNullOrEmpty(objName) && !tm.ViewExists(objName))
        {
            EditedObject = null;
        }

        // Init edit area
        editSQL.ObjectName = objName;
        editSQL.HideSaveButton = objName != null;
        editSQL.IsView = true;
        editSQL.OnSaved += new EventHandler(editSQL_OnSaved);
        bool loadedCorrectly = true;
        if (!RequestHelper.IsPostBack())
        {
            if (QueryHelper.GetBoolean("saved", false))
            {
                ShowChangesSaved();
            }

            loadedCorrectly = editSQL.SetupControl();
        }

        if (objName == null)
        {
            string[,] breadcrumbs = new string[2,3];
            breadcrumbs[0, 0] = GetString("sysdev.views");
            breadcrumbs[0, 1] = "~/CMSModules/SystemTables/Pages/Development/Views/Views_List.aspx";
            breadcrumbs[0, 2] = "";
            breadcrumbs[1, 0] = GetString("general.new");
            breadcrumbs[1, 1] = "";
            breadcrumbs[1, 2] = "";

            CurrentMaster.Title.Breadcrumbs = breadcrumbs;
            CurrentMaster.Title.HelpName = "helpTopic";
            CurrentMaster.Title.HelpTopicName = "systemtables_views_new";
        }
        else
        {
            // Header actions
            string[,] actions = new string[2,11];

            // Save button
            actions[0, 0] = HeaderActions.TYPE_SAVEBUTTON;
            actions[0, 1] = GetString("General.Save");
            actions[0, 5] = GetImageUrl("CMSModules/CMS_Content/EditMenu/" + (loadedCorrectly ? "save.png" : "savedisabled.png"));
            actions[0, 6] = "save";
            actions[0, 8] = loadedCorrectly.ToString();
            actions[0, 9] = loadedCorrectly.ToString();

            // Undo button
            actions[1, 0] = HeaderActions.TYPE_HYPERLINK;
            actions[1, 1] = GetString("General.Rollback");
            actions[1, 5] = GetImageUrl("CMSModules/CMS_Content/EditMenu/undo.png");
            actions[1, 6] = "rollback";
            actions[1, 10] = editSQL.RollbackAvailable.ToString();

            CurrentMaster.HeaderActions.Actions = actions;
            CurrentMaster.HeaderActions.ActionPerformed += new CommandEventHandler(HeaderActions_ActionPerformed);
        }
    }
    private string RefreshViews(TableManager tm, DataClassInfo dci)
    {
        string errorMessage = null;

        try
        {
            tm.RefreshCustomViews(dci.ClassTableName);

            if (dci.ClassName.EqualsCSafe("cms.document", StringComparison.InvariantCultureIgnoreCase) || dci.ClassName.EqualsCSafe("cms.tree", StringComparison.InvariantCultureIgnoreCase))
            {
                tm.RefreshDocumentViews();
            }
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("FieldEditor", "REFRESHVIEWS", ex);
            errorMessage = ResHelper.GetString("fieldeditor.refreshingviewsfailed");
        }

        return errorMessage;
    }
    private string CreateDatabaseColumn(TableManager tm, string tableName, FormFieldInfo updatedFieldInfo)
    {
        updatedFieldInfo.PrimaryKey = IsPrimaryField;

        string errorMessage = null;

        if (IsMainForm && !updatedFieldInfo.IsDummyField && !updatedFieldInfo.IsExtraField)
        {
            // Validate the default value
            string newDBDefaultValue = GetDefaultValueInDBCulture(updatedFieldInfo, out errorMessage, !DevelopmentMode);

            if (String.IsNullOrEmpty(errorMessage))
            {
                switch (mMode)
                {
                    case FieldEditorModeEnum.ClassFormDefinition:
                    case FieldEditorModeEnum.BizFormDefinition:
                    case FieldEditorModeEnum.SystemTable:
                    case FieldEditorModeEnum.CustomTable:

                        // Add new column to specified table
                        if (!updatedFieldInfo.External && (tm != null))
                        {
                            // Set column type and size
                            string newColumnType = DataTypeManager.GetSqlType(updatedFieldInfo.DataType, updatedFieldInfo.Size, updatedFieldInfo.Precision);

                            tm.AddTableColumn(tableName, updatedFieldInfo.Name, newColumnType, updatedFieldInfo.AllowEmpty, newDBDefaultValue, !DevelopmentMode);

                            // Recreate the table PK constraint
                            if (IsPrimaryField)
                            {
                                // Existing primary keys
                                var pkFields = FormInfo.GetFields(true, true, true, true);

                                // Include the new field in the collection
                                pkFields.Add(updatedFieldInfo);

                                var primaryKeys = pkFields.Select(pk => String.Format("[{0}]", pk.Name));

                                tm.RecreatePKConstraint(tableName, primaryKeys.ToArray());
                            }
                        }
                        break;

                }
            }
        }

        return errorMessage;
    }
    /// <summary>
    /// Processes the step 3 of the wizard
    /// </summary>
    private void ProcessStep3(WizardNavigationEventArgs e)
    {
        // Actions after next button click
        var dci = DataClassInfoProvider.GetDataClassInfo(ClassName);

        // Ensure actual form info
        FormHelper.ClearFormInfos(true);

        // Get and load form definition
        var fi = FormHelper.GetFormInfo(dci.ClassName, false);

        if (fi.GetFields(true, true).Count() < 2)
        {
            e.Cancel = true;
            FieldEditor.ShowError(GetString("DocumentType_New_Step3.TableMustHaveCustomField"));
        }
        else
        {
            // Different behavior by mode
            switch (Mode)
            {
                case NewClassWizardModeEnum.DocumentType:
                    {
                        TableManager tm = new TableManager(null);

                        // Create new view if doesn't exist
                        string viewName = SqlHelper.GetViewName(dci.ClassTableName, null);

                        // Create view for document types
                        if (!tm.ViewExists(viewName))
                        {
                            tm.CreateView(viewName, SqlGenerator.GetSqlQuery(ClassName, SqlOperationTypeEnum.SelectView, null));
                        }

                        // If new document type is created prepare next step otherwise skip steps 4, 5 and 6

                        // Disable previous steps' viewstates
                        DisablePreviousStepsViewStates(e.CurrentStepIndex);

                        // Enable next step's viewstate
                        EnableNextStepViewState(e.CurrentStepIndex);

                        // Add implicit value to the list
                        lstFields.Items.Add(new ListItem(GetString("DocumentType_New_Step4.ImplicitDocumentName"), ""));

                        // Get all fields
                        List<FormFieldInfo> ffiFields = fi.GetFields(true, true);

                        if (ffiFields != null)
                        {
                            bool selected = false;

                            // Add all text fields' names to the list except primary-key field
                            foreach (FormFieldInfo ffi in ffiFields)
                            {
                                if (!ffi.PrimaryKey && !ffi.AllowEmpty && ((ffi.DataType == FieldDataType.Text) || (ffi.DataType == FieldDataType.LongText)))
                                {
                                    lstFields.Items.Add(new ListItem(ffi.Name, ffi.Name));

                                    // Select the first text field
                                    if (!selected)
                                    {
                                        string controlName = ValidationHelper.GetString(ffi.Settings["controlname"], null);

                                        // Preselect only textbox
                                        if (CMSString.Compare(controlName, Enum.GetName(typeof (FormFieldControlTypeEnum), FormFieldControlTypeEnum.TextBoxControl), StringComparison.InvariantCultureIgnoreCase) == 0)
                                        {
                                            lstFields.SelectedValue = ffi.Name;
                                            selected = true;
                                        }
                                    }
                                }
                            }
                        }

                        lblSelectField.Text = GetString("DocumentType_New_Step4.DocumentName");
                        wzdStep4.Title = GetString("DocumentType_New_Step4.Title");
                        ucHeader.Description = GetString("DocumentType_New_Step4.Description");
                    }
                    break;

                case NewClassWizardModeEnum.Class:
                    {
                        // Update class in DB
                        using (CMSActionContext context = new CMSActionContext())
                        {
                            // Disable logging into event log
                            context.LogEvents = false;

                            DataClassInfoProvider.SetDataClassInfo(dci);
                        }

                        // Remember that some steps were omitted
                        SomeStepsOmitted = true;

                        // Prepare next step (7) - skip steps 4, 5 and 6

                        // Disable previous steps' viewstates
                        DisablePreviousStepsViewStates(5);

                        // Enable next step's viewstate
                        EnableNextStepViewState(5);

                        PrepareStep7();
                        // Go to the step 7 (indexed from 0)
                        wzdNewDocType.ActiveStepIndex = 6;
                    }
                    break;

                case NewClassWizardModeEnum.CustomTable:
                    {
                        // Update class in DB
                        using (CMSActionContext context = new CMSActionContext())
                        {
                            // Disable logging into event log
                            context.LogEvents = false;

                            DataClassInfoProvider.SetDataClassInfo(dci);
                        }

                        // Remember that some steps were omitted,
                        SomeStepsOmitted = true;

                        // Prepare next step (6) - skip steps 4, 5

                        // Disable previous steps' viewstates
                        DisablePreviousStepsViewStates(4);

                        // Enable next step's viewstate
                        EnableNextStepViewState(4);

                        PrepareStep6();
                        // Go to the step 6 (indexed from 0)
                        wzdNewDocType.ActiveStepIndex = 5;
                    }
                    break;
            }
        }
    }
    /// <summary>
    /// Processes the step 2 of the wizard
    /// </summary>
    private void ProcessStep2(WizardNavigationEventArgs e)
    {
        var dci = DataClassInfoProvider.GetDataClassInfo(ClassName);

        if (dci != null)
        {
            var tm = new TableManager(null);

            using (var tr = new CMSTransactionScope())
            {
                // New document type has custom attributes -> no wizard steps will be omitted
                if (radCustom.Checked)
                {
                    // Actions after next button click
                    bool fromExisting = (Mode == NewClassWizardModeEnum.CustomTable) && radExistingTable.Checked;

                    string tableName = (fromExisting) ? drpExistingTables.SelectedValue : txtTableName.Text.Trim();

                    // Validate checkboxes first
                    string tableNameError = new Validator()
                        .NotEmpty(tableName, GetString("DocumentType_New.ErrorEmptyTableName"))
                        .IsIdentifier(tableName, GetString("class.ErrorIdentifier"))
                        .Result;

                    string primaryKeyNameEmpty = new Validator().NotEmpty(txtPKName.Text.Trim(), GetString("DocumentType_New.ErrorEmptyPKName")).Result;

                    bool columnExists = DocumentHelper.ColumnExistsInDocumentView(txtPKName.Text.Trim());

                    // Textboxes are filled correctly
                    if ((tableNameError == "") && (primaryKeyNameEmpty == "") && (!columnExists))
                    {
                        try
                        {
                            bool tableExists = tm.TableExists(tableName);
                            if (fromExisting)
                            {
                                // Custom table from existing table - validate the table name
                                if (!tableExists)
                                {
                                    e.Cancel = true;

                                    // Table with the same name already exists
                                    ShowError(GetString("customtable.newwizard.tablenotexists"));
                                }

                                // Check primary key
                                List<string> primaryKeys = tm.GetPrimaryKeyColumns(tableName);
                                if ((primaryKeys == null) || (primaryKeys.Count != 1))
                                {
                                    e.Cancel = true;

                                    ShowError(GetString("customtable.newwizard.musthaveprimarykey"));
                                }
                                else if (!IsIdentityColumn(tableName, primaryKeys.First()))
                                {
                                    e.Cancel = true;
                                    ShowError(GetString("customtable.newwizard.mustbeidentitypk"));
                                }
                            }
                            else if (tableExists)
                            {
                                // Check if given table name already exists in database
                                e.Cancel = true;
                                ShowError(GetString("sysdev.class_edit_gen.tablenameunique"));
                            }
                            else if (Mode == NewClassWizardModeEnum.Class)
                            {
                                // Standard class in development mode
                                tm.CreateTable(tableName, txtPKName.Text.Trim(), !chbIsMNTable.Checked);
                            }
                            else
                            {
                                tm.CreateTable(tableName, txtPKName.Text.Trim());
                            }
                        }
                        catch (Exception ex)
                        {
                            // No movement to the next step
                            e.Cancel = true;

                            // Show error message if something caused unhandled exception
                            ShowError(ex.Message);
                        }

                        if ((pnlMessages2.ErrorLabel.Text == "") && !e.Cancel)
                        {
                            // Change table owner
                            try
                            {
                                string owner = "";

                                // Get site related DB object owner setting when creating new wizard and global otherwise
                                switch (Mode)
                                {
                                    case NewClassWizardModeEnum.DocumentType:
                                    case NewClassWizardModeEnum.Class:
                                    case NewClassWizardModeEnum.CustomTable:
                                        owner = SqlHelper.GetDBSchema(SiteContext.CurrentSiteName);
                                        break;
                                }

                                if ((owner != "") && (owner.ToLowerCSafe() != "dbo"))
                                {
                                    tm.ChangeDBObjectOwner(tableName, owner);
                                    tableName = SqlHelper.GetSafeOwner(owner) + "." + tableName;
                                }
                            }
                            catch
                            {
                                // Suppress error
                            }

                            FormInfo fi;
                            if (fromExisting)
                            {
                                // From existing DB table
                                dci.ClassXmlSchema = tm.GetXmlSchema(tableName);

                                string formDef = FormHelper.GetXmlFormDefinitionFromXmlSchema(dci.ClassXmlSchema, false);
                                fi = new FormInfo(formDef);
                            }
                            else
                            {
                                // Create empty form info
                                fi = CreateEmptyFormInfo();

                                dci.ClassXmlSchema = tm.GetXmlSchema(tableName);
                            }

                            dci.ClassTableName = tableName;
                            dci.ClassFormDefinition = fi.GetXmlDefinition();
                            dci.ClassIsCoupledClass = true;

                            dci.ClassInheritsFromClassID = ValidationHelper.GetInteger(selInherits.Value, 0);

                            // Update class in DB
                            using (var context = new CMSActionContext())
                            {
                                // Disable logging into event log
                                context.LogEvents = false;

                                DataClassInfoProvider.SetDataClassInfo(dci);

                                UpdateInheritedClass(dci);
                            }

                            if (Mode == NewClassWizardModeEnum.CustomTable)
                            {
                                try
                                {
                                    InitCustomTable(dci, fi, tm);
                                }
                                catch (Exception ex)
                                {
                                    // Do not move to next step.
                                    e.Cancel = true;

                                    EventLogProvider.LogException("NewClassWizard", "CREATE", ex);

                                    string message = null;
                                    if (ex is MissingSQLTypeException)
                                    {
                                        var missingSqlType = (MissingSQLTypeException) ex;
                                        message = String.Format(GetString("customtable.sqltypenotsupported"), missingSqlType.UnsupportedType, missingSqlType.ColumnName, missingSqlType.RecommendedType);
                                    }
                                    else
                                    {
                                        message = ex.Message;
                                    }

                                    pnlMessages2.ShowError(message);
                                    pnlMessages2.Visible = true;
                                }
                            }

                            if (!e.Cancel)
                            {
                                // Remember that no steps were omitted
                                SomeStepsOmitted = false;

                                // Prepare next step (3)

                                // Disable previous steps' viewstates
                                DisablePreviousStepsViewStates(e.CurrentStepIndex);

                                // Enable next step's viewstate
                                EnableNextStepViewState(e.CurrentStepIndex);

                                // Set field editor class name
                                FieldEditor.ClassName = ClassName;

                                // Fill field editor in the next step
                                FieldEditor.Reload(null);

                                wzdStep3.Title = GetString("general.fields");

                                // Set new step header based on the development mode setting
                                switch (Mode)
                                {
                                    case NewClassWizardModeEnum.DocumentType:
                                        ucHeader.Description = GetString("DocumentType_New_Step3.Description");
                                        break;

                                    case NewClassWizardModeEnum.Class:
                                        ucHeader.Description = GetString("sysdev.class_new_Step3.Description");
                                        break;

                                    case NewClassWizardModeEnum.CustomTable:
                                        ucHeader.Description = GetString("customtable.newwizzard.Step3Description");
                                        break;
                                }
                            }
                        }
                    }
                    // Some textboxes are not filled correctly
                    else
                    {
                        // Prepare current step (2)

                        // No movement to the next step
                        e.Cancel = true;

                        // Show errors
                        if (!String.IsNullOrEmpty(tableNameError))
                        {
                            lblTableNameError.Text = tableNameError;
                            lblTableNameError.Visible = true;
                        }
                        else
                        {
                            lblTableNameError.Visible = false;
                        }

                        if (!String.IsNullOrEmpty(primaryKeyNameEmpty))
                        {
                            lblPKNameError.Visible = true;
                            lblPKNameError.Text = primaryKeyNameEmpty;
                        }
                        else
                        {
                            lblPKNameError.Visible = false;
                        }

                        if (columnExists)
                        {
                            pnlMessages2.ShowError(GetString("DocumentType_New_Step2.ErrorColumnExists"));
                            pnlMessages2.Visible = true;
                        }

                        wzdStep2.Title = GetString("DocumentType_New_Step2.Title");

                        // Reset the header
                        switch (Mode)
                        {
                            case NewClassWizardModeEnum.DocumentType:
                                ucHeader.Description = GetString("DocumentType_New_Step2.Description");
                                break;

                            case NewClassWizardModeEnum.Class:
                                ucHeader.Description = GetString("sysdev.class_new_Step2.Description");
                                break;

                            case NewClassWizardModeEnum.CustomTable:
                                ucHeader.Description = GetString("customtable.newwizzard.Step2Description");
                                break;
                        }
                    }
                }
                // New document type is only the container -> some wizard steps will be omitted
                else
                {
                    // Actions after next button click

                    dci.ClassIsCoupledClass = false;

                    // Update class in DB
                    using (CMSActionContext context = new CMSActionContext())
                    {
                        // Disable logging into event log
                        context.LogEvents = false;

                        DataClassInfoProvider.SetDataClassInfo(dci);
                    }

                    // Remember that some steps were omitted
                    SomeStepsOmitted = true;
                    IsContainer = true;

                    // Prepare next step (5) - skip steps 3 and 4

                    // Disable previous steps' viewstates
                    DisablePreviousStepsViewStates(3);

                    // Enable next step's viewstate
                    EnableNextStepViewState(3);

                    PrepareStep5();
                    // Go to the step 5 (indexed from 0)
                    wzdNewDocType.ActiveStepIndex = 4;
                }

                // Create new icon if the wizard is used to create new document type
                if (Mode == NewClassWizardModeEnum.DocumentType)
                {
                    // Setup icon class for new doc. type
                    string iconClass = (SomeStepsOmitted) ? DEFAULT_CLASS_ICON : DEFAULT_COUPLED_CLASS_ICON;
                    dci.SetValue("ClassIconClass", iconClass);
                }

                if (!e.Cancel)
                {
                    tr.Commit();
                }
            }
        }
    }
    /// <summary>
    /// Delete attribute button clicked.
    /// </summary>
    protected void btnDeleteItem_Click(Object sender, EventArgs e)
    {
        DataClassInfo dci = null;
        bool updateInherited = false;

        // Ensure the transaction
        using (var tr = new CMSLateBoundTransaction())
        {
            if (Mode == FieldEditorModeEnum.BizFormDefinition)
            {
                // Check 'EditForm' permission
                if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.form", "EditForm"))
                {
                    RedirectToAccessDenied("cms.form", "EditForm");
                }
            }

            // Raise on before definition update event
            if (OnBeforeDefinitionUpdate != null)
            {
                OnBeforeDefinitionUpdate(this, EventArgs.Empty);
            }

            string errorMessage = null;
            string newSelectedValue = null;
            string deletedItemPreffix = null;

            // Clear settings
            controlSettings.Settings = new Hashtable();
            controlSettings.BasicForm.Mode = FormModeEnum.Insert;

            TableManager tm = null;

            switch (mMode)
            {
                // Do nothing for WebPart
                case FieldEditorModeEnum.ClassFormDefinition:
                case FieldEditorModeEnum.BizFormDefinition:
                case FieldEditorModeEnum.SystemTable:
                case FieldEditorModeEnum.CustomTable:
                    {
                        // Get the DataClass
                        dci = DataClassInfoProvider.GetDataClassInfo(ClassName);
                        if (dci == null)
                        {
                            ShowError(GetString("FieldEditor.ClassNotFound"));
                            return;
                        }

                        tm = new TableManager(dci.ClassConnectionString);
                        tr.BeginTransaction();
                    }
                    break;
            }

            // Load current xml form definition
            LoadFormDefinition();

            if (!String.IsNullOrEmpty(SelectedItemName) && !IsNewItemEdited)
            {
                switch (SelectedItemType)
                {
                    case FieldEditorSelectedItemEnum.Field:
                        {
                            FormFieldInfo ffiSelected = FormInfo.GetFormField(SelectedItemName);
                            deletedItemPreffix = fieldPreffix;

                            if (ffiSelected != null)
                            {
                                // Do not allow deleting of the primary key except for external fields
                                if (ffiSelected.PrimaryKey && !ffiSelected.External)
                                {
                                    if (!DevelopmentMode)
                                    {
                                        ShowError(GetString("TemplateDesigner.ErrorCannotDeletePK"));
                                        return;
                                    }

                                    // Check if at least one primary key stays
                                    if (FormInfo.GetFields(true, true, false, true).Count() < 2)
                                    {
                                        ShowError(GetString("TemplateDesigner.ErrorCannotDeletePK"));
                                        return;
                                    }
                                }

                                // Check if at least two fields stay in document type definition
                                if ((Mode == FieldEditorModeEnum.ClassFormDefinition) && (FormInfo.GetFields(true, true, true, false, false).Count() < 3) && !ffiSelected.IsDummyField)
                                {
                                    ShowError(GetString("TemplateDesigner.ErrorCannotDeleteAllCustomFields"));
                                    return;
                                }

                                // Do not allow deleting of the system field
                                if (ffiSelected.System && !ffiSelected.External && !DevelopmentMode)
                                {
                                    ShowError(GetString("TemplateDesigner.ErrorCannotDeleteSystemField"));
                                    return;
                                }

                                // Remove specific field from xml form definition
                                FormInfo.RemoveFormField(SelectedItemName);

                                // Get updated definition
                                FormDefinition = FormInfo.GetXmlDefinition();

                                switch (mMode)
                                {
                                    case FieldEditorModeEnum.WebPartProperties:
                                        errorMessage = UpdateWebPartProperties();
                                        break;

                                    case FieldEditorModeEnum.ClassFormDefinition:
                                    case FieldEditorModeEnum.BizFormDefinition:
                                    case FieldEditorModeEnum.SystemTable:
                                    case FieldEditorModeEnum.CustomTable:
                                        {
                                            // If document type is edited AND field that should be removed is FILE
                                            if (IsDocumentType && (mMode == FieldEditorModeEnum.ClassFormDefinition) && !String.IsNullOrEmpty(ClassName) && (ffiSelected.DataType == FieldDataType.File))
                                            {
                                                DocumentHelper.DeleteDocumentAttachments(ClassName, ffiSelected.Name, null);
                                            }

                                            // If bizform is edited AND field that should be removed is FILE
                                            if ((mMode == FieldEditorModeEnum.BizFormDefinition) && !String.IsNullOrEmpty(ClassName) && (ffiSelected.FieldType == FormFieldControlTypeEnum.UploadControl))
                                            {
                                                BizFormInfoProvider.DeleteBizFormFiles(ClassName, ffiSelected.Name, SiteContext.CurrentSiteID);
                                            }

                                            // Update xml definition
                                            if (dci != null)
                                            {
                                                dci.ClassFormDefinition = FormDefinition;

                                                if (!ffiSelected.IsDummyField)
                                                {
                                                    try
                                                    {
                                                        if (!ffiSelected.External)
                                                        {
                                                            // Remove corresponding column from table
                                                            tm.DropTableColumn(dci.ClassTableName, SelectedItemName);

                                                            // Update xml schema
                                                            dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName);
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        EventLogProvider.LogException("FieldEditor", "SAVE", ex);
                                                        errorMessage = ex.Message;
                                                    }
                                                }

                                                // Deleted field is used as ClassNodeNameSource -> remove node name source
                                                if (dci.ClassNodeNameSource == SelectedItemName)
                                                {
                                                    dci.ClassNodeNameSource = String.Empty;
                                                }

                                                // Update changes in database
                                                try
                                                {
                                                    using (CMSActionContext context = new CMSActionContext())
                                                    {
                                                        // Do not log synchronization for BizForm
                                                        if (mMode == FieldEditorModeEnum.BizFormDefinition)
                                                        {
                                                            context.DisableLogging();
                                                        }

                                                        // Clean search settings
                                                        dci.ClassSearchSettings = SearchHelper.CleanSearchSettings(dci);

                                                        // Save the data class
                                                        DataClassInfoProvider.SetDataClassInfo(dci);

                                                        updateInherited = true;

                                                        // Update alternative forms of form class
                                                        RemoveFieldFromAlternativeForms(dci);
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    EventLogProvider.LogException("FieldEditor", "SAVE", ex);
                                                    errorMessage = ex.Message;
                                                }

                                                // Refresh views and queries only if changes to DB were made
                                                if (!ffiSelected.External)
                                                {
                                                    // Generate default view
                                                    SqlGenerator.GenerateDefaultView(dci, mMode == FieldEditorModeEnum.BizFormDefinition ? SiteContext.CurrentSiteName : null);

                                                    QueryInfoProvider.ClearDefaultQueries(dci, true, true);

                                                    // Updates custom views
                                                    if ((mMode == FieldEditorModeEnum.SystemTable) || (mMode == FieldEditorModeEnum.ClassFormDefinition))
                                                    {
                                                        errorMessage = RefreshViews(tm, dci);
                                                    }
                                                }
                                            }

                                            // Clear hashtables and search settings
                                            ClearHashtables();
                                        }
                                        break;
                                }
                            }
                        }
                        break;

                    case FieldEditorSelectedItemEnum.Category:
                        deletedItemPreffix = categPreffix;

                        // Remove specific category from xml form definition
                        FormInfo.RemoveFormCategory(SelectedItemName);

                        // Get updated form definition
                        FormDefinition = FormInfo.GetXmlDefinition();

                        switch (mMode)
                        {
                            case FieldEditorModeEnum.WebPartProperties:
                                errorMessage = UpdateWebPartProperties();
                                break;

                            case FieldEditorModeEnum.ClassFormDefinition:
                            case FieldEditorModeEnum.BizFormDefinition:
                            case FieldEditorModeEnum.SystemTable:
                            case FieldEditorModeEnum.CustomTable:
                                // Standard classes
                                {
                                    // Update xml definition
                                    if (dci != null)
                                    {
                                        dci.ClassFormDefinition = FormDefinition;

                                        // Update changes in database
                                        try
                                        {
                                            using (CMSActionContext context = new CMSActionContext())
                                            {
                                                // Do not log synchronization for BizForm
                                                if (mMode == FieldEditorModeEnum.BizFormDefinition)
                                                {
                                                    context.DisableLogging();
                                                }

                                                // Save the data class
                                                DataClassInfoProvider.SetDataClassInfo(dci);

                                                updateInherited = true;

                                                RemoveFieldFromAlternativeForms(dci);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            EventLogProvider.LogException("FieldEditor", "SAVE", ex);
                                            errorMessage = ex.Message;
                                        }
                                    }
                                }
                                break;

                        }
                        break;

                }

                if (!String.IsNullOrEmpty(errorMessage))
                {
                    ShowError("[ FieldEditor.btnDeleteItem_Click() ]: " + errorMessage);
                }
            }
            else
            {
                // "delete" new item from the list
                IsNewItemEdited = false;
            }

            // Raise on after definition update event
            if (OnAfterDefinitionUpdate != null)
            {
                OnAfterDefinitionUpdate(this, EventArgs.Empty);
            }

            // Raise on after item delete
            if (AfterItemDeleted != null)
            {
                AfterItemDeleted(this, new FieldEditorEventArgs(SelectedItemName, SelectedItemType, lstAttributes.SelectedIndex));
            }

            // Commit the transaction
            tr.Commit();

            // Set new selected value
            ListItem deletedItem = lstAttributes.Items.FindByValue(deletedItemPreffix + SelectedItemName);
            int deletedItemIndex = lstAttributes.Items.IndexOf(deletedItem);

            if (deletedItemIndex > 0)
            {
                var item = lstAttributes.Items[deletedItemIndex - 1];
                if (item != null)
                {
                    newSelectedValue = item.Value;
                }
            }

            // Reload data
            Reload(newSelectedValue);
        }

        // Update inherited classes with new fields if necessary
        if (updateInherited)
        {
            FormHelper.UpdateInheritedClasses(dci);
        }
    }
    /// <summary>
    /// Save selected field.
    /// </summary>
    private bool SaveSelectedField()
    {
        DataClassInfo dci = null;
        bool updateInherited = false;

        // Ensure the transaction
        using (var tr = new CMSLateBoundTransaction())
        {
            // FormFieldInfo structure with data from updated form
            FormFieldInfo ffiUpdated = null;

            // FormCategoryInfo structure with data from updated form
            FormCategoryInfo fciUpdated = null;

            // For some types of forms initialize table manager
            string tableName = null;
            TableManager tm = null;

            if (IsMainForm)
            {
                switch (mMode)
                {
                    // Do nothing for WebPart
                    case FieldEditorModeEnum.ClassFormDefinition:
                    case FieldEditorModeEnum.BizFormDefinition:
                    case FieldEditorModeEnum.SystemTable:
                    case FieldEditorModeEnum.CustomTable:
                        {
                            // Fill ClassInfo structure with data from database
                            dci = DataClassInfoProvider.GetDataClassInfo(ClassName);
                            if (dci != null)
                            {
                                // Set table name
                                tableName = dci.ClassTableName;

                                tm = new TableManager(dci.ClassConnectionString);
                                tr.BeginTransaction();
                            }
                            else
                            {
                                ShowError(GetString("fieldeditor.notablename"));
                                return false;
                            }
                        }
                        break;

                }
            }

            // Load current XML form definition
            if (!LoadFormDefinition())
            {
                // Form definition was not loaded
                return false;
            }

            string error = null;

            switch (SelectedItemType)
            {
                case FieldEditorSelectedItemEnum.Field:
                    // Fill FormFieldInfo structure with original data
                    ffi = FormInfo.GetFormField(SelectedItemName);

                    // Fill FormFieldInfo structure with updated form data
                    ffiUpdated = FillFormFieldInfoStructure(ffi);

                    try
                    {
                        error = UpdateFormField(tm, tableName, ffiUpdated);
                    }
                    catch (Exception ex)
                    {
                        EventLogProvider.LogException("FieldEditor", "SAVE", ex);

                        // User friendly message for not null setting of column
                        if (!IsNewItemEdited && ffi.AllowEmpty && !ffiUpdated.AllowEmpty)
                        {
                            ShowError(GetString("FieldEditor.ColumnNotAcceptNull"), ex.Message);
                        }
                        else
                        {
                            ShowError(GetString("general.saveerror"), ex.Message);
                        }
                        return false;
                    }
                    break;

                case FieldEditorSelectedItemEnum.Category:
                    // Fill FormCategoryInfo structure with original data
                    fci = FormInfo.GetFormCategory(SelectedItemName);

                    // Initialize new FormCategoryInfo structure
                    fciUpdated = new FormCategoryInfo();

                    error = UpdateFormCategory(fciUpdated);
                    break;
            }

            if (!String.IsNullOrEmpty(error))
            {
                ShowError(error);
                return false;
            }

            // Make changes in database
            if (SelectedItemType != 0)
            {
                // Get updated definition
                FormDefinition = FormInfo.GetXmlDefinition();

                if (IsMainForm)
                {
                    switch (mMode)
                    {
                        case FieldEditorModeEnum.WebPartProperties:
                            error = UpdateWebPartProperties();
                            break;

                        case FieldEditorModeEnum.ClassFormDefinition:
                        case FieldEditorModeEnum.BizFormDefinition:
                        case FieldEditorModeEnum.SystemTable:
                        case FieldEditorModeEnum.CustomTable:
                            error = UpdateDependencies(dci, tm, ffiUpdated, out updateInherited);
                            break;

                    }
                }

                if (!String.IsNullOrEmpty(error))
                {
                    ShowError("[FieldEditor.SaveSelectedField()]: " + error);
                    return false;
                }
            }

            // All done and new item, fire OnFieldCreated  event
            RaiseOnFieldCreated(ffiUpdated);

            // Reload field/category
            switch (SelectedItemType)
            {
                case FieldEditorSelectedItemEnum.Category:
                    Reload(categPreffix + fciUpdated.CategoryName);
                    break;

                case FieldEditorSelectedItemEnum.Field:
                    Reload(fieldPreffix + ffiUpdated.Name);
                    break;
            }

            // Commit the transaction
            tr.Commit();
        }

        // Update inherited classes with new fields
        if (updateInherited)
        {
            FormHelper.UpdateInheritedClasses(dci);
        }

        return true;
    }
    protected void LoadAvailableTables()
    {
        var tm = new TableManager(null);

        var where = new WhereCondition()
            .WhereNotIn("TABLE_NAME", new ObjectQuery<DataClassInfo>().Column("ClassTableName").WhereNotNull("ClassTableName"))
            .WhereNotIn("TABLE_NAME", new List<string> { "Analytics_Index", "sysdiagrams", "Temp_WebPart" });

        drpExistingTables.DataSource = tm.GetTables(where.ToString());
        drpExistingTables.DataBind();
    }
    private string UpdateDatabaseColumn(TableManager tm, string tableName, FormFieldInfo updatedFieldInfo)
    {
        // Get info whether it is a primary key or system field
        updatedFieldInfo.PrimaryKey = ffi.PrimaryKey;

        string errorMessage = ValidatePrimaryKey(updatedFieldInfo);
        if (!String.IsNullOrEmpty(errorMessage))
        {
            return errorMessage;
        }

        // If table column update is needed
        if ((ffi.PrimaryKey && (ffi.Name != updatedFieldInfo.Name)) ||
           (!ffi.PrimaryKey && (IsDatabaseChangeRequired(ffi, updatedFieldInfo) || (updatedFieldInfo.DataType == FieldDataType.Double))))
        {
            if (IsMainForm && !updatedFieldInfo.IsDummyField && !updatedFieldInfo.IsExtraField && (tm != null))
            {
                switch (mMode)
                {
                    case FieldEditorModeEnum.ClassFormDefinition:
                    case FieldEditorModeEnum.BizFormDefinition:
                    case FieldEditorModeEnum.SystemTable:
                    case FieldEditorModeEnum.CustomTable:
                        errorMessage = UpdateDatabaseColumn(ffi, updatedFieldInfo, tm, tableName);
                        break;

                }
            }
            else
            {
                RaiseOnFieldNameChanged(ffi.Name, updatedFieldInfo.Name);
            }
        }

        return errorMessage;
    }
    /// <summary>
    /// Initializes the controls. Returns false if parsing code of existing view/procedure failed.
    /// </summary>
    private bool SetupControl(string code)
    {
        bool result = true;

        if (!String.IsNullOrEmpty(ObjectName) && String.IsNullOrEmpty(code))
        {
            if (IsView != null)
            {
                TableManager tm = new TableManager(null);

                code = tm.GetCode(ObjectName);
            }
        }

        if (IsView == true)
        {
            plcGenerate.Visible = true;
            if (code == null)
            {
                lblCreateLbl.Text = "CREATE VIEW " + (!SettingsKeyProvider.DevelopmentMode ? VIEW_CUSTOM_PREFIX : String.Empty);
                plcGenerate.Visible = true;
                State = STATE_CREATE_VIEW;
            }
            else
            {
                lblCreateLbl.Text = "ALTER VIEW";
                plcGenerate.Visible = false;
                string name, body;
                result = ParseView(code, out name, out body);
                txtObjName.Enabled = false;
                txtObjName.ReadOnly = true;
                txtObjName.Text = name;
                txtSQLText.Text = body;
                State = STATE_ALTER_VIEW;
            }

            plcParams.Visible = false;
            lblBegin.Text = "AS";
        }
        else
        {
            if (code == null)
            {
                lblCreateLbl.Text = "CREATE PROCEDURE " + (!SettingsKeyProvider.DevelopmentMode ? PROCEDURE_CUSTOM_PREFIX : String.Empty);
                plcGenerate.Visible = true;
                State = STATE_CREATE_PROCEDURE;
            }
            else
            {
                plcGenerate.Visible = false;
                lblCreateLbl.Text = "ALTER PROCEDURE";
                string name, param, body;
                result = ParseProcedure(code, out name, out param, out body);
                txtObjName.Enabled = false;
                txtObjName.ReadOnly = true;
                txtObjName.Text = name;
                txtParams.Text = param;
                txtSQLText.Text = body;
                State = STATE_ALTER_PROCEDURE;
            }
            plcParams.Visible = true;
            lblBegin.Text = "AS<br/>BEGIN";
            lblEnd.Text = "END";
        }

        if (!result)
        {
            // Parsing code failed => disable all controls
            DisableControl(txtObjName);
            DisableControl(txtParams);
            txtSQLText.EditorMode = EditorModeEnum.Basic;
            DisableControl(txtSQLText);
            btnGenerate.Enabled = false;

            ShowWarning(GetString((IsView == true) ? "systbl.view.parsingfailed" : "systbl.proc.parsingfailed"), null, null);
        }

        FailedToLoad = !result;
        return result;
    }