/// <summary>
        /// Updates the gallery items with the specified metadata value. <see cref="Entity.GalleryItemMeta.ActionResult" />
        /// contains details about the success or failure of the operation.
        /// </summary>
        /// <param name="galleryItemMeta">An instance of <see cref="Entity.GalleryItemMeta" /> that defines
        /// the tag value to be added and the gallery items it is to be added to. It is expected that only
        /// the MTypeId and Value properties of <see cref="Entity.GalleryItemMeta.MetaItem" /> are populated.</param>
        /// <returns>An instance of <see cref="Entity.GalleryItemMeta" />.</returns>
        /// <exception cref="System.Web.Http.HttpResponseException">Thrown when the current user does not have permission
        /// to carry out the operation or an internal server error occurs.</exception>
        public Entity.GalleryItemMeta PutGalleryItemMeta(Entity.GalleryItemMeta galleryItemMeta)
        {
            // /api/galleryitemmeta
            try
            {
                MetadataController.SaveGalleryItemMeta(galleryItemMeta);

                if (galleryItemMeta.ActionResult == null)
                {
                    galleryItemMeta.ActionResult = new ActionResult()
                    {
                        Status = ActionResultStatus.Success.ToString(),
                        Title  = "Save successful"
                    };
                }
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }

            return(galleryItemMeta);
        }
Exemplo n.º 2
0
        //
        //====================================================================================================
        /// <summary>
        /// getFieldEditorPreference remote method
        /// </summary>
        /// <param name="cp"></param>
        /// <returns></returns>
        public override object Execute(Contensive.BaseClasses.CPBaseClass cp)
        {
            string result = "";

            try {
                CoreController core = ((CPClass)cp).core;
                //
                // ----- Redirect with RC and RI
                //
                core.doc.redirectContentID = core.docProperties.getInteger(rnRedirectContentId);
                core.doc.redirectRecordID  = core.docProperties.getInteger(rnRedirectRecordId);
                if (core.doc.redirectContentID != 0 && core.doc.redirectRecordID != 0)
                {
                    string ContentName = MetadataController.getContentNameByID(core, core.doc.redirectContentID);
                    if (!string.IsNullOrEmpty(ContentName))
                    {
                        core.webServer.redirectByRecord_ReturnStatus(ContentName, core.doc.redirectRecordID, "");
                        result = "";
                        core.doc.continueProcessing = false;
                    }
                }
            } catch (Exception ex) {
                cp.Site.ErrorReport(ex);
            }
            return(result);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Gets a JSON string representing the tags used in the specified gallery. The JSON can be used as the
        /// data source for the jsTree jQuery widget. Only tags the current user has permission to view are
        /// included. The tag tree has a root node containing a single level of tags. Throws an exception when
        /// the application is not running an Enterprise License.
        /// </summary>
        /// <param name="galleryId">The gallery ID.</param>
        /// <param name="top">The number of tags to return. Values less than zero are treated the same as zero,
        /// meaning no tags will be returned. Specify <see cref="int.MaxValue" /> to return all tags.</param>
        /// <param name="sortBy">The property to sort the tags by. Specify "count" to sort by tag frequency or
        /// "value" to sort by tag name. When not specified, defaults to "count".</param>
        /// <param name="sortAscending">Specifies whether to sort the tags in ascending order. Specify <c>true</c>
        /// for ascending order or <c>false</c> for descending order. When not specified, defaults to <c>false</c>.</param>
        /// <param name="expanded">if set to <c>true</c> the tree is configured to display in an expanded form.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.Web.Http.HttpResponseException">Thrown when an error occurs.</exception>
        public string GetTagTreeAsJson(int galleryId, int top = int.MaxValue, string sortBy = "count", bool sortAscending = false, bool expanded = false)
        {
            try
            {
                ValidateEnterpriseLicense();

                TagSearchOptions.TagProperty sortProperty;
                if (!Enum.TryParse(sortBy, true, out sortProperty))
                {
                    sortProperty = TagSearchOptions.TagProperty.NotSpecified;
                }

                return(MetadataController.GetTagTreeAsJson(TagSearchType.TagsUserCanView, galleryId, top, sortProperty, sortAscending, expanded));
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
        /// <summary>
        /// Deletes the meta tag value from the specified gallery items.
        /// </summary>
        /// <param name="galleryItemMeta">An instance of <see cref="Entity.GalleryItemMeta" /> that defines
        /// the tag value to be added and the gallery items it is to be added to.</param>
        /// <returns><see cref="HttpResponseMessage" />.</returns>
        /// <exception cref="System.Web.Http.HttpResponseException"></exception>
        public HttpResponseMessage DeleteGalleryItemMeta(Entity.GalleryItemMeta galleryItemMeta)
        {
            // /api/galleryitemmeta
            try
            {
                var mType = (MetadataItemName)galleryItemMeta.MetaItem.MTypeId;
                if (mType == MetadataItemName.Tags || mType == MetadataItemName.People)
                {
                    MetadataController.DeleteTag(galleryItemMeta);
                }
                else
                {
                    MetadataController.Delete(galleryItemMeta);
                }

                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("Meta item deleted...")
                });
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
        public void GetODataServiceDocumentOnMetadataController_ReturnsODataODataServiceDocument()
        {
            // Arrange
            EdmModel           model     = new EdmModel();
            EdmEntityType      entity    = new EdmEntityType("NS", "Entity");
            EdmEntityContainer container = new EdmEntityContainer("NS", "Default");

            container.AddSingleton("me", entity);
            model.AddElement(entity);
            model.AddElement(container);

            HttpRequest reqest = RequestFactory.Create(model);

            MetadataController metadataController = new MetadataController();

            metadataController.ControllerContext.HttpContext = reqest.HttpContext;

            // Act
            ODataServiceDocument actual = metadataController.GetServiceDocument();

            // Assert
            Assert.NotNull(actual);
            Assert.Empty(actual.EntitySets);
            Assert.Empty(actual.FunctionImports);
            ODataSingletonInfo singletonInfo = Assert.Single(actual.Singletons);

            Assert.Equal("me", singletonInfo.Name);
        }
Exemplo n.º 6
0
 public static void housekeep(CoreController core, HouseKeepEnvironmentModel env)
 {
     try {
         //
         LogController.logInfo(core, "Housekeep, grouprules");
         //
         //
         // GroupRules with bad ContentID
         //   Handled record by record removed to prevent CDEF reload
         //
         LogController.logInfo(core, "Deleting Group Rules with bad ContentID.");
         string sql = "Select ccGroupRules.ID"
                      + " From ccGroupRules LEFT JOIN ccContent on ccContent.ID=ccGroupRules.ContentID"
                      + " WHERE (ccContent.ID is null)";
         using (var csData = new CsModel(core)) {
             csData.openSql(sql);
             while (csData.ok())
             {
                 MetadataController.deleteContentRecord(core, "Group Rules", csData.getInteger("ID"));
                 csData.goNext();
             }
         }
         //
         // GroupRules with bad GroupID
         //
         LogController.logInfo(core, "Deleting Group Rules with bad GroupID.");
         sql = "delete ccGroupRules"
               + " From ccGroupRules"
               + " LEFT JOIN ccgroups on ccgroups.ID=ccGroupRules.GroupID"
               + " WHERE (ccgroups.ID is null)";
         core.db.executeNonQuery(sql);
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }
Exemplo n.º 7
0
        public void TestLongRunning_Test(int timeout,
                                         Mock <IIAM> iam,
                                         Mock <IAppConfig> config,
                                         Mock <IDataClient> dataClient,
                                         Mock <IJobProxy> jobProxy,
                                         Mock <IStoredProcedureRequest> greenplumRequest,
                                         Mock <ILogging> logging,
                                         Mock <ITaskLogging> taskLogging,
                                         Mock <IValidation> validation,
                                         Mock <IWorkStatusProxy> workStatusProxy,
                                         IOrchestrationJob orchestrationJob,
                                         ProjectConfig projectConfig,
                                         string customerShortName,
                                         string projectShortName,
                                         Guid id)
        {
            var fixture = new Fixture();

            config.SetupGet(x => x.IAMCustomerManagementUri).Returns(fixture.Create <Uri>().ToString());
            projectConfig.GreenplumConfig.RawConnectionString = Utilities.ValidConnectionString;

            dataClient.Setup(x => x.ExecuteScalar <object>(greenplumRequest.Object)).Returns(It.IsAny <object>());
            iam.Setup(x => x.GetProjectConfig(customerShortName, projectShortName)).Returns(projectConfig);

            var metaData = new MetadataController(config.Object, jobProxy.Object, logging.Object, taskLogging.Object, validation.Object, workStatusProxy.Object);
            var result   = metaData.TestLongRunning(dataClient.Object, iam.Object, customerShortName, projectShortName, timeout);

            result.Should().BeOfType <OkResult>();
        }
        public void ShouldReturn404WhenMetadataNotFound()
        {
            var serviceMock       = new Mock <IMetadataService>();
            var searchServiceMock = new Mock <ISearchService>();
            var controller        = new MetadataController(serviceMock.Object, searchServiceMock.Object);
            var result            = controller.Index(Uuid) as HttpNotFoundResult;

            result.Should().NotBeNull();
        }
        public void GetMetadata_Returns_EdmModelFromRequest()
        {
            IEdmModel model = new EdmModel();

            MetadataController controller = new MetadataController();
            controller.Request = new HttpRequestMessage();
            controller.Request.ODataProperties().Model = model;

            IEdmModel responseModel = controller.GetMetadata();
            Assert.Equal(model, responseModel);
        }
        public void GetMetadata_Throws_IfModelIsNotSetOnRequest()
        {
            HttpConfiguration configuration = new HttpConfiguration();
            MetadataController controller = new MetadataController();
            controller.Request = new HttpRequestMessage();

            Assert.Throws<InvalidOperationException>(() => controller.GetMetadata(),
                "The request must have an associated EDM model. Consider using the extension method " +
                "HttpConfiguration.Routes.MapODataServiceRoute to register a route that parses the OData URI and " +
                "attaches the model information.");
        }
Exemplo n.º 11
0
        public void GetMetadata_Throws_IfModelIsNotSetOnRequest()
        {
            HttpConfiguration  configuration = new HttpConfiguration();
            MetadataController controller    = new MetadataController();

            controller.Request = new HttpRequestMessage();

            Assert.Throws <InvalidOperationException>(() => controller.GetMetadata(),
                                                      "The request must have an associated EDM model. Consider using the extension method " +
                                                      "HttpConfiguration.Routes.MapODataServiceRoute to register a route that parses the OData URI and " +
                                                      "attaches the model information.");
        }
Exemplo n.º 12
0
 public MetadataControllerTest()
 {
     _service      = A.Fake <IMetadataService>();
     _controller   = new MetadataController(_service);
     _listResponse = new Response {
         Data = new List <MetaData>()
     };
     _singleResponse = new Response {
         Data = new MetaData()
     };
     _queryWithDefaultValues = BaseListQuery.DefaultValues("nb");
 }
Exemplo n.º 13
0
        public void GetMetadata_Returns_EdmModelFromRequest()
        {
            IEdmModel model = new EdmModel();

            MetadataController controller = new MetadataController();

            controller.Request = new HttpRequestMessage();
            controller.Request.ODataProperties().Model = model;

            IEdmModel responseModel = controller.GetMetadata();

            Assert.Equal(model, responseModel);
        }
 /// <summary>
 /// For memberSelect type content. memberSelectGroup, name set by xml file load, name get for xml file save, id and name get and set in code
 /// </summary>
 public string memberSelectGroupName_get(CoreController core)
 {
     if ((_memberSelectGroupName == null) && (_memberSelectGroupId != null))
     {
         if (_memberSelectGroupId == 0)
         {
             _memberSelectGroupName = "";
         }
         else
         {
             _memberSelectGroupName = MetadataController.getRecordName(core, "groups", GenericController.encodeInteger(_memberSelectGroupId));
         }
     }
     return(_memberSelectGroupName as string);
 }
        public void GetMetadataOnMetadataController_ReturnsODataModel()
        {
            // Arrange
            IEdmModel   model  = new EdmModel();
            HttpRequest reqest = RequestFactory.Create(model);

            MetadataController metadataController = new MetadataController();

            metadataController.ControllerContext.HttpContext = reqest.HttpContext;

            // Act
            IEdmModel actual = metadataController.GetMetadata();

            // Assert
            Assert.Same(model, actual);
        }
Exemplo n.º 16
0
 public override void Clear(string ContentNameList)
 {
     if (!string.IsNullOrEmpty(ContentNameList))
     {
         List <string> tableNameList = new List <string>();
         foreach (var contentName in new List <string>(ContentNameList.ToLowerInvariant().Split(',')))
         {
             string tableName = MetadataController.getContentTablename(cp.core, contentName).ToLowerInvariant();
             if (!tableNameList.Contains(tableName))
             {
                 tableNameList.Add(tableName);
                 cp.core.cache.invalidateTableObjects(tableName);
             }
         }
     }
 }
        public void GetODataServiceDocumentOnMetadataController_ThrowsInvalidOperationException_()
        {
            // Arrange
            HttpRequest reqest = RequestFactory.Create(model: null);

            MetadataController metadataController = new MetadataController();

            metadataController.ControllerContext.HttpContext = reqest.HttpContext;

            // Act
            Action test = () => metadataController.GetServiceDocument();

            // Assert
            ExceptionAssert.Throws <InvalidOperationException>(test,
                                                               "The request must have an associated EDM model. Consider registering Edm model calling AddOData().");
        }
        public void ShouldReturnRedirectUserToSeoUrl()
        {
            var serviceMock       = new Mock <IMetadataService>();
            var searchServiceMock = new Mock <ISearchService>();

            serviceMock.Setup(m => m.GetMetadataViewModelByUuid(Uuid)).Returns(new MetadataViewModel
            {
                Title        = "N50",
                ContactOwner = new Contact {
                    Organization = "Kartverket"
                }
            });
            var controller = new MetadataController(serviceMock.Object, searchServiceMock.Object);
            var result     = controller.Index(Uuid, "blabla", "testing") as RedirectToRouteResult;

            result.Should().NotBeNull();
        }
Exemplo n.º 19
0
        public IEnumerable <Entity.Tag> GetPeople()
        {
            try
            {
                return(MetadataController.GetTags(GetTagSearchOptions(TagSearchType.PeopleUserCanView)));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
        public bool CanUserEdit(System.Collections.Generic.IEnumerable <Entity.GalleryItem> galleryItems)
        {
            // POST /api/meta/canuseredit
            try
            {
                return(MetadataController.CanUserEditAllItems(galleryItems));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
        public void ShouldReturnMetadataForUuid()
        {
            var serviceMock       = new Mock <IMetadataService>();
            var searchServiceMock = new Mock <ISearchService>();

            serviceMock.Setup(m => m.GetMetadataViewModelByUuid(Uuid)).Returns(new MetadataViewModel
            {
                Title          = "N50",
                NorwegianTitle = "N50",
                ContactOwner   = new Contact {
                    Organization = "Kartverket"
                }
            });
            var controller = new MetadataController(serviceMock.Object, searchServiceMock.Object);
            var result     = controller.Index(Uuid, "kartverket", "n50") as ViewResult;

            result.Should().NotBeNull();
        }
Exemplo n.º 22
0
 public static void housekeep(CoreController core, HouseKeepEnvironmentModel env)
 {
     try {
         //
         LogController.logInfo(core, "HousekeepDaily, contentwatch");
         //
         using (var csData = new CsModel(core)) {
             string sql = "select cccontentwatch.id from cccontentwatch left join cccontent on cccontent.id=cccontentwatch.contentid  where (cccontent.id is null)or(cccontent.active=0)or(cccontent.active is null)";
             csData.openSql(sql);
             while (csData.ok())
             {
                 MetadataController.deleteContentRecord(core, "Content Watch", csData.getInteger("ID"));
                 csData.goNext();
             }
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }
        public IQueryable <Entity.MetaItem> GetMetaItemsForGalleryItems(Entity.GalleryItem[] galleryItems)
        {
            // GET /api/meta/galleryitems - Gets metadata items for the specified objects
            try
            {
                return(MetadataController.GetMetaItemsForGalleryItems(galleryItems).AsQueryable());
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
Exemplo n.º 24
0
        //====================================================================================================
        //
        public static void houseKeep_App_Daily_RemoveVisitRecords(CoreController core, DateTime DeleteBeforeDate)
        {
            try {
                //
                int    TimeoutSave         = 0;
                string SQL                 = null;
                string DeleteBeforeDateSQL = null;
                string appName             = null;
                string SQLTablePeople      = null;
                //
                // Set long timeout (30 min) needed for heavy work on big tables
                TimeoutSave = core.db.sqlCommandTimeout;
                core.db.sqlCommandTimeout = 1800;
                //
                SQLTablePeople = MetadataController.getContentTablename(core, "People");
                //
                appName             = core.appConfig.name;
                DeleteBeforeDateSQL = DbController.encodeSQLDate(DeleteBeforeDate);
                //
                // Visits older then archive age
                //
                LogController.logInfo(core, "Deleting visits before [" + DeleteBeforeDateSQL + "]");
                core.db.deleteTableRecordChunks("ccVisits", "(DateAdded<" + DeleteBeforeDateSQL + ")", 1000, 10000);
                //
                // Viewings with visits before the first
                //
                LogController.logInfo(core, "Deleting viewings with visitIDs lower then the lowest ccVisits.ID");
                core.db.deleteTableRecordChunks("ccviewings", "(visitid<(select min(ID) from ccvisits))", 1000, 10000);

                //
                // restore sved timeout
                //
                core.db.sqlCommandTimeout = TimeoutSave;
                return;
                //
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
        }
Exemplo n.º 25
0
        public IEnumerable <Business.Entity.Tag> GetTags(string q, int galleryId, int top = int.MaxValue, string sortBy = "notspecified", bool sortAscending = false)
        {
            try
            {
                TagSearchOptions.TagProperty sortProperty;
                if (!Enum.TryParse(sortBy, true, out sortProperty))
                {
                    sortProperty = TagSearchOptions.TagProperty.NotSpecified;
                }

                return(MetadataController.GetTags(TagSearchType.TagsUserCanView, q, galleryId, top, sortProperty, sortAscending));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Persists the metadata item to the data store. The current implementation requires that
        /// an existing item exist in the data store and only stores the contents of the
        /// <see cref="Entity.MetaItem.Value" /> property.
        /// </summary>
        /// <param name="metaItem">An instance of <see cref="Entity.MetaItem" /> to persist to the data
        /// store.</param>
        /// <returns>Entity.MetaItem.</returns>
        /// <exception cref="System.Web.Http.HttpResponseException">Thrown when an album or media object associated
        /// with the meta item doesn't exist or an error occurs.</exception>
        public Entity.MetaItem PutMetaItem(Entity.MetaItem metaItem)
        {
            try
            {
                return(MetadataController.Save(metaItem));
            }
            catch (InvalidAlbumException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent(String.Format("Could not find album with ID {0}", metaItem.MediaId)),
                    ReasonPhrase = "Album Not Found"
                });
            }
            catch (InvalidMediaObjectException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent(String.Format("One of the following errors occurred: (1) Could not find meta item with ID {0} (2) Could not find media object with ID {1} ", metaItem.Id, metaItem.MediaId)),
                    ReasonPhrase = "Media Object/Metadata Item Not Found"
                });
            }
            catch (GallerySecurityException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
Exemplo n.º 27
0
        public void PublishSQL_Test(Mock <IAppConfig> config,
                                    Mock <IJobProxy> jobProxy,
                                    Mock <ILogging> logging,
                                    Mock <ITaskLogging> taskLogging,
                                    Mock <IValidation> validation,
                                    Mock <IWorkStatusProxy> workStatusProxy,
                                    IOrchestrationJob orchestrationJob,
                                    string customerShortName,
                                    string projectShortName,
                                    Guid id)

        {
            var fixture = new Fixture();

            config.SetupGet(x => x.IAMCustomerManagementUri).Returns(fixture.Create <Uri>().ToString());
            config.SetupGet(x => x.AnalyticsEngineUri).Returns(fixture.Create <Uri>().ToString());

            jobProxy.Setup(x => x.GetJob(customerShortName, projectShortName, id)).Returns(orchestrationJob);

            var metaData = new MetadataController(config.Object, jobProxy.Object, logging.Object, taskLogging.Object, validation.Object, workStatusProxy.Object);
            var result   = metaData.PublishSql(new MockReportingServicesClient("{'PublishFlowchartMetadataReportingDB_RestResult':true}"), customerShortName, projectShortName, id);

            result.Should().BeOfType <OkResult>();
        }
Exemplo n.º 28
0
        public void RebuildItemForGallery(int metaNameId, int galleryId)
        {
            try
            {
                if (Utils.IsCurrentUserGalleryAdministrator(galleryId))
                {
                    var metaName = (MetadataItemName)metaNameId;
                    if (MetadataItemNameEnumHelper.IsValidFormattedMetadataItemName(metaName))
                    {
                        MetadataController.RebuildItemForGalleryAsync(metaName, galleryId);
                    }
                }
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
Exemplo n.º 29
0
 //
 //====================================================================================================
 /// <summary>
 /// Returns OK on success
 /// + available drive space
 /// + log size
 /// </summary>
 /// <param name="cp"></param>
 /// <returns></returns>
 public override object Execute(Contensive.BaseClasses.CPBaseClass cp)
 {
     try {
         var result = new StringBuilder();
         var core   = ((CPClass)cp).core;
         //
         // -- tmp, check for 10% free on C-drive and D-drive
         if (Directory.Exists(@"c:\"))
         {
             DriveInfo driveTest = new DriveInfo("c");
             double    freeSpace = Math.Round(100.0 * (Convert.ToDouble(driveTest.AvailableFreeSpace) / Convert.ToDouble(driveTest.TotalSize)), 2);
             if (freeSpace < 10)
             {
                 return("ERROR, Drive-C does not have 10% free");
             }
             result.AppendLine("ok, drive-c free space [" + freeSpace + "%], [" + (driveTest.AvailableFreeSpace / (1024 * 1024)).ToString("F2", CultureInfo.InvariantCulture) + " MB]");
         }
         if (Directory.Exists(@"d:\"))
         {
             DriveInfo driveTest = new DriveInfo("d");
             double    freeSpace = Math.Round(100.0 * (Convert.ToDouble(driveTest.AvailableFreeSpace) / Convert.ToDouble(driveTest.TotalSize)), 2);
             if (freeSpace < 10)
             {
                 return("ERROR, Drive-D does not have 10% free");
             }
             result.AppendLine("ok, drive-D free space [" + freeSpace + "%], [" + (driveTest.AvailableFreeSpace / (1024 * 1024)).ToString("F2", CultureInfo.InvariantCulture) + " MB]");
         }
         //
         // -- log files under 1MB
         if (!core.programDataFiles.pathExists("Logs/"))
         {
             core.programDataFiles.createPath("Logs/");
         }
         foreach (var fileDetail in core.programDataFiles.getFileList("Logs/"))
         {
             if (fileDetail.Size > 1000000)
             {
                 return("ERROR, log file size error [" + fileDetail.Name + "], size [" + fileDetail.Size + "]");
             }
         }
         result.AppendLine("ok, all log files under 1 MB");
         //
         // test default data connection
         try {
             using (var csData = new CsModel(core)) {
                 int recordId = 0;
                 if (csData.insert("Properties"))
                 {
                     recordId = csData.getInteger("ID");
                 }
                 if (recordId == 0)
                 {
                     return("ERROR, Failed to insert record in default data source.");
                 }
                 else
                 {
                     MetadataController.deleteContentRecord(core, "Properties", recordId);
                 }
             }
         } catch (Exception exDb) {
             return("ERROR, exception occured during default data source record insert, [" + exDb + "].");
         }
         result.AppendLine("ok, database connection passed.");
         //
         // -- test for taskscheduler not running
         if (DbBaseModel.createList <AddonModel>(core.cpParent, "(ProcessNextRun<" + DbController.encodeSQLDate(core.dateTimeNowMockable.AddHours(-1)) + ")").Count > 0)
         {
             return("ERROR, there are process addons unexecuted for over 1 hour. TaskScheduler may not be enabled, or no server is running the Contensive Task Service.");
         }
         if (DbBaseModel.createList <TaskModel>(core.cpParent, "(dateCompleted is null)and(dateStarted<" + DbController.encodeSQLDate(core.dateTimeNowMockable.AddHours(-1)) + ")").Count > 0)
         {
             return("ERROR, there are tasks that have been executing for over 1 hour. The Task Runner Server may have stopped.");
         }
         result.AppendLine("ok, taskscheduler running.");
         //
         // -- test for taskrunner not running
         if (DbBaseModel.createList <TaskModel>(core.cpParent, "(dateCompleted is null)and(dateStarted is null)").Count > 100)
         {
             return("ERROR, there are over 100 task waiting to be execute. The Task Runner Server may have stopped.");
         }
         result.AppendLine("ok, taskrunner running.");
         //
         // -- verify the email process is running.
         if (cp.Site.GetDate("EmailServiceLastCheck") < core.dateTimeNowMockable.AddHours(-1))
         {
             return("ERROR, Email process has not executed for over 1 hour.");
         }
         result.AppendLine("ok, email process running.");
         //
         // -- last -- if alarm folder is not empty, fail diagnostic. Last so others can add an alarm entry
         if (!core.programDataFiles.pathExists("Alarms/"))
         {
             core.programDataFiles.createPath("Alarms/");
         }
         foreach (var alarmFile in core.programDataFiles.getFileList("Alarms/"))
         {
             return("ERROR, Alarm folder is not empty, [" + core.programDataFiles.readFileText("Alarms/" + alarmFile.Name) + "].");
         }
         // -- verify the default username=root, password=contensive is not present
         var rootUserList = PersonModel.createList <PersonModel>(cp, "((username='******')and(password='******')and(active>0))");
         if (rootUserList.Count > 0)
         {
             return("ERROR, delete or inactive default user root/contensive.");
         }
         //
         // -- meta data test- lookup field without lookup set
         string sql = "select c.id as contentid, c.name as contentName, f.* from ccfields f left join ccContent c on c.id = f.LookupContentID where f.Type = 7 and c.id is null and f.LookupContentID > 0 and f.Active > 0 and f.Authorable > 0";
         using (DataTable dt = core.db.executeQuery(sql)) {
             if (!dt.Rows.Count.Equals(0))
             {
                 string badFieldList = "";
                 foreach (DataRow row in dt.Rows)
                 {
                     badFieldList += "," + row["contentName"] + "." + row["name"].ToString();
                 }
                 return("ERROR, the following field(s) are configured as lookup, but the field's lookup-content is not set [" + badFieldList.Substring(1) + "].");
             }
         }
         //
         // -- metadata test - many to many setup
         sql = "select f.id,f.name as fieldName,f.ManyToManyContentID, f.ManyToManyRuleContentID, f.ManyToManyRulePrimaryField, f.ManyToManyRuleSecondaryField"
               + " ,pc.name as primaryContentName"
               + " , sc.name as secondaryContentName"
               + " , r.name as ruleContentName"
               + " , rp.name as PrimaryContentField"
               + " , rs.name as SecondaryContentField"
               + " from ccfields f"
               + " left join cccontent sc on sc.id = f.ManyToManyContentID"
               + " left join cccontent pc on pc.id = f.contentid"
               + " left join cccontent r on r.id = f.ManyToManyRuleContentID"
               + " left join ccfields rp on (rp.name = f.ManyToManyRulePrimaryField)and(rp.ContentID = r.id)"
               + " left join ccfields rs on(rs.name = f.ManyToManyRuleSecondaryField)and(rs.ContentID = r.id)"
               + " where"
               + " (f.type = 14)and(f.Authorable > 0)and(f.active > 0)"
               + " and((1 = 0)or(sc.id is null)or(pc.id is null)or(r.id is null)or(rp.id is null)or(rs.id is null))";
         using (DataTable dt = core.db.executeQuery(sql)) {
             if (!dt.Rows.Count.Equals(0))
             {
                 string badFieldList = "";
                 foreach (DataRow row in dt.Rows)
                 {
                     badFieldList += "," + row["primaryContentName"] + "." + row["fieldName"].ToString();
                 }
                 return("ERROR, the following field(s) are configured as many-to-many, but the field's many-to-many metadata is not set [" + badFieldList.Substring(1) + "].");
             }
         }
         return("ok, all server diagnostics passed" + Environment.NewLine + result.ToString());
     } catch (Exception ex) {
         cp.Site.ErrorReport(ex);
         return("ERROR, unexpected exception during diagnostics");
     }
 }
Exemplo n.º 30
0
        //====================================================================================================
        /// <summary>
        /// Summarize the page views, excludes non-cookie visits, excludes administrator and developer visits, excludes authenticated users with ExcludeFromReporting
        /// </summary>
        /// <param name="core"></param>
        /// <param name="StartTimeDate"></param>
        /// <param name="EndTimeDate"></param>
        /// <param name="HourDuration"></param>
        /// <param name="BuildVersion"></param>
        /// <param name="OldestVisitSummaryWeCareAbout"></param>
        //
        public static void pageViewSummary(CoreController core, DateTime StartTimeDate, DateTime EndTimeDate, int HourDuration, string BuildVersion, DateTime OldestVisitSummaryWeCareAbout)
        {
            int    hint    = 0;
            string hinttxt = "";

            try {
                XmlDocument LibraryCollections = new XmlDocument();
                XmlDocument LocalCollections   = new XmlDocument();
                XmlDocument Doc = new XmlDocument();
                {
                    hint = 1;
                    DateTime PeriodStart = default;
                    PeriodStart = StartTimeDate;
                    if (PeriodStart < OldestVisitSummaryWeCareAbout)
                    {
                        PeriodStart = OldestVisitSummaryWeCareAbout;
                    }
                    DateTime PeriodDatePtr = default;
                    PeriodDatePtr = PeriodStart.Date;
                    while (PeriodDatePtr < EndTimeDate)
                    {
                        hint = 2;
                        //
                        hinttxt = ", HourDuration [" + HourDuration + "], PeriodDatePtr [" + PeriodDatePtr + "], PeriodDatePtr.AddHours(HourDuration / 2.0) [" + PeriodDatePtr.AddHours(HourDuration / 2.0) + "]";
                        int DateNumber = encodeInteger((PeriodDatePtr - default(DateTime)).TotalDays);
                        // encodeInteger(PeriodDatePtr.AddHours(HourDuration / 2.0).ToOADate());
                        int      TimeNumber = encodeInteger(PeriodDatePtr.TimeOfDay.TotalHours);
                        DateTime DateStart  = default(DateTime);
                        DateStart = PeriodDatePtr.Date;
                        DateTime DateEnd = default(DateTime);
                        DateEnd = PeriodDatePtr.AddHours(HourDuration).Date;
                        string PageTitle = "";
                        int    PageId    = 0;
                        int    PageViews = 0;
                        int    AuthenticatedPageViews = 0;
                        int    MobilePageViews        = 0;
                        int    BotPageViews           = 0;
                        int    NoCookiePageViews      = 0;
                        //
                        // Loop through all the pages hit during this period
                        //
                        //
                        // for now ignore the problem caused by addons like Blogs creating multiple 'pages' within on pageid
                        // One way to handle this is to expect the addon to set something unquie in he page title
                        // then use the title to distinguish a page. The problem with this is the current system puts the
                        // visit number and page number in the name. if we select on district name, they will all be.
                        //
                        using (var csPages = new CsModel(core)) {
                            string sql = "select distinct recordid,pagetitle from ccviewings h"
                                         + " where (h.recordid<>0)"
                                         + " and(h.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                                         + " and (h.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                                         + " and((h.ExcludeFromAnalytics is null)or(h.ExcludeFromAnalytics=0))"
                                         + "order by recordid";
                            hint = 3;
                            if (!csPages.openSql(sql))
                            {
                                //
                                // no hits found - add or update a single record for this day so we know it has been calculated
                                csPages.open("Page View Summary", "(timeduration=" + HourDuration + ")and(DateNumber=" + DateNumber + ")and(TimeNumber=" + TimeNumber + ")and(pageid=" + PageId + ")and(pagetitle=" + DbController.encodeSQLText(PageTitle) + ")");
                                if (!csPages.ok())
                                {
                                    csPages.close();
                                    csPages.insert("Page View Summary");
                                }
                                //
                                if (csPages.ok())
                                {
                                    csPages.set("name", HourDuration + " hr summary for " + DateTime.MinValue.AddDays(DateNumber) + " " + TimeNumber + ":00, " + PageTitle);
                                    csPages.set("DateNumber", DateNumber);
                                    csPages.set("TimeNumber", TimeNumber);
                                    csPages.set("TimeDuration", HourDuration);
                                    csPages.set("PageViews", PageViews);
                                    csPages.set("PageID", PageId);
                                    csPages.set("PageTitle", PageTitle);
                                    csPages.set("AuthenticatedPageViews", AuthenticatedPageViews);
                                    csPages.set("NoCookiePageViews", NoCookiePageViews);
                                    {
                                        csPages.set("MobilePageViews", MobilePageViews);
                                        csPages.set("BotPageViews", BotPageViews);
                                    }
                                }
                                csPages.close();
                                hint = 4;
                            }
                            else
                            {
                                hint = 5;
                                //
                                // add an entry for each page hit on this day
                                //
                                while (csPages.ok())
                                {
                                    PageId    = csPages.getInteger("recordid");
                                    PageTitle = csPages.getText("pagetitle");
                                    string baseCriteria = ""
                                                          + " (h.recordid=" + PageId + ")"
                                                          + " "
                                                          + " and(h.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                                                          + " and(h.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                                                          + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                                                          + " and((h.ExcludeFromAnalytics is null)or(h.ExcludeFromAnalytics=0))"
                                                          + "";
                                    if (!string.IsNullOrEmpty(PageTitle))
                                    {
                                        baseCriteria = baseCriteria + "and(h.pagetitle=" + DbController.encodeSQLText(PageTitle) + ")";
                                    }
                                    hint = 6;
                                    //
                                    // Total Page Views
                                    using (var csPageViews = new CsModel(core)) {
                                        sql = "select count(h.id) as cnt"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and (v.CookieSupport<>0)"
                                              + "";
                                        csPageViews.openSql(sql);
                                        if (csPageViews.ok())
                                        {
                                            PageViews = csPageViews.getInteger("cnt");
                                        }
                                    }
                                    //
                                    // Authenticated Visits
                                    //
                                    using (var csAuthPages = new CsModel(core)) {
                                        sql = "select count(h.id) as cnt"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and(v.CookieSupport<>0)"
                                              + " and(v.visitAuthenticated<>0)"
                                              + "";
                                        csAuthPages.openSql(sql);
                                        if (csAuthPages.ok())
                                        {
                                            AuthenticatedPageViews = csAuthPages.getInteger("cnt");
                                        }
                                    }
                                    //
                                    // No Cookie Page Views
                                    //
                                    using (var csNoCookie = new CsModel(core)) {
                                        sql = "select count(h.id) as NoCookiePageViews"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and((v.CookieSupport=0)or(v.CookieSupport is null))"
                                              + "";
                                        csNoCookie.openSql(sql);
                                        if (csNoCookie.ok())
                                        {
                                            NoCookiePageViews = csNoCookie.getInteger("NoCookiePageViews");
                                        }
                                    }
                                    //
                                    //
                                    // Mobile Visits
                                    using (var csMobileVisits = new CsModel(core)) {
                                        sql = "select count(h.id) as cnt"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and(v.CookieSupport<>0)"
                                              + " and(v.mobile<>0)"
                                              + "";
                                        csMobileVisits.openSql(sql);
                                        if (csMobileVisits.ok())
                                        {
                                            MobilePageViews = csMobileVisits.getInteger("cnt");
                                        }
                                    }
                                    //
                                    // Bot Visits
                                    using (var csBotVisits = new CsModel(core)) {
                                        sql = "select count(h.id) as cnt"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and(v.CookieSupport<>0)"
                                              + " and(v.bot<>0)"
                                              + "";
                                        csBotVisits.openSql(sql);
                                        if (csBotVisits.ok())
                                        {
                                            BotPageViews = csBotVisits.getInteger("cnt");
                                        }
                                    }
                                    //
                                    // Add or update the Visit Summary Record
                                    //
                                    using (var csPVS = new CsModel(core)) {
                                        if (!csPVS.open("Page View Summary", "(timeduration=" + HourDuration + ")and(DateNumber=" + DateNumber + ")and(TimeNumber=" + TimeNumber + ")and(pageid=" + PageId + ")and(pagetitle=" + DbController.encodeSQLText(PageTitle) + ")"))
                                        {
                                            csPVS.insert("Page View Summary");
                                        }
                                        //
                                        if (csPVS.ok())
                                        {
                                            hint = 11;
                                            string PageName = "";
                                            if (string.IsNullOrEmpty(PageTitle))
                                            {
                                                PageName = MetadataController.getRecordName(core, "page content", PageId);
                                                csPVS.set("name", HourDuration + " hr summary for " + DateTime.MinValue.AddDays(DateNumber) + " " + TimeNumber + ":00, " + PageName);
                                                csPVS.set("PageTitle", PageName);
                                            }
                                            else
                                            {
                                                csPVS.set("name", HourDuration + " hr summary for " + DateTime.MinValue.AddDays(DateNumber) + " " + TimeNumber + ":00, " + PageTitle);
                                                csPVS.set("PageTitle", PageTitle);
                                            }
                                            csPVS.set("DateNumber", DateNumber);
                                            csPVS.set("TimeNumber", TimeNumber);
                                            csPVS.set("TimeDuration", HourDuration);
                                            csPVS.set("PageViews", PageViews);
                                            csPVS.set("PageID", PageId);
                                            csPVS.set("AuthenticatedPageViews", AuthenticatedPageViews);
                                            csPVS.set("NoCookiePageViews", NoCookiePageViews);
                                            hint = 12;
                                            {
                                                csPVS.set("MobilePageViews", MobilePageViews);
                                                csPVS.set("BotPageViews", BotPageViews);
                                            }
                                        }
                                    }
                                    csPages.goNext();
                                }
                            }
                        }
                        PeriodDatePtr = PeriodDatePtr.AddHours(HourDuration);
                    }
                }
                //
                return;
            } catch (Exception ex) {
                LogController.logError(core, ex, "hint [" + hint + "]");
            }
        }
Exemplo n.º 31
0
        //
        //====================================================================================================
        /// <summary>
        /// Get the Configure Edit
        /// </summary>
        /// <param name="cp"></param>
        /// <returns></returns>
        public static string get(CPClass cp)
        {
            CoreController core = cp.core;

            try {
                KeyPtrController Index = new KeyPtrController();
                int    ContentId       = cp.Doc.GetInteger(RequestNameToolContentId);
                var    contentMetadata = ContentMetadataModel.create(core, ContentId, true, true);
                int    RecordCount     = 0;
                int    formFieldId     = 0;
                string StatusMessage   = "";
                string ErrorMessage    = "";
                bool   ReloadCDef      = cp.Doc.GetBoolean("ReloadCDef");
                if (contentMetadata != null)
                {
                    string ToolButton = cp.Doc.GetText("Button");
                    //
                    if (!string.IsNullOrEmpty(ToolButton))
                    {
                        bool AllowContentAutoLoad = false;
                        if (ToolButton != ButtonCancel)
                        {
                            //
                            // Save the form changes
                            //
                            AllowContentAutoLoad = cp.Site.GetBoolean("AllowContentAutoLoad", true);
                            cp.Site.SetProperty("AllowContentAutoLoad", "false");
                            //
                            // ----- Save the input
                            //
                            RecordCount = GenericController.encodeInteger(cp.Doc.GetInteger("dtfaRecordCount"));
                            if (RecordCount > 0)
                            {
                                int RecordPointer = 0;
                                for (RecordPointer = 0; RecordPointer < RecordCount; RecordPointer++)
                                {
                                    //
                                    string formFieldName = cp.Doc.GetText("dtfaName." + RecordPointer);
                                    CPContentBaseClass.FieldTypeIdEnum formFieldTypeId = (CPContentBaseClass.FieldTypeIdEnum)cp.Doc.GetInteger("dtfaType." + RecordPointer);
                                    formFieldId = GenericController.encodeInteger(cp.Doc.GetInteger("dtfaID." + RecordPointer));
                                    bool formFieldInherited = cp.Doc.GetBoolean("dtfaInherited." + RecordPointer);
                                    //
                                    // problem - looking for the name in the Db using the form's name, but it could have changed.
                                    // have to look field up by id
                                    //
                                    foreach (KeyValuePair <string, Processor.Models.Domain.ContentFieldMetadataModel> cdefFieldKvp in contentMetadata.fields)
                                    {
                                        if (cdefFieldKvp.Value.id == formFieldId)
                                        {
                                            //
                                            // Field was found in CDef
                                            //
                                            if (cdefFieldKvp.Value.inherited && (!formFieldInherited))
                                            {
                                                //
                                                // Was inherited, but make a copy of the field
                                                //
                                                using (var CSTarget = new CsModel(core)) {
                                                    if (CSTarget.insert("Content Fields"))
                                                    {
                                                        using (var CSSource = new CsModel(core)) {
                                                            if (CSSource.openRecord("Content Fields", formFieldId))
                                                            {
                                                                CSSource.copyRecord(CSTarget);
                                                            }
                                                        }
                                                        formFieldId = CSTarget.getInteger("ID");
                                                        CSTarget.set("ContentID", ContentId);
                                                    }
                                                    CSTarget.close();
                                                }
                                                ReloadCDef = true;
                                            }
                                            else if ((!cdefFieldKvp.Value.inherited) && (formFieldInherited))
                                            {
                                                //
                                                // Was a field, make it inherit from it's parent
                                                MetadataController.deleteContentRecord(core, "Content Fields", formFieldId);
                                                ReloadCDef = true;
                                            }
                                            else if ((!cdefFieldKvp.Value.inherited) && (!formFieldInherited))
                                            {
                                                //
                                                // not inherited, save the field values and mark for a reload
                                                //
                                                {
                                                    if (formFieldName.IndexOf(" ") != -1)
                                                    {
                                                        //
                                                        // remoave spaces from new name
                                                        //
                                                        StatusMessage = StatusMessage + "<LI>Field [" + formFieldName + "] was renamed [" + GenericController.strReplace(formFieldName, " ", "") + "] because the field name can not include spaces.</LI>";
                                                        formFieldName = GenericController.strReplace(formFieldName, " ", "");
                                                    }
                                                    //
                                                    string SQL = null;
                                                    //
                                                    if ((!string.IsNullOrEmpty(formFieldName)) && ((int)formFieldTypeId != 0) && ((cdefFieldKvp.Value.nameLc == "") || (cdefFieldKvp.Value.fieldTypeId == 0)))
                                                    {
                                                        //
                                                        // Create Db field, Field is good but was not before
                                                        //
                                                        core.db.createSQLTableField(contentMetadata.tableName, formFieldName, formFieldTypeId);
                                                        StatusMessage = StatusMessage + "<LI>Field [" + formFieldName + "] was saved to this content definition and a database field was created in [" + contentMetadata.tableName + "].</LI>";
                                                    }
                                                    else if ((string.IsNullOrEmpty(formFieldName)) || ((int)formFieldTypeId == 0))
                                                    {
                                                        //
                                                        // name blank or type=0 - do nothing but tell them
                                                        //
                                                        if (string.IsNullOrEmpty(formFieldName) && ((int)formFieldTypeId == 0))
                                                        {
                                                            ErrorMessage += "<LI>Field number " + (RecordPointer + 1) + " was saved to this content definition but no database field was created because a name and field type are required.</LI>";
                                                        }
                                                        else if (formFieldName == "unnamedfield" + formFieldId.ToString())
                                                        {
                                                            ErrorMessage += "<LI>Field number " + (RecordPointer + 1) + " was saved to this content definition but no database field was created because a field name is required.</LI>";
                                                        }
                                                        else
                                                        {
                                                            ErrorMessage += "<LI>Field [" + formFieldName + "] was saved to this content definition but no database field was created because a field type are required.</LI>";
                                                        }
                                                    }
                                                    else if ((formFieldName == cdefFieldKvp.Value.nameLc) && (formFieldTypeId != cdefFieldKvp.Value.fieldTypeId))
                                                    {
                                                        //
                                                        // Field Type changed, must be done manually
                                                        //
                                                        ErrorMessage += "<LI>Field [" + formFieldName + "] changed type from [" + DbBaseModel.getRecordName <ContentFieldTypeModel>(core.cpParent, (int)cdefFieldKvp.Value.fieldTypeId) + "] to [" + DbBaseModel.getRecordName <ContentFieldTypeModel>(core.cpParent, (int)formFieldTypeId) + "]. This may have caused a problem converting content.</LI>";
                                                        int DataSourceTypeId = core.db.getDataSourceType();
                                                        switch (DataSourceTypeId)
                                                        {
                                                        case DataSourceTypeODBCMySQL:
                                                            SQL = "alter table " + contentMetadata.tableName + " change " + cdefFieldKvp.Value.nameLc + " " + cdefFieldKvp.Value.nameLc + " " + core.db.getSQLAlterColumnType(formFieldTypeId) + ";";
                                                            break;

                                                        default:
                                                            SQL = "alter table " + contentMetadata.tableName + " alter column " + cdefFieldKvp.Value.nameLc + " " + core.db.getSQLAlterColumnType(formFieldTypeId) + ";";
                                                            break;
                                                        }
                                                        core.db.executeNonQuery(SQL);
                                                    }
                                                    SQL = "Update ccFields"
                                                          + " Set name=" + DbController.encodeSQLText(formFieldName)
                                                          + ",type=" + (int)formFieldTypeId
                                                          + ",caption=" + DbController.encodeSQLText(cp.Doc.GetText("dtfaCaption." + RecordPointer))
                                                          + ",DefaultValue=" + DbController.encodeSQLText(cp.Doc.GetText("dtfaDefaultValue." + RecordPointer))
                                                          + ",EditSortPriority=" + DbController.encodeSQLText(GenericController.encodeText(cp.Doc.GetInteger("dtfaEditSortPriority." + RecordPointer)))
                                                          + ",Active=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaActive." + RecordPointer))
                                                          + ",ReadOnly=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaReadOnly." + RecordPointer))
                                                          + ",Authorable=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaAuthorable." + RecordPointer))
                                                          + ",Required=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaRequired." + RecordPointer))
                                                          + ",UniqueName=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaUniqueName." + RecordPointer))
                                                          + ",TextBuffered=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaTextBuffered." + RecordPointer))
                                                          + ",Password="******"dtfaPassword." + RecordPointer))
                                                          + ",HTMLContent=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaHTMLContent." + RecordPointer))
                                                          + ",EditTab=" + DbController.encodeSQLText(cp.Doc.GetText("dtfaEditTab." + RecordPointer))
                                                          + ",Scramble=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaScramble." + RecordPointer)) + "";
                                                    if (core.session.isAuthenticatedAdmin())
                                                    {
                                                        SQL += ",adminonly=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaAdminOnly." + RecordPointer));
                                                    }
                                                    if (core.session.isAuthenticatedDeveloper())
                                                    {
                                                        SQL += ",DeveloperOnly=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaDeveloperOnly." + RecordPointer));
                                                    }
                                                    SQL += " where ID=" + formFieldId;
                                                    core.db.executeNonQuery(SQL);
                                                    ReloadCDef = true;
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                            core.cache.invalidateAll();
                            core.clearMetaData();
                        }
                        if (ToolButton == ButtonAdd)
                        {
                            //
                            // ----- Insert a blank Field
                            var defaultValues = ContentMetadataModel.getDefaultValueDict(core, ContentFieldModel.tableMetadata.contentName);
                            var field         = ContentFieldModel.addDefault <ContentFieldModel>(core.cpParent, defaultValues);
                            field.name             = "unnamedField" + field.id.ToString();
                            field.contentId        = ContentId;
                            field.editSortPriority = 0;
                            field.save(core.cpParent);
                            ReloadCDef = true;
                        }
                        //
                        // ----- Button Reload CDef
                        if (ToolButton == ButtonSaveandInvalidateCache)
                        {
                            core.cache.invalidateAll();
                            core.clearMetaData();
                        }
                        //
                        // ----- Restore Content Autoload site property
                        //
                        if (AllowContentAutoLoad)
                        {
                            cp.Site.SetProperty("AllowContentAutoLoad", AllowContentAutoLoad.ToString());
                        }
                        //
                        // ----- Cancel or Save, reload CDef and go
                        //
                        if ((ToolButton == ButtonCancel) || (ToolButton == ButtonOK))
                        {
                            //
                            // ----- Exit back to menu
                            //
                            return(core.webServer.redirect(core.appConfig.adminRoute, "Tool-ConfigureContentEdit, ok or cancel button, go to root."));
                        }
                    }
                }
                //
                //   Print Output
                string description = ""
                                     + HtmlController.p("Use this tool to add or modify content definition fields and the underlying sql table fields.")
                                     + ((ContentId.Equals(0)) ? "" : ""
                                        + HtmlController.ul(""
                                                            + HtmlController.li(HtmlController.a("Edit Content", "?aa=0&cid=3&id=" + ContentId + "&tx=&ad=0&asf=1&af=4", "nav-link btn btn-primary"), "nav-item mr-1")
                                                            + HtmlController.li(HtmlController.a("Edit Records", "?cid=" + ContentId, "nav-link btn btn-primary"), "nav-item mr-1")
                                                            + HtmlController.li(HtmlController.a("Select Different Fields", "?af=105", "nav-link btn btn-primary"), "nav-item mr-1")
                                                            , "nav")
                                        );
                StringBuilderLegacyController Stream = new StringBuilderLegacyController();
                Stream.add(AdminUIController.getHeaderTitleDescription("Manage Admin Edit Fields", description));
                //
                // -- status of last operation
                if (!string.IsNullOrEmpty(StatusMessage))
                {
                    Stream.add(AdminUIController.getToolFormRow(core, "<UL>" + StatusMessage + "</UL>"));
                }
                //
                // -- errors with last operations
                if (!string.IsNullOrEmpty(ErrorMessage))
                {
                    Stream.add(HtmlController.div("There was a problem saving these changes" + "<UL>" + ErrorMessage + "</UL>", "ccError"));
                }
                if (ReloadCDef)
                {
                    contentMetadata = Processor.Models.Domain.ContentMetadataModel.create(core, ContentId, true, true);
                }
                string ButtonList = ButtonCancel + "," + ButtonSelect;
                if (ContentId == 0)
                {
                    //
                    // content tables that have edit forms to Configure
                    bool isEmptyList = false;
                    Stream.add(AdminUIController.getToolFormInputRow(core, "Select a Content Definition to Configure", AdminUIEditorController.getLookupContentEditor(core, RequestNameToolContentId, ContentId, ContentMetadataModel.getContentId(core, "Content"), ref isEmptyList, false, "", "", false, "")));
                }
                else
                {
                    //
                    // Configure edit form
                    Stream.add(HtmlController.inputHidden(RequestNameToolContentId, ContentId));
                    Stream.add(core.html.getPanelTop());
                    ButtonList = ButtonCancel + "," + ButtonSave + "," + ButtonOK + "," + ButtonAdd;
                    //
                    // Get a new copy of the content definition
                    //
                    Stream.add(SpanClassAdminNormal + "<P><B>" + contentMetadata.name + "</b></P>");
                    Stream.add("<table border=\"0\" cellpadding=\"1\" cellspacing=\"1\" width=\"100%\">");
                    //
                    int  ParentContentId  = contentMetadata.parentId;
                    bool AllowCDefInherit = false;
                    Processor.Models.Domain.ContentMetadataModel ParentCDef = null;
                    if (ParentContentId == -1)
                    {
                        AllowCDefInherit = false;
                    }
                    else
                    {
                        AllowCDefInherit = true;
                        string ParentContentName = MetadataController.getContentNameByID(core, ParentContentId);
                        ParentCDef = Processor.Models.Domain.ContentMetadataModel.create(core, ParentContentId, true, true);
                    }
                    bool NeedFootNote1 = false;
                    bool NeedFootNote2 = false;
                    if (contentMetadata.fields.Count > 0)
                    {
                        //
                        // -- header row
                        Stream.add("<tr>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\"></td>");
                        if (!AllowCDefInherit)
                        {
                            Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Inherited*</b></span></td>");
                            NeedFootNote1 = true;
                        }
                        else
                        {
                            Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Inherited</b></span></td>");
                        }
                        Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Field</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Caption</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Edit Tab</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Default</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Type</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b>Edit<br>Order</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Active</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b>Read<br>Only</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Auth</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Req</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Unique</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b>Text<br>Buffer</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Pass</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b>Text<br>Scrm</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>HTML</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b>Admin<br>Only</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b>Dev<br>Only</b></span></td>");
                        Stream.add("</tr>");
                        RecordCount = 0;
                        //
                        // Build a select template for Type
                        //
                        string TypeSelectTemplate = core.html.selectFromContent("menuname", -1, "Content Field Types", "", "unknown");
                        //
                        // Index the sort order
                        //
                        List <FieldSortClass> fieldList = new List <FieldSortClass>();
                        int FieldCount = contentMetadata.fields.Count;
                        foreach (var keyValuePair in contentMetadata.fields)
                        {
                            FieldSortClass fieldSort = new FieldSortClass();
                            string         sortOrder = "";
                            fieldSort.field = keyValuePair.Value;
                            sortOrder       = "";
                            if (fieldSort.field.active)
                            {
                                sortOrder += "0";
                            }
                            else
                            {
                                sortOrder += "1";
                            }
                            if (fieldSort.field.authorable)
                            {
                                sortOrder += "0";
                            }
                            else
                            {
                                sortOrder += "1";
                            }
                            sortOrder     += fieldSort.field.editTabName + getIntegerString(fieldSort.field.editSortPriority, 10) + getIntegerString(fieldSort.field.id, 10);
                            fieldSort.sort = sortOrder;
                            fieldList.Add(fieldSort);
                        }
                        fieldList.Sort((p1, p2) => p1.sort.CompareTo(p2.sort));
                        StringBuilderLegacyController StreamValidRows = new StringBuilderLegacyController();
                        var contentFieldsCdef = Processor.Models.Domain.ContentMetadataModel.createByUniqueName(core, "content fields");
                        foreach (FieldSortClass fieldsort in fieldList)
                        {
                            StringBuilderLegacyController streamRow = new StringBuilderLegacyController();
                            bool rowValid = true;
                            //
                            // If Field has name and type, it is locked and can not be changed
                            //
                            bool FieldLocked = (fieldsort.field.nameLc != "") && (fieldsort.field.fieldTypeId != 0);
                            //
                            // put the menu into the current menu format
                            //
                            formFieldId = fieldsort.field.id;
                            streamRow.add(HtmlController.inputHidden("dtfaID." + RecordCount, formFieldId));
                            streamRow.add("<tr>");
                            //
                            // edit button
                            //
                            streamRow.add("<td class=\"ccPanelInput\" align=\"left\">" + AdminUIController.getRecordEditAnchorTag(core, contentFieldsCdef, formFieldId) + "</td>");
                            //
                            // Inherited
                            //
                            if (!AllowCDefInherit)
                            {
                                //
                                // no parent
                                //
                                streamRow.add("<td class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "False</span></td>");
                            }
                            else if (fieldsort.field.inherited)
                            {
                                //
                                // inherited property
                                //
                                streamRow.add("<td class=\"ccPanelInput\" align=\"center\">" + HtmlController.checkbox("dtfaInherited." + RecordCount, fieldsort.field.inherited) + "</td>");
                            }
                            else
                            {
                                Processor.Models.Domain.ContentFieldMetadataModel parentField = null;
                                //
                                // CDef has a parent, but the field is non-inherited, test for a matching Parent Field
                                //
                                if (ParentCDef == null)
                                {
                                    foreach (KeyValuePair <string, Processor.Models.Domain.ContentFieldMetadataModel> kvp in ParentCDef.fields)
                                    {
                                        if (kvp.Value.nameLc == fieldsort.field.nameLc)
                                        {
                                            parentField = kvp.Value;
                                            break;
                                        }
                                    }
                                }
                                if (parentField == null)
                                {
                                    streamRow.add("<td class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "False**</span></td>");
                                    NeedFootNote2 = true;
                                }
                                else
                                {
                                    streamRow.add("<td class=\"ccPanelInput\" align=\"center\">" + HtmlController.checkbox("dtfaInherited." + RecordCount, fieldsort.field.inherited) + "</td>");
                                }
                            }
                            //
                            // name
                            //
                            bool tmpValue = string.IsNullOrEmpty(fieldsort.field.nameLc);
                            rowValid = rowValid && !tmpValue;
                            streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>");
                            if (fieldsort.field.inherited)
                            {
                                streamRow.add(SpanClassAdminSmall + fieldsort.field.nameLc + "&nbsp;</SPAN>");
                            }
                            else if (FieldLocked)
                            {
                                streamRow.add(SpanClassAdminSmall + fieldsort.field.nameLc + "&nbsp;</SPAN><input type=hidden name=dtfaName." + RecordCount + " value=\"" + fieldsort.field.nameLc + "\">");
                            }
                            else
                            {
                                streamRow.add(HtmlController.inputText_Legacy(core, "dtfaName." + RecordCount, fieldsort.field.nameLc, 1, 10));
                            }
                            streamRow.add("</nobr></td>");
                            //
                            // caption
                            //
                            streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>");
                            if (fieldsort.field.inherited)
                            {
                                streamRow.add(SpanClassAdminSmall + fieldsort.field.caption + "</SPAN>");
                            }
                            else
                            {
                                streamRow.add(HtmlController.inputText_Legacy(core, "dtfaCaption." + RecordCount, fieldsort.field.caption, 1, 10));
                            }
                            streamRow.add("</nobr></td>");
                            //
                            // Edit Tab
                            //
                            streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>");
                            if (fieldsort.field.inherited)
                            {
                                streamRow.add(SpanClassAdminSmall + fieldsort.field.editTabName + "</SPAN>");
                            }
                            else
                            {
                                streamRow.add(HtmlController.inputText_Legacy(core, "dtfaEditTab." + RecordCount, fieldsort.field.editTabName, 1, 10));
                            }
                            streamRow.add("</nobr></td>");
                            //
                            // default
                            //
                            streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>");
                            if (fieldsort.field.inherited)
                            {
                                streamRow.add(SpanClassAdminSmall + GenericController.encodeText(fieldsort.field.defaultValue) + "</SPAN>");
                            }
                            else
                            {
                                streamRow.add(HtmlController.inputText_Legacy(core, "dtfaDefaultValue." + RecordCount, GenericController.encodeText(fieldsort.field.defaultValue), 1, 10));
                            }
                            streamRow.add("</nobr></td>");
                            //
                            // type
                            //
                            rowValid = rowValid && (fieldsort.field.fieldTypeId > 0);
                            streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>");
                            if (fieldsort.field.inherited)
                            {
                                using (var csData = new CsModel(core)) {
                                    csData.openRecord("Content Field Types", (int)fieldsort.field.fieldTypeId);
                                    if (!csData.ok())
                                    {
                                        streamRow.add(SpanClassAdminSmall + "Unknown[" + fieldsort.field.fieldTypeId + "]</SPAN>");
                                    }
                                    else
                                    {
                                        streamRow.add(SpanClassAdminSmall + csData.getText("Name") + "</SPAN>");
                                    }
                                }
                            }
                            else if (FieldLocked)
                            {
                                streamRow.add(DbBaseModel.getRecordName <ContentFieldTypeModel>(core.cpParent, (int)fieldsort.field.fieldTypeId) + HtmlController.inputHidden("dtfaType." + RecordCount, (int)fieldsort.field.fieldTypeId));
                            }
                            else
                            {
                                string TypeSelect = TypeSelectTemplate;
                                TypeSelect = GenericController.strReplace(TypeSelect, "menuname", "dtfaType." + RecordCount, 1, 99, 1);
                                TypeSelect = GenericController.strReplace(TypeSelect, "=\"" + fieldsort.field.fieldTypeId + "\"", "=\"" + fieldsort.field.fieldTypeId + "\" selected", 1, 99, 1);
                                streamRow.add(TypeSelect);
                            }
                            streamRow.add("</nobr></td>");
                            //
                            // sort priority
                            //
                            streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>");
                            if (fieldsort.field.inherited)
                            {
                                streamRow.add(SpanClassAdminSmall + fieldsort.field.editSortPriority + "</SPAN>");
                            }
                            else
                            {
                                streamRow.add(HtmlController.inputText_Legacy(core, "dtfaEditSortPriority." + RecordCount, fieldsort.field.editSortPriority.ToString(), 1, 10));
                            }
                            streamRow.add("</nobr></td>");
                            //
                            // active
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaActive." + RecordCount, fieldsort.field.active, fieldsort.field.inherited));
                            //
                            // read only
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaReadOnly." + RecordCount, fieldsort.field.readOnly, fieldsort.field.inherited));
                            //
                            // authorable
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaAuthorable." + RecordCount, fieldsort.field.authorable, fieldsort.field.inherited));
                            //
                            // required
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaRequired." + RecordCount, fieldsort.field.required, fieldsort.field.inherited));
                            //
                            // UniqueName
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaUniqueName." + RecordCount, fieldsort.field.uniqueName, fieldsort.field.inherited));
                            //
                            // text buffered
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaTextBuffered." + RecordCount, fieldsort.field.textBuffered, fieldsort.field.inherited));
                            //
                            // password
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaPassword." + RecordCount, fieldsort.field.password, fieldsort.field.inherited));
                            //
                            // scramble
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaScramble." + RecordCount, fieldsort.field.scramble, fieldsort.field.inherited));
                            //
                            // HTML Content
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaHTMLContent." + RecordCount, fieldsort.field.htmlContent, fieldsort.field.inherited));
                            //
                            // Admin Only
                            //
                            if (core.session.isAuthenticatedAdmin())
                            {
                                streamRow.add(configureEdit_CheckBox("dtfaAdminOnly." + RecordCount, fieldsort.field.adminOnly, fieldsort.field.inherited));
                            }
                            //
                            // Developer Only
                            //
                            if (core.session.isAuthenticatedDeveloper())
                            {
                                streamRow.add(configureEdit_CheckBox("dtfaDeveloperOnly." + RecordCount, fieldsort.field.developerOnly, fieldsort.field.inherited));
                            }
                            //
                            streamRow.add("</tr>");
                            RecordCount = RecordCount + 1;
                            //
                            // rows are built - put the blank rows at the top
                            //
                            if (!rowValid)
                            {
                                Stream.add(streamRow.text);
                            }
                            else
                            {
                                StreamValidRows.add(streamRow.text);
                            }
                        }
                        Stream.add(StreamValidRows.text);
                        Stream.add(HtmlController.inputHidden("dtfaRecordCount", RecordCount));
                    }
                    Stream.add("</table>");
                    //
                    Stream.add(core.html.getPanelBottom());
                    if (NeedFootNote1)
                    {
                        Stream.add("<br>*Field Inheritance is not allowed because this Content Definition has no parent.");
                    }
                    if (NeedFootNote2)
                    {
                        Stream.add("<br>**This field can not be inherited because the Parent Content Definition does not have a field with the same name.");
                    }
                }
                Stream.add(HtmlController.inputHidden("ReloadCDef", ReloadCDef));
                //
                // -- assemble form
                return(AdminUIController.getToolForm(core, Stream.text, ButtonList));
            } catch (Exception ex) {
                LogController.logError(core, ex);
                return(toolExceptionMessage);
            }
        }
        //
        //=================================================================================
        //
        //=================================================================================
        //
        public static string get(CPClass cp, CoreController core, AdminDataModel adminData)
        {
            string returnForm = "";

            try {
                //
                string            SearchValue = null;
                FindWordMatchEnum MatchOption = 0;
                int FormFieldPtr                     = 0;
                int FormFieldCnt                     = 0;
                ContentMetadataModel CDef            = null;
                string FieldName                     = null;
                StringBuilderLegacyController Stream = new StringBuilderLegacyController();
                int      FieldPtr                    = 0;
                bool     RowEven                     = false;
                string   RQS          = null;
                string[] FieldNames   = { };
                string[] FieldCaption = { };
                int[]    fieldId      = null;
                CPContentBaseClass.FieldTypeIdEnum[] fieldTypeId = { };
                string[] FieldValue             = { };
                int[]    FieldMatchOptions      = { };
                int      FieldMatchOption       = 0;
                string[] FieldLookupContentName = { };
                string[] FieldLookupList        = { };
                int      ContentId   = 0;
                int      FieldCnt    = 0;
                int      FieldSize   = 0;
                int      RowPointer  = 0;
                string   LeftButtons = "";
                string   ButtonBar   = null;
                string   Title       = null;
                string   TitleBar    = null;
                string   Content     = null;

                //
                // Process last form
                //
                string           Button      = core.docProperties.getText("button");
                IndexConfigClass IndexConfig = null;
                if (!string.IsNullOrEmpty(Button))
                {
                    switch (Button)
                    {
                    case ButtonSearch:
                        IndexConfig  = IndexConfigClass.get(core, adminData);
                        FormFieldCnt = core.docProperties.getInteger("fieldcnt");
                        if (FormFieldCnt > 0)
                        {
                            for (FormFieldPtr = 0; FormFieldPtr < FormFieldCnt; FormFieldPtr++)
                            {
                                FieldName   = GenericController.toLCase(core.docProperties.getText("fieldname" + FormFieldPtr));
                                MatchOption = (FindWordMatchEnum)core.docProperties.getInteger("FieldMatch" + FormFieldPtr);
                                switch (MatchOption)
                                {
                                case FindWordMatchEnum.MatchEquals:
                                case FindWordMatchEnum.MatchGreaterThan:
                                case FindWordMatchEnum.matchincludes:
                                case FindWordMatchEnum.MatchLessThan:
                                    SearchValue = core.docProperties.getText("FieldValue" + FormFieldPtr);
                                    break;

                                default:
                                    SearchValue = "";
                                    break;
                                }
                                if (!IndexConfig.findWords.ContainsKey(FieldName))
                                {
                                    //
                                    // fieldname not found, save if not FindWordMatchEnum.MatchIgnore
                                    //
                                    if (MatchOption != FindWordMatchEnum.MatchIgnore)
                                    {
                                        IndexConfig.findWords.Add(FieldName, new IndexConfigFindWordClass {
                                            Name        = FieldName,
                                            MatchOption = MatchOption,
                                            Value       = SearchValue
                                        });
                                    }
                                }
                                else
                                {
                                    //
                                    // fieldname was found
                                    //
                                    IndexConfig.findWords[FieldName].MatchOption = MatchOption;
                                    IndexConfig.findWords[FieldName].Value       = SearchValue;
                                }
                            }
                        }
                        GetHtmlBodyClass.setIndexSQL_SaveIndexConfig(cp, core, IndexConfig);
                        return(string.Empty);

                    case ButtonCancel:
                        return(string.Empty);
                    }
                }
                IndexConfig = IndexConfigClass.get(core, adminData);
                Button      = "CriteriaSelect";
                RQS         = core.doc.refreshQueryString;
                //
                // ----- ButtonBar
                //
                if (adminData.ignore_legacyMenuDepth > 0)
                {
                    LeftButtons += AdminUIController.getButtonPrimary(ButtonClose, "window.close();");
                }
                else
                {
                    LeftButtons += AdminUIController.getButtonPrimary(ButtonCancel);
                }
                LeftButtons += AdminUIController.getButtonPrimary(ButtonSearch);
                ButtonBar    = AdminUIController.getSectionButtonBar(core, LeftButtons, "");
                //
                // ----- TitleBar
                //
                Title = adminData.adminContent.name;
                Title = Title + " Advanced Search";
                string TitleDescription = "<div>Enter criteria for each field to identify and select your results. The results of a search will have to have all of the criteria you enter.</div>";
                TitleBar = AdminUIController.getSectionHeader(core, Title, TitleDescription);
                //
                // ----- List out all fields
                //
                CDef      = ContentMetadataModel.createByUniqueName(core, adminData.adminContent.name);
                FieldSize = 100;
                Array.Resize(ref FieldNames, FieldSize + 1);
                Array.Resize(ref FieldCaption, FieldSize + 1);
                Array.Resize(ref fieldId, FieldSize + 1);
                Array.Resize(ref fieldTypeId, FieldSize + 1);
                Array.Resize(ref FieldValue, FieldSize + 1);
                Array.Resize(ref FieldMatchOptions, FieldSize + 1);
                Array.Resize(ref FieldLookupContentName, FieldSize + 1);
                Array.Resize(ref FieldLookupList, FieldSize + 1);
                foreach (KeyValuePair <string, ContentFieldMetadataModel> keyValuePair in adminData.adminContent.fields)
                {
                    ContentFieldMetadataModel field = keyValuePair.Value;
                    if (FieldPtr >= FieldSize)
                    {
                        FieldSize = FieldSize + 100;
                        Array.Resize(ref FieldNames, FieldSize + 1);
                        Array.Resize(ref FieldCaption, FieldSize + 1);
                        Array.Resize(ref fieldId, FieldSize + 1);
                        Array.Resize(ref fieldTypeId, FieldSize + 1);
                        Array.Resize(ref FieldValue, FieldSize + 1);
                        Array.Resize(ref FieldMatchOptions, FieldSize + 1);
                        Array.Resize(ref FieldLookupContentName, FieldSize + 1);
                        Array.Resize(ref FieldLookupList, FieldSize + 1);
                    }
                    FieldName              = GenericController.toLCase(field.nameLc);
                    FieldNames[FieldPtr]   = FieldName;
                    FieldCaption[FieldPtr] = field.caption;
                    fieldId[FieldPtr]      = field.id;
                    fieldTypeId[FieldPtr]  = field.fieldTypeId;
                    if (fieldTypeId[FieldPtr] == CPContentBaseClass.FieldTypeIdEnum.Lookup)
                    {
                        ContentId = field.lookupContentId;
                        if (ContentId > 0)
                        {
                            FieldLookupContentName[FieldPtr] = MetadataController.getContentNameByID(core, ContentId);
                        }
                        FieldLookupList[FieldPtr] = field.lookupList;
                    }
                    //
                    // set prepoplate value from indexconfig
                    //
                    if (IndexConfig.findWords.ContainsKey(FieldName))
                    {
                        FieldValue[FieldPtr]        = IndexConfig.findWords[FieldName].Value;
                        FieldMatchOptions[FieldPtr] = (int)IndexConfig.findWords[FieldName].MatchOption;
                    }
                    FieldPtr += 1;
                }
                FieldCnt = FieldPtr;
                //
                // Add headers to stream
                //
                returnForm = returnForm + "<table border=0 width=100% cellspacing=0 cellpadding=4>";
                //
                RowPointer = 0;
                for (FieldPtr = 0; FieldPtr < FieldCnt; FieldPtr++)
                {
                    returnForm       = returnForm + HtmlController.inputHidden("fieldname" + FieldPtr, FieldNames[FieldPtr]);
                    RowEven          = ((RowPointer % 2) == 0);
                    FieldMatchOption = FieldMatchOptions[FieldPtr];
                    switch (fieldTypeId[FieldPtr])
                    {
                    case CPContentBaseClass.FieldTypeIdEnum.Date:
                        //
                        // Date

                        returnForm = returnForm + "<tr>"
                                     + "<td class=\"ccAdminEditCaption\">" + FieldCaption[FieldPtr] + "</td>"
                                     + "<td class=\"ccAdminEditField\">"
                                     + "<div style=\"display:block;float:left;width:800px;\">"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, encodeInteger(FindWordMatchEnum.MatchIgnore).ToString(), FieldMatchOption.ToString(), "") + "ignore</div>"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, encodeInteger(FindWordMatchEnum.MatchEmpty).ToString(), FieldMatchOption.ToString(), "") + "empty</div>"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, encodeInteger(FindWordMatchEnum.MatchNotEmpty).ToString(), FieldMatchOption.ToString(), "") + "not&nbsp;empty</div>"
                                     + "<div style=\"display:block;float:left;width:50px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, encodeInteger(FindWordMatchEnum.MatchEquals).ToString(), FieldMatchOption.ToString(), "") + "=</div>"
                                     + "<div style=\"display:block;float:left;width:50px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, encodeInteger(FindWordMatchEnum.MatchGreaterThan).ToString(), FieldMatchOption.ToString(), "") + "&gt;</div>"
                                     + "<div style=\"display:block;float:left;width:50px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, encodeInteger(FindWordMatchEnum.MatchLessThan).ToString(), FieldMatchOption.ToString(), "") + "&lt;</div>"
                                     + "<div style=\"display:block;float:left;width:300px;\">" + HtmlController.inputDate(core, "fieldvalue" + FieldPtr, encodeDate(FieldValue[FieldPtr])).Replace(">", " onFocus=\"ccAdvSearchText\">") + "</div>"
                                     + "</div>"
                                     + "</td>"
                                     + "</tr>";
                        break;

                    case CPContentBaseClass.FieldTypeIdEnum.Currency:
                    case CPContentBaseClass.FieldTypeIdEnum.Float:
                    case CPContentBaseClass.FieldTypeIdEnum.Integer:
                    case CPContentBaseClass.FieldTypeIdEnum.AutoIdIncrement:
                        //
                        // -- Numeric - changed FindWordMatchEnum.MatchEquals to MatchInclude to be compatible with Find Search
                        returnForm = returnForm + "<tr>"
                                     + "<td class=\"ccAdminEditCaption\">" + FieldCaption[FieldPtr] + "</td>"
                                     + "<td class=\"ccAdminEditField\">"
                                     + "<div style=\"display:block;float:left;width:800px;\">"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchIgnore).ToString(), FieldMatchOption.ToString(), "") + "ignore</div>"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchEmpty).ToString(), FieldMatchOption.ToString(), "") + "empty</div>"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchNotEmpty).ToString(), FieldMatchOption.ToString(), "") + "not&nbsp;empty</div>"
                                     + "<div style=\"display:block;float:left;width:50px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.matchincludes).ToString(), FieldMatchOption.ToString(), "n" + FieldPtr) + "=</div>"
                                     + "<div style=\"display:block;float:left;width:50px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchGreaterThan).ToString(), FieldMatchOption.ToString(), "") + "&gt;</div>"
                                     + "<div style=\"display:block;float:left;width:50px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchLessThan).ToString(), FieldMatchOption.ToString(), "") + "&lt;</div>"
                                     + "<div style=\"display:block;float:left;width:300px;\">" + HtmlController.inputText_Legacy(core, "fieldvalue" + FieldPtr, FieldValue[FieldPtr], 1, 5, "", false, false, "ccAdvSearchText").Replace(">", " onFocus=\"var e=getElementById('n" + FieldPtr + "');e.checked=1;\">") + "</div>"
                                     + "</div>"
                                     + "</td>"
                                     + "</tr>";
                        RowPointer += 1;
                        break;

                    case CPContentBaseClass.FieldTypeIdEnum.File:
                    case CPContentBaseClass.FieldTypeIdEnum.FileImage:
                        //
                        // File
                        //
                        returnForm = returnForm + "<tr>"
                                     + "<td class=\"ccAdminEditCaption\">" + FieldCaption[FieldPtr] + "</td>"
                                     + "<td class=\"ccAdminEditField\">"
                                     + "<div style=\"display:block;float:left;width:800px;\">"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchIgnore).ToString(), FieldMatchOption.ToString(), "") + "ignore</div>"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchEmpty).ToString(), FieldMatchOption.ToString(), "") + "empty</div>"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchNotEmpty).ToString(), FieldMatchOption.ToString(), "") + "not&nbsp;empty</div>"
                                     + "</div>"
                                     + "</td>"
                                     + "</tr>";
                        RowPointer = RowPointer + 1;
                        break;

                    case CPContentBaseClass.FieldTypeIdEnum.Boolean:
                        //
                        // Boolean
                        //
                        returnForm = returnForm + "<tr>"
                                     + "<td class=\"ccAdminEditCaption\">" + FieldCaption[FieldPtr] + "</td>"
                                     + "<td class=\"ccAdminEditField\">"
                                     + "<div style=\"display:block;float:left;width:800px;\">"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchIgnore).ToString(), FieldMatchOption.ToString(), "") + "ignore</div>"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchTrue).ToString(), FieldMatchOption.ToString(), "") + "true</div>"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchFalse).ToString(), FieldMatchOption.ToString(), "") + "false</div>"
                                     + "</div>"
                                     + "</td>"
                                     + "</tr>";
                        break;

                    case CPContentBaseClass.FieldTypeIdEnum.Text:
                    case CPContentBaseClass.FieldTypeIdEnum.LongText:
                    case CPContentBaseClass.FieldTypeIdEnum.HTML:
                    case CPContentBaseClass.FieldTypeIdEnum.HTMLCode:
                    case CPContentBaseClass.FieldTypeIdEnum.FileHTML:
                    case CPContentBaseClass.FieldTypeIdEnum.FileHTMLCode:
                    case CPContentBaseClass.FieldTypeIdEnum.FileCSS:
                    case CPContentBaseClass.FieldTypeIdEnum.FileJavascript:
                    case CPContentBaseClass.FieldTypeIdEnum.FileXML:
                        //
                        // Text
                        //
                        returnForm = returnForm + "<tr>"
                                     + "<td class=\"ccAdminEditCaption\">" + FieldCaption[FieldPtr] + "</td>"
                                     + "<td class=\"ccAdminEditField\">"
                                     + "<div style=\"display:block;float:left;width:800px;\">"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchIgnore).ToString(), FieldMatchOption.ToString(), "") + "ignore</div>"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchEmpty).ToString(), FieldMatchOption.ToString(), "") + "empty</div>"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchNotEmpty).ToString(), FieldMatchOption.ToString(), "") + "not&nbsp;empty</div>"
                                     + "<div style=\"display:block;float:left;width:150px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.matchincludes).ToString(), FieldMatchOption.ToString(), "t" + FieldPtr) + "includes</div>"
                                     + "<div style=\"display:block;float:left;width:300px;\">" + HtmlController.inputText_Legacy(core, "fieldvalue" + FieldPtr, FieldValue[FieldPtr], 1, 5, "", false, false, "ccAdvSearchText").Replace(">", " onFocus=\"var e=getElementById('t" + FieldPtr + "');e.checked=1;\">") + "</div>"
                                     + "</div>"
                                     + "</td>"
                                     + "</tr>";
                        RowPointer = RowPointer + 1;
                        break;

                    case CPContentBaseClass.FieldTypeIdEnum.Lookup:
                    case CPContentBaseClass.FieldTypeIdEnum.MemberSelect:
                        //
                        // Lookup
                        returnForm = returnForm + "<tr>"
                                     + "<td class=\"ccAdminEditCaption\">" + FieldCaption[FieldPtr] + "</td>"
                                     + "<td class=\"ccAdminEditField\">"
                                     + "<div style=\"display:block;float:left;width:800px;\">"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchIgnore).ToString(), FieldMatchOption.ToString(), "") + "ignore</div>"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchEmpty).ToString(), FieldMatchOption.ToString(), "") + "empty</div>"
                                     + "<div style=\"display:block;float:left;width:100px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.MatchNotEmpty).ToString(), FieldMatchOption.ToString(), "") + "not&nbsp;empty</div>"
                                     + "<div style=\"display:block;float:left;width:150px;\">" + HtmlController.inputRadio("FieldMatch" + FieldPtr, ((int)FindWordMatchEnum.matchincludes).ToString(), FieldMatchOption.ToString(), "t" + FieldPtr) + "includes</div>"
                                     + "<div style=\"display:block;float:left;width:300px;\">" + HtmlController.inputText_Legacy(core, "fieldvalue" + FieldPtr, FieldValue[FieldPtr], 1, 5, "", false, false, "ccAdvSearchText").Replace(">", " onFocus=\"var e=getElementById('t" + FieldPtr + "'); e.checked= 1;\">") + "</div>"
                                     + "</div>"
                                     + "</td>"
                                     + "</tr>";
                        RowPointer = RowPointer + 1;
                        break;
                    }
                }
                returnForm = returnForm + HtmlController.tableRowStart();
                returnForm = returnForm + HtmlController.tableCellStart("120", 1, RowEven, "right") + "<img src=" + cdnPrefix + "images/spacer.gif width=120 height=1></td>";
                returnForm = returnForm + HtmlController.tableCellStart("99%", 1, RowEven, "left") + "<img src=" + cdnPrefix + "images/spacer.gif width=1 height=1></td>";
                returnForm = returnForm + kmaEndTableRow;
                returnForm = returnForm + "</table>";
                Content    = returnForm;
                //
                // Assemble LiveWindowTable
                Stream.add(ButtonBar);
                Stream.add(TitleBar);
                Stream.add(Content);
                Stream.add(ButtonBar);
                Stream.add("<input type=hidden name=fieldcnt VALUE=" + FieldCnt + ">");
                Stream.add("<input type=hidden name=" + RequestNameAdminSubForm + " VALUE=" + AdminFormIndex_SubFormAdvancedSearch + ">");
                returnForm = HtmlController.form(core, Stream.text);
                core.html.addTitle(adminData.adminContent.name + " Advanced Search");
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(returnForm);
        }
        public void GetMetadata_Doesnot_Change_DataServiceVersion()
        {
            // Arrange
            IEdmModel model = new EdmModel();
            model.SetDataServiceVersion(new Version(0, 42));

            MetadataController controller = new MetadataController();
            controller.Request = new HttpRequestMessage();
            controller.Request.ODataProperties().Model = model;

            // Act
            IEdmModel controllerModel = controller.GetMetadata();

            // Assert
            Assert.Equal(new Version(0, 42), controllerModel.GetDataServiceVersion());
        }