Ejemplo n.º 1
0
        /// <summary>
        /// Page Action Result
        /// </summary>
        /// <returns></returns>
        public ActionResult Pages(int?page, int?sortColumnIndex, int?sortDirection)
        {
            PageListModel    model       = new PageListModel();
            SearchAttributes searchParam = new SearchAttributes();

            searchParam.CurrentPageNumber = (page.HasValue && page.Value > 0) ? page.Value : 1;
            searchParam.RecordsPerPage    = AppSettingsUtility.GetInt(AppSettingsKeys.RecordsPerPage);
            searchParam.SortColumnIndex   = 1;
            searchParam.SortDirection     = (sortDirection.HasValue && sortDirection.Value == 1) ? Entity.SortDirection.Descending : Entity.SortDirection.Ascending;

            model.Populate(searchParam);

            //for Ajax Specific Request
            if (Request.IsAjaxRequest())
            {
                return(View("~/Views/Shared/PartialViews/Admin/Page/_PageList.cshtml", model));
            }
            else
            {
                return(View("~/Views/Admin/Page/PageList.cshtml", model));
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Send Email
        /// </summary>
        /// <returns></returns>
        public bool SendMail(HttpPostedFileBase File)
        {
            bool SendMail = false;

            try
            {
                MailMessage mail = new MailMessage();
                mail.Subject = AppSettingsUtility.GetString(AppSettingsKeys.MailSubject);
                mail.Body    = "";
                string html = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/mailTemplate/MailBody.html"));
                mail.Body = string.Format(html, this.Contact, this.Salutation, this.FirstName, this.LastName, this.Email, this.Company,
                                          this.JobTitle, this.PhoneNumber, this.Country, this.DocumentName, this.Year, this.DocumentAvailability,
                                          this.URL, this.Comments);

                mail.From = new MailAddress(Email);
                mail.To.Add(AppSettingsUtility.GetString(AppSettingsKeys.MailTo));
                if (File != null)
                {
                    string fileName = Path.GetFileName(File.FileName);
                    mail.Attachments.Add(new Attachment(File.InputStream, fileName));
                }
                mail.IsBodyHtml = true;

                using (SmtpClient smtp = new SmtpClient())
                {
                    smtp.Host = AppSettingsUtility.GetString(AppSettingsKeys.SmtpHost);
                    smtp.Port = AppSettingsUtility.GetInt(AppSettingsKeys.SmtpPort);;
                    smtp.Send(mail);
                    SendMail = true;
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteLog("ContactUsModel", "SendEmail", ex, "");
            }


            return(SendMail);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        static void Main()
        {
            string manufacturerUrl = AppSettingsUtility.GetString(AppSettingsKeys.ManufacturerUrl);

            for (int count = 0; count < 53; count++)
            {
                var    modifiedManufacturerUrl = manufacturerUrl.Replace("{index}", count.ToString());
                var    webRequestHelper        = new WebRequestHelper(modifiedManufacturerUrl);
                string response = webRequestHelper.GetResponse();

                var manufacturers = GetManufaturersFromHtml(response);

                // Add to database
                if (manufacturers.Count > 0)
                {
                    manufaturerRepository.Add(manufacturers);
                }

                Console.Clear();
                Console.Write("Manufacturer Updated: " + count * 50);
            }
        }
Ejemplo n.º 4
0
        //public static IResultSet GetNewsItems(string[] providers, out int hitCount, Guid[] categories = null, string terms = null, int skip = 0, int take = 0)
        public static IResultSet GetNewsItems(out int hitCount, Guid[] categories = null, string terms = null, int skip = 0, int take = 0)
        {
            var searchService = ServiceBus.ResolveService <ISearchService>();

            var        searchQuery = BuildQuery(categories);
            var        catalogName = AppSettingsUtility.GetValue <string>("KeyIssuesCatalogName");
            var        orderBy     = new[] { "PublishDate DESC" };
            IResultSet resultSet;

            if (skip == 0 && take == 0)
            {
                resultSet = searchService.Search(catalogName, searchQuery, null, orderBy, new object[0]);
            }
            else
            {
                resultSet = searchService.Search(catalogName, searchQuery, null, skip, take, orderBy, new object[0]);
            }

            hitCount = resultSet.HitCount;

            return(resultSet);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Populate Pie chart of thematic focus
        /// </summary>
        private void PopulateBarChartThematicFocus(Guid languageID, List <Guid> listOfRecordIds)
        {
            Guid documentTypeVariableID = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.DocumentTypeVariableID));

            var recordVariables = ChartService.GetThematicFocus(languageID, listOfRecordIds);
            //categories

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

            foreach (var recordVariable in recordVariables)
            {
                barChartCategory.Add(recordVariable.VariableName);
                //barChartData.Add(new BarChartModel { name = regionLanguage.VariableName, data = regionLanguage.RecordCount });
            }

            JavaScriptSerializer serializerCategory = new JavaScriptSerializer();
            string jsonDataCategory = serializerCategory.Serialize(barChartCategory);

            this.BarChartThematicFocusCategory = jsonDataCategory;



            //data

            List <int> barChartData = new List <int>();

            foreach (var recordVariable in recordVariables)
            {
                barChartData.Add(recordVariable.RecordCount);
                //barChartData.Add(new BarChartModel { name = regionLanguage.VariableName, data = regionLanguage.RecordCount });
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string jsonData = serializer.Serialize(barChartData);

            this.BarChartThematicFocusItems = jsonData;
        }
Ejemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="languageID"></param>
        /// <returns></returns>

        public static List <Region_Language> GetRecordsInRegion(Guid languageID)
        {
            List <Region_Language> regionLanguages = new List <Region_Language>();
            List <Region>          regions         = new List <Region>();
            string currentYear    = DateTime.Now.Year.ToString();
            Guid   yearVariableID = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.YearVariableID));

            List <Guid> recordIds = GetActiveCurrentYearRecordsIDs(languageID);

            using (var context = new TSMContext())
            {
                var query = (from r in context.Regions.Include("Region_Languages")
                             join rl in context.Region_Languages
                             on r.ID equals rl.ID
                             where rl.LanguageID == languageID && r.Type == TSM.Entity.RegionType.Geographical &&
                             r.IsDeleted == false && r.IsActive
                             select new
                {
                    Region = r,
                    RegionName = r.Region_Languages.Where(rgl => rgl.LanguageID == languageID).FirstOrDefault().Name,
                    RecordCount = r.Records.Where(re => recordIds.Contains(re.ID)).Count()
                }).OrderBy(rls => rls.RegionName);


                foreach (var row in query)
                {
                    Region_Language regionLanguage = new Region_Language();
                    regionLanguage.ID          = row.Region.ID;
                    regionLanguage.Name        = row.RegionName;
                    regionLanguage.RecordCount = row.RecordCount;
                    regionLanguages.Add(regionLanguage);
                }
            }

            return(regionLanguages);
        }
Ejemplo n.º 7
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureLogging((logging) => {
            // seed Rollbar infrastructure configuration:
            RollbarInfrastructureConfig rollbarInfrastructureConfig = new RollbarInfrastructureConfig();

            // reconfigure the seed from the appsettings.json file:
            if (!AppSettingsUtility.LoadAppSettings(rollbarInfrastructureConfig))
            {
                throw new ApplicationException("Couldn't load Rollbar configuration!");
            }

            // init the Rollbar infrastructure with the loaded configuration:
            RollbarInfrastructure.Instance.Init(rollbarInfrastructureConfig);

            // add a well-configured RollbarLoggerProvider:
            logging.ClearProviders();
            logging.AddProvider(new RollbarLoggerProvider(rollbarInfrastructureConfig.RollbarLoggerConfig));
        }
                          )
        .ConfigureServices((hostContext, services) =>
        {
            services.AddHostedService <Worker>();
        });
Ejemplo n.º 8
0
        /// <summary>
        /// line chart home page load
        /// </summary>
        /// <param name="languageID"></param>
        /// <returns></returns>

        public static List <Record_Variable> GetRecordInYear(Guid languageID)
        {
            Guid yearVariableID          = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.YearVariableID));
            Guid startImplementationYear = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.StartYearVariableID));
            Guid endImplementationYear   = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.EndYearVariableID));

            List <Record_Variable> recordVariables = new List <Record_Variable>();
            List <Record_Variable> results         = new List <Record_Variable>();
            List <Guid>            recordIds       = new List <Guid>();

            using (var context = new TSMContext())
            {
                recordVariables = context.Record_Variables.Where(rv => rv.LanguageID == languageID && (rv.VariableID == yearVariableID || rv.VariableID == startImplementationYear || rv.VariableID == endImplementationYear)).ToList();
                recordIds       = context.Record_Languages.Where(rl => rl.LanguageID == languageID).Select(rl => rl.ID).Distinct().ToList();
            }

            int currentYear = DateTime.Now.Year;
            int startYear   = Convert.ToInt32(recordVariables.Where(rv => rv.VariableID == startImplementationYear).OrderBy(rv => rv.Value).FirstOrDefault().Value);

            var recordYears = new List <RecordYear>();

            foreach (var recordId in recordIds)
            {
                if (recordVariables.Any(rv => rv.RecordID == recordId))
                {
                    var recordYear = new RecordYear();
                    recordYear.RecordID = recordId;

                    //Start
                    var start = recordVariables.Where(rv => rv.RecordID == recordId && rv.VariableID == startImplementationYear && rv.Value != "").FirstOrDefault();
                    if (start != null)
                    {
                        recordYear.StartYear = Convert.ToInt32(start.Value);
                    }

                    //End
                    var end = recordVariables.Where(rv => rv.RecordID == recordId && rv.VariableID == endImplementationYear && rv.Value != "").FirstOrDefault();
                    if (end != null)
                    {
                        recordYear.EndYear = Convert.ToInt32(end.Value);
                    }

                    //Year
                    var year = recordVariables.Where(rv => rv.RecordID == recordId && rv.VariableID == yearVariableID && rv.Value != "").FirstOrDefault();
                    if (year != null && recordYear.StartYear == 0)
                    {
                        recordYear.StartYear = Convert.ToInt32(year.Value);
                        recordYear.EndYear   = recordYear.StartYear + 5;
                    }

                    recordYears.Add(recordYear);
                }
            }

            for (int count = startYear; count <= currentYear; count++)
            {
                var result = new Record_Variable();
                result.Value = count.ToString();

                result.RecordCount = recordYears.Where(ry => ry.StartYear <= count && ry.EndYear >= count).Count();

                results.Add(result);
            }

            return(results);
        }
Ejemplo n.º 9
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static DocumentData GetSitcAndRecord(Guid languageID, List <Guid> listRecord)
        {
            Guid startImplementationYear = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.StartYearVariableID));
            Guid endImplementationYear   = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.EndYearVariableID));

            //List<Record_Variable> listRecordVariable = new List<Record_Variable>();
            List <Guid>       recordIdFilteredYear = new List <Guid>();
            int               currentYear          = DateTime.Now.Year;
            List <RecordYear> ryear = new List <RecordYear>();

            using (var context = new TSMContext())
            {
                var filteredRecordsID = listRecord;
                var result1           = (from rv in context.Record_Variables where filteredRecordsID.Contains(rv.RecordID) && rv.LanguageID == languageID && (rv.VariableID == startImplementationYear || rv.VariableID == endImplementationYear) select rv).ToList();
                foreach (var rec in listRecord)
                {
                    RecordYear RecVar = new RecordYear();
                    try
                    {
                        var rec1 = result1.Where(r => r.RecordID == rec && r.VariableID == startImplementationYear).FirstOrDefault().Value;
                        var rec2 = result1.Where(r => r.RecordID == rec && r.VariableID == endImplementationYear).FirstOrDefault().Value;

                        RecVar.RecordID  = rec;
                        RecVar.StartYear = Convert.ToInt32(rec1);
                        RecVar.EndYear   = Convert.ToInt32(rec2);

                        if (RecVar.EndYear >= currentYear)
                        {
                            recordIdFilteredYear.Add(rec);
                        }
                    }
                    catch { }
                }

                var filterSectorRecords = (from r in context.Records where recordIdFilteredYear.Contains(r.ID) && r.Sectors.Count > 0 && r.IsDeleted == false && r.IsActive == true select r).ToList();


                int serviceCount = 0;
                int productCount = 0;

                foreach (var rec in filterSectorRecords)
                {
                    foreach (var r in rec.Sectors)
                    {
                        if (r.Type == SectorType.Product)
                        {
                            productCount = productCount + 1;
                        }
                        else if (r.Type == SectorType.Service)
                        {
                            serviceCount = serviceCount + 1;
                        }
                    }
                }


                DocumentData documentData = new DocumentData();
                documentData.ResultWithSitcWTOCount   = serviceCount;
                documentData.ResultOfOtherRecordCount = productCount;
                return(documentData);

                //var filteredRecords = GetRecordList(languageID, selectedRegions, selectedCountries, selectedSectors, selectedDocumentTypes, documentTypeVariableID);
                //var filteredRecordsID = filteredRecords.Select(r => r.ID).ToList();

                //var filteredRecordsID = listRecord;
                //DocumentData documentData = new DocumentData();
                //documentData.ResultWithSitcWTOCount = (from r in context.Records where recordIdFilteredYear.Contains(r.ID) && r.Sectors.Count > 0 select r).ToList().Count;
                //documentData.ResultOfOtherRecordCount = (from r in context.Records where recordIdFilteredYear.Contains(r.ID) && r.Sectors.Count == 0 select r).ToList().Count;
                //return documentData;
            }
        }
Ejemplo n.º 10
0
        public static List <DocumentData> GetRecordPerYearWithDocumentType(Guid languageID, List <Guid> listOfRecordIds)
        {
            Guid yearVariableID         = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.YearVariableID));
            var  documentTypeVariableID = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.DocumentTypeVariableID));

            using (var context = new TSMContext())
            {
                //var filteredRecords = GetRecordList(languageID, selectedRegions, selectedCountries, selectedSectors, selectedDocumentTypes, documentTypeVariableID);
                //var filteredRecordsID = filteredRecords.Select(r => r.ID).ToList();
                var filteredRecordsID = listOfRecordIds;

                var result = from rv in context.Record_Variables
                             where filteredRecordsID.Contains(rv.RecordID) && rv.VariableID == yearVariableID && rv.LanguageID == languageID
                             group rv
                             by rv.Value into grps
                             select new
                {
                    value       = grps.Key,
                    recordCount = grps.Count()
                };

                List <Record_Variable> recordVariablesYearWise = new List <Record_Variable>();
                Record_Variable        recordVaraibleYearWise;
                foreach (var record in result)
                {
                    if ((!string.IsNullOrEmpty(record.value)) && (record.value != "0"))
                    {
                        recordVaraibleYearWise             = new Record_Variable();
                        recordVaraibleYearWise.Value       = record.value;
                        recordVaraibleYearWise.RecordCount = record.recordCount;
                        recordVariablesYearWise.Add(recordVaraibleYearWise);
                    }
                }
                recordVariablesYearWise = recordVariablesYearWise.OrderBy(rv => rv.Value).ToList();

                int minYear = 1993;
                if (recordVariablesYearWise.Count > 0)
                {
                    int.TryParse(recordVariablesYearWise.FirstOrDefault().Value.ToString(), out minYear);
                }
                //int minYear = Convert.ToInt32(recordVariablesYearWise.FirstOrDefault().Value);

                int maxYear = 2025;
                if (recordVariablesYearWise.Count > 0)
                {
                    int.TryParse(recordVariablesYearWise.LastOrDefault().Value.ToString(), out maxYear);
                }
                List <DocumentData> listDocumentData = new List <DocumentData>();

                for (int year = minYear; year <= maxYear; year++)
                {
                    var itemYear = Convert.ToString(year);
                    var result1  = (from rv in context.Record_Variables where filteredRecordsID.Contains(rv.RecordID) && rv.VariableID == yearVariableID && rv.Value == itemYear && rv.LanguageID == languageID select rv).ToList();
                    List <Record_Variable> listRecordVariableDocuemtType = new List <Record_Variable>();

                    foreach (var item in result1)
                    {
                        Record_Variable recordVariable = new Record_Variable();
                        recordVariable = context.Record_Variables.Where(r => r.VariableID == documentTypeVariableID && r.RecordID == item.RecordID && r.LanguageID == languageID).FirstOrDefault();
                        if (recordVariable != null)
                        {
                            listRecordVariableDocuemtType.Add(recordVariable);
                        }
                    }
                    var          nationalCount      = (from lst in listRecordVariableDocuemtType where lst.Value == "National" select lst).ToList().Count;
                    var          internationalCount = (from lst in listRecordVariableDocuemtType where lst.Value != "National" select lst).ToList().Count;
                    DocumentData dt = new DocumentData();
                    dt.Year              = itemYear;
                    dt.NationalCount     = nationalCount;
                    dt.InterNtionalCount = internationalCount;
                    listDocumentData.Add(dt);
                }
                return(listDocumentData);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Get record per document in current or filtered year
        /// </summary>
        /// <param name="languageID"></param>
        /// <returns></returns>
        public static List <Record_Variable> GetRecordPerDocumentType(Guid languageID, List <Guid> listOfRecordIds)
        {
            Guid yearVariableID          = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.YearVariableID));
            var  documentTypeVariableID  = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.DocumentTypeVariableID));
            Guid startImplementationYear = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.StartYearVariableID));
            Guid endImplementationYear   = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.EndYearVariableID));

            List <Record_Variable> listRecordVariable = new List <Record_Variable>();
            List <Guid>            recordIds          = new List <Guid>();
            int currentYear = DateTime.Now.Year;

            using (var context = new TSMContext())
            {
                // var filteredRecords = GetRecordList(languageID, selectedRegions, selectedCountries, selectedSectors, selectedDocumentTypes, documentTypeVariableID);
                //var filteredRecordsID = filteredRecords.Select(r => r.ID).ToList();
                var filteredRecordsID = listOfRecordIds;
                var result            = (from rv in context.Record_Variables where filteredRecordsID.Contains(rv.RecordID) && rv.LanguageID == languageID && (rv.VariableID == startImplementationYear || rv.VariableID == endImplementationYear) select rv).ToList();
                recordIds = context.Record_Languages.Where(rl => rl.LanguageID == languageID).Select(rl => rl.ID).Distinct().ToList();

                List <Record_Variable> listRecVar = new List <Record_Variable>();
                List <RecordYear>      ryear      = new List <RecordYear>();
                foreach (var rec in listOfRecordIds)
                {
                    RecordYear RecVar = new RecordYear();



                    try
                    {
                        var rec1 = result.Where(r => r.RecordID == rec && r.VariableID == startImplementationYear).FirstOrDefault().Value;
                        var rec2 = result.Where(r => r.RecordID == rec && r.VariableID == endImplementationYear).FirstOrDefault().Value;

                        RecVar.RecordID  = rec;
                        RecVar.StartYear = Convert.ToInt32(rec1);
                        RecVar.EndYear   = Convert.ToInt32(rec2);


                        if (RecVar.EndYear >= currentYear)
                        {
                            ryear.Add(RecVar);
                        }
                    }
                    catch
                    {
                        var resultSubstitute = context.Record_Variables.Where(r => r.RecordID == rec && r.VariableID == yearVariableID && r.LanguageID == languageID).FirstOrDefault();
                        if (resultSubstitute != null)
                        {
                            if (resultSubstitute.Value != "")
                            {
                                RecVar.RecordID  = rec;
                                RecVar.StartYear = Convert.ToInt32(resultSubstitute.Value);
                                RecVar.EndYear   = Convert.ToInt32(resultSubstitute.Value) + 5;

                                if (RecVar.EndYear >= currentYear)
                                {
                                    ryear.Add(RecVar);
                                }
                            }
                        }
                    }

                    //var rec1 = rec.Where(ry => ry.StartYear <= count && ry.EndYear >= count).Count();
                }



                foreach (var item in ryear)
                {
                    Record_Variable recordVariable = new Record_Variable();
                    recordVariable = (from rv in context.Record_Variables where rv.VariableID == documentTypeVariableID && rv.RecordID == item.RecordID && rv.LanguageID == languageID select rv).ToList().FirstOrDefault();
                    if (recordVariable != null)
                    {
                        listRecordVariable.Add(recordVariable);
                    }
                }

                var groupListRecord = from i in listRecordVariable group i by i.Value into grps select new { value = grps.Key, recordCount = grps.Count() };

                List <Record_Variable> recordVariables = new List <Record_Variable>();
                Record_Variable        recordVaraible;
                foreach (var record in groupListRecord)
                {
                    recordVaraible             = new Record_Variable();
                    recordVaraible.Value       = record.value;
                    recordVaraible.RecordCount = record.recordCount;
                    recordVariables.Add(recordVaraible);
                }


                return(recordVariables);
            }
        }
Ejemplo n.º 12
0
        public void metaData_ItemDataBound(object sender, RadListViewItemEventArgs e)
        {
            if (e.Item is RadListViewDataItem)
            {
                var dataItem    = ((RadListViewDataItem)e.Item).DataItem;
                var contentItem = dataItem as Content;

                #region searchblox tags

                Page.RemoveExistingPublishedTags();
                Page.RemoveExistingModuleTags();

                // get data type and add content type
                var dataType = dataItem.GetType().Name;
                if (dataType == "NewsItem")
                {
                    // add published date tags
                    Page.AddCustomMetaTags("Published", contentItem.PublicationDate.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture));

                    try
                    {
                        if (!AppSettingsUtility.GetValue <string>("MetaDataTags.NewsItem.Name").IsNullOrWhitespace())
                        {
                            dataType = AppSettingsUtility.GetValue <string>("MetaDataTags.NewsItem.Name");
                        }
                    }
                    catch (Exception ex)
                    {
                    }

                    Page.AddCustomMetaTags("Module", dataType);

                    // get data type and add content type
                    // add categories
                    var taxonomyManager = TaxonomyManager.GetManager();
                    var categoryIds     = contentItem.GetValue("Category") as TrackedList <Guid>;
                    if (categoryIds.Any())
                    {
                        var categoryList = string.Join(",", categoryIds.Select(cid => taxonomyManager.GetTaxon(cid).Title));

                        /* This works because the meta tag is allowed to have a
                         * comma-separated list of values to denote multiple
                         * categories. The list will simply be converted to
                         * the correct format.
                         */
                        Page.AddCustomMetaTags("webcategory", categoryList);
                    }

                    NewsItem newsContent = dataItem as NewsItem;

                    if (newsContent != null && newsContent.Author != null)
                    {
                        string author = newsContent.Author.Value;
                        Page.AddCustomMetaTags("Author", author);
                    }
                }
                else if (dataType == "BlogPost")
                {
                    try
                    {
                        if (!AppSettingsUtility.GetValue <string>("MetaDataTags.BlogPost.Name").IsNullOrWhitespace())
                        {
                            dataType = AppSettingsUtility.GetValue <string>("MetaDataTags.BlogPost.Name");
                        }
                    }
                    catch (Exception ex)
                    {
                    }

                    Page.AddCustomMetaTags("Module", dataType);
                }
                else if (dataType == "Event")
                {
                    try
                    {
                        if (!AppSettingsUtility.GetValue <string>("MetaDataTags.Event.Name").IsNullOrWhitespace())
                        {
                            dataType = AppSettingsUtility.GetValue <string>("MetaDataTags.Event.Name");
                        }
                    }
                    catch (Exception ex)
                    {
                    }

                    Page.AddCustomMetaTags("Module", dataType);
                }


                #endregion
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Populate Record variables
        /// </summary>
        private void PopulateRecordVariables()
        {
            try
            {
                this.RecordVariables = new List<RecordVariableModel>();
                foreach (var variableLanguage in this.Variable_Languages)
                {
                    var recordVariable = new RecordVariableModel();
                    recordVariable.VariableID = variableLanguage.ID;
                    recordVariable.DisplayLabel = variableLanguage.DisplayName;
                    recordVariable.IsMandatory = variableLanguage.Variable.IsMandatory.Value;
                    if (recordVariable.IsMandatory)
                    {
                        recordVariable.ErrorMessage = string.Format("Please enter {0}.", recordVariable.DisplayLabel);
                    }
                    recordVariable.Type = variableLanguage.Variable.Type;
                    recordVariable.Description = variableLanguage.Description;

                    //populate value
                    string value = GetVariableValue(variableLanguage.ID, this.LanguageID);
                    recordVariable.StringValue = value;

                    string isDownloadITC = AppSettingsUtility.GetString(AppSettingsKeys.isDownload);
                    if ((recordVariable.StringValue == "") && (variableLanguage.ID.ToString() == isDownloadITC))
                    {
                        recordVariable.StringValue = "false";
                    }

                    if (recordVariable.Type == VariableType.MultipleChoice || recordVariable.Type == VariableType.SingleChoice)
                    {
                        recordVariable.Choices = new List<KeyValue>();
                        recordVariable.Choices.Add(new KeyValue { Key = "", Value = "--- Select---" });

                        var choices = new List<KeyValue>();
                        foreach (var choice in variableLanguage.Variable.Choices)
                        {
                            var choiceLanguage = choice.Choice_Languages.Where(cl => cl.LanguageID == this.LanguageID).FirstOrDefault();
                            choices.Add(new KeyValue { Key = choiceLanguage.Name, Value = choiceLanguage.Name });
                        }

                        choices = choices.OrderBy(c => c.Value).ToList();
                        recordVariable.Choices.AddRange(choices);

                        //populate selected choices
                        if (recordVariable.Type == VariableType.MultipleChoice && !string.IsNullOrEmpty(recordVariable.StringValue))
                        {
                            recordVariable.SelectedChoices = recordVariable.StringValue.Split('|').ToList().OrderBy(s => s).ToList();
                        }

                    }
                    else if (recordVariable.Type == VariableType.Boolean && !string.IsNullOrEmpty(recordVariable.StringValue))
                    {
                        bool blnValue = false;
                        bool.TryParse(recordVariable.StringValue, out blnValue);
                        recordVariable.BoolValue = blnValue;
                    }


                    this.RecordVariables.Add(recordVariable);
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteLog("ManageRecordModel", "PopulateRecordVariables", ex, string.Empty);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Populate Region Counrty Sector Document
        /// </summary>
        /// <param name="languageID"></param>
        public void PopulateSearchFilter(Guid languageID)
        {
            //Countries
            var countries = CountryService.GetCountries(languageID);

            Countries = new List <KeyValue>();

            foreach (var country in countries)
            {
                Countries.Add(new KeyValue {
                    Key = country.ID.ToString(), Value = country.Name
                });
            }

            //this.Countries.Insert(0, new KeyValue { Key = "", Value = "Country" });

            //regions
            var regions = RegionService.GetRegions(languageID).OrderBy(r => r.Region.Type).ThenBy(r => r.Name);

            this.Regions = new List <GroupedSelectListItem>();

            foreach (var region in regions)
            {
                this.Regions.Add(new GroupedSelectListItem
                {
                    GroupKey  = region.Region.Type == RegionType.Economical ? "2" : "1",
                    GroupName = region.Region.Type == RegionType.Economical ? "Economical" : "Geographical",
                    Text      = region.Name,
                    Value     = region.ID.ToString()
                });
            }

            //this.Regions.Insert(0, new GroupedSelectListItem { GroupKey = "", GroupName = "", Text = "Region", Value = "" });

            //Authority
            Guid authorityID   = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.AuthorityVariableID));
            var  listauthority = SearchServices.GetAuthority(languageID, authorityID);

            this.Authorities = new List <KeyValue>();
            Authorities.Add(new KeyValue {
                Key = "", Value = "--Select One --"
            });
            foreach (var authorities in listauthority)
            {
                Authorities.Add(new KeyValue {
                    Key = authorities.ToString(), Value = authorities.ToString()
                });
            }

            //Documents
            Guid documentTypeVariableID = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.DocumentTypeVariableID));
            var  choiceLanguages        = VariableService.GetChoiceOptions(languageID, documentTypeVariableID);

            this.DocumentTypes = new List <KeyValue>();

            foreach (var choiceLanguage in choiceLanguages)
            {
                this.DocumentTypes.Add(new KeyValue {
                    Key = choiceLanguage.ID.ToString(), Value = choiceLanguage.Name
                });
            }
        }
Ejemplo n.º 15
0
        public static SearchQueryGroup BuildSearchQuery(SearchCriteria model, string[] searchFields)
        {
            //GOAL: (Title:[term]* Content:[term*]) AND (Title:[secondTerm]* Content:[secondTerm]*) AND (Type:[t1] OR Type:[t2] ... OR Type:[tN]) AND (Category:[c1] ... OR Category:[cN])
            //log.Trace("Keyword: {0}", keyword);
            var queryGroups = new SearchQueryGroup(QueryOperator.And);

            //var queryGroups = new List<string>();

            //**** TERMS ****
            var documentLibraryToSearch = AppSettingsUtility.GetValue <string>("ResourceLibrary.DocumentLibrary.ToSearch");

            if (!string.IsNullOrEmpty(documentLibraryToSearch))
            {
                var SearchDocumentLibraryGroup = new SearchQueryGroup(QueryOperator.Or);
                var documentLibraries          = documentLibraryToSearch.Split(',').ToList();

                foreach (var documentLibrary in documentLibraries)
                {
                    var searchTerm = new SearchTerm();
                    searchTerm.Field = "DocumentLibrary";
                    searchTerm.Value = documentLibrary;
                    SearchDocumentLibraryGroup.AddTerm(searchTerm);
                }

                queryGroups.AddGroup(SearchDocumentLibraryGroup);
            }

            //**** TERMS ****
            if (!string.IsNullOrEmpty(model.Term))
            {
                var SearchTermGroup = new SearchQueryGroup(QueryOperator.Or);
                var keyword         = model.Term + " " + model.SecondTerm;

                foreach (var field in searchFields)
                {
                    var keywords = keyword.Split(' ');
                    var count    = keywords.Count();

                    for (int i = 0; i < count; i++)
                    {
                        if (!SitefinityExtensions.IsNullOrEmpty(keywords[i]))
                        {
                            var searchTerm = new SearchTerm();
                            searchTerm.Field = field;
                            //log.Trace("Search Term Field: {0}", searchTerm.Field);
                            searchTerm.Value = keywords[i];
                            //log.Trace("Search Term Value: {0}", searchTerm.Value);
                            SearchTermGroup.AddTerm(searchTerm);
                        }
                    }
                }

                queryGroups.AddGroup(SearchTermGroup);
            }

            //**** TYPES *****
            if (model.Types != null && model.Types.Any())
            {
                var searchTypeGroup = new SearchQueryGroup(QueryOperator.Or);
                foreach (var type in model.Types)
                {
                    var searchTerm = new SearchTerm();
                    searchTerm.Field = "ResourceTypesIds";
                    searchTerm.Value = type;

                    searchTypeGroup.AddTerm(searchTerm);
                }
                queryGroups.AddGroup(searchTypeGroup);
            }

            //**** TOPICS ****
            if (model.Topics != null && model.Topics.Any())
            {
                var searchCategoriesGroup = new SearchQueryGroup(QueryOperator.Or);
                foreach (var cat in model.Topics)
                {
                    var searchTerm = new SearchTerm();
                    searchTerm.Field = "CategoryIds";
                    searchTerm.Value = cat.ToString().Replace("-", "");

                    searchCategoriesGroup.AddTerm(searchTerm);
                }
                queryGroups.AddGroup(searchCategoriesGroup);
            }

            //**** Authors ****
            if (model.Authors != null && model.Authors.Any())
            {
                var searchAuthorsGroup = new SearchQueryGroup(QueryOperator.Or);
                foreach (var cat in model.Authors)
                {
                    var searchTerm = new SearchTerm();
                    searchTerm.Field = "OrganizationalAuthorsIds";
                    searchTerm.Value = cat.ToString().Replace("-", "");

                    searchAuthorsGroup.AddTerm(searchTerm);
                }
                queryGroups.AddGroup(searchAuthorsGroup);
            }

            if (model.Types == null && model.Topics == null && string.IsNullOrEmpty(model.Term) && string.IsNullOrEmpty(model.SecondTerm))
            {
                SearchQueryGroup SearchAnyGroup = new SearchQueryGroup(QueryOperator.Or);
                var searchField = "Title";
                var sTerm       = "a* b* c* d* e* f* g* h* i* j* k* l* m* n* o* p* q* r* s* t* u* v* w* x* y* z*";

                foreach (var term in sTerm.Split(' '))
                {
                    var searchTerm = new SearchTerm
                    {
                        Field = searchField,
                        Value = term
                    };
                    //add wildcards to the query terms
                    SearchAnyGroup.AddTerm(searchTerm);
                }
                queryGroups.AddGroup(SearchAnyGroup);
            }

            return(queryGroups);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Get Filter Records
        /// </summary>
        /// <param name="regions"></param>
        /// <param name="countries"></param>
        /// <param name="internationalSectors"></param>
        /// <param name="documentTypes"></param>
        /// <param name="trueFalseVariables"></param>
        /// <param name="year"></param>
        /// <param name="implementationStart"></param>
        /// <param name="implementationEnd"></param>
        /// <param name="authority"></param>
        /// <param name="lastUpdateStart"></param>
        /// <param name="lastUpdateEnd"></param>
        /// <returns></returns>
        public static List <Guid> GetFilterRecordIds(List <Guid> regions, List <Guid> countries, List <Guid> internationalSectors, List <string> documentTypes,
                                                     List <Guid> trueFalseVariables, int?year, int?implementationStart, int?implementationEnd, string authority,
                                                     DateTime?lastUpdateStart, DateTime?lastUpdateEnd, Guid languageID)
        {
            List <Record> records   = GetRecords();
            List <Guid>   sectors   = new List <Guid>();
            List <Guid>   recordIDs = new List <Guid>();

            if (internationalSectors != null && internationalSectors.Count > 0)
            {
                using (var context = new TSMContext())
                {
                    var query = context.Sectors.Where(s => s.International_NomenclatureID != null &&
                                                      internationalSectors.Contains(s.International_NomenclatureID.Value)).Select(s => s.ID);
                    sectors = query.ToList();
                }
            }


            //Region Checking
            if (regions != null && regions.Count > 0)
            {
                records = (from r in records
                           where r.Regions.Any(region => regions.Any(sr => sr == region.ID))
                           select r).ToList();
            }

            //Country Checking
            if (countries != null && countries.Count > 0 && records != null)
            {
                records = (from r in records
                           where r.Countries.Any(c => countries.Any(sc => sc == c.ID))
                           select r).ToList();
            }

            //Sector Checking
            if (sectors != null && sectors.Count > 0 && records != null)
            {
                records = (from r in records
                           where r.Sectors.Any(c => sectors.Any(sc => sc == c.ID))
                           select r).ToList();
            }

            //Document Type Checking
            var documentTypeVariableID = AppSettingsUtility.GetGuid(AppSettingsKeys.DocumentTypeVariableID);

            if (documentTypes != null && documentTypes.Count > 0 && records != null)
            {
                records = (from r in records
                           where CheckVariableValue(r.Variables, documentTypeVariableID, documentTypes)
                           select r).ToList();
            }

            //True/False variable checking
            if (trueFalseVariables != null && trueFalseVariables.Count > 0 && records != null)
            {
                foreach (var variableID in trueFalseVariables)
                {
                    if (records != null)
                    {
                        records = (from r in records
                                   where CheckVariableValue(r.Variables, variableID, "true")
                                   select r).ToList();
                    }
                }
            }

            //Year checking
            var yearVariableID = AppSettingsUtility.GetGuid(AppSettingsKeys.YearVariableID);

            if (year != null)
            {
                if (records != null)
                {
                    records = (from r in records
                               where CheckVariableValue(r.Variables, yearVariableID, year.Value.ToString())
                               select r).ToList();
                }
            }

            //Implementation Year checking
            var startYearVariableID = AppSettingsUtility.GetGuid(AppSettingsKeys.StartYearVariableID);
            var endYearVariableID   = AppSettingsUtility.GetGuid(AppSettingsKeys.EndYearVariableID);

            if (implementationStart.HasValue && implementationEnd.HasValue)
            {
                if (records != null)
                {
                    records = (from r in records
                               where CheckVariableValue(r.Variables, startYearVariableID, endYearVariableID, implementationStart.Value, implementationEnd.Value)
                               select r).ToList();
                }
            }

            //Last Updated Checking
            var lastUpdatedVariableID = AppSettingsUtility.GetGuid(AppSettingsKeys.LastUpdatedVariableID);

            if (lastUpdateStart.HasValue && lastUpdateEnd.HasValue)
            {
                if (records != null)
                {
                    records = (from r in records
                               where CheckVariableValue(r.Variables, lastUpdatedVariableID, lastUpdateStart.Value, lastUpdateEnd.Value)
                               select r).ToList();
                }
            }

            //Authority Checking
            var AuthorityVariableID = AppSettingsUtility.GetGuid(AppSettingsKeys.AuthorityVariableID);

            if (!string.IsNullOrEmpty(authority))
            {
                if (records != null)
                {
                    records = (from r in records
                               where CheckVariableValue(r.Variables, AuthorityVariableID, authority.ToString())
                               select r).ToList();
                }
            }

            if (records != null && records.Count > 0)
            {
                recordIDs = records.Select(r => r.ID).ToList();
            }

            return(recordIDs);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Populate
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Populate(Guid id, string urlPath)
        {
            bool isExists   = false;
            var  languageID = TSMContext.CurrentSiteLanguageID;

            this.ThematicFocus = new List <string>();
            this.DesignProcess = new List <string>();

            try
            {
                this.RecordLanguage = RecordService.GetRecordLanguage(id, languageID);

                if (this.RecordLanguage != null)
                {
                    isExists = true;

                    this.Name = RecordLanguage.Name;
                    this.ID   = id.ToString();

                    //Document Type
                    var documentType = RecordLanguage.Record.Variables.Where(v => v.VariableID == AppSettingsUtility.GetGuid(AppSettingsKeys.DocumentTypeVariableID) &&
                                                                             v.LanguageID == languageID).FirstOrDefault();
                    if (documentType != null)
                    {
                        this.DocumentType = documentType.Value;
                    }

                    //Description
                    var description = RecordLanguage.Record.Variables.Where(v => v.VariableID == AppSettingsUtility.GetGuid(AppSettingsKeys.DescriptionVariableID) &&
                                                                            v.LanguageID == languageID).FirstOrDefault();

                    if (description != null)
                    {
                        this.Description = description.Value;
                    }

                    this.Region    = GetRegionName(RecordLanguage, languageID);
                    this.Countries = GetCountryNames(RecordLanguage, languageID);

                    // Year
                    var year = RecordLanguage.Record.Variables.Where(v => v.VariableID == AppSettingsUtility.GetGuid(AppSettingsKeys.YearVariableID) &&
                                                                     v.LanguageID == languageID).FirstOrDefault();

                    if (year != null)
                    {
                        this.Year = year.Value;
                    }

                    //last updated
                    var lastUpdated = RecordLanguage.Record.Variables.Where(v => v.VariableID == AppSettingsUtility.GetGuid(AppSettingsKeys.LastUpdatedVariableID) &&
                                                                            v.LanguageID == languageID).FirstOrDefault();

                    if (lastUpdated != null)
                    {
                        this.LastUpdated = GetLastUpdatedValue(lastUpdated.Value);
                    }

                    //Implementation Period
                    var startYear = RecordLanguage.Record.Variables.Where(v => v.VariableID == AppSettingsUtility.GetGuid(AppSettingsKeys.StartYearVariableID) &&
                                                                          v.LanguageID == languageID).FirstOrDefault();
                    var endYear = RecordLanguage.Record.Variables.Where(v => v.VariableID == AppSettingsUtility.GetGuid(AppSettingsKeys.EndYearVariableID) &&
                                                                        v.LanguageID == languageID).FirstOrDefault();

                    if (startYear != null)
                    {
                        this.ImplementationPeriod = startYear.Value;
                    }

                    if (endYear != null)
                    {
                        this.ImplementationPeriod += "/" + endYear.Value;
                    }

                    var variableLanguages = VariableService.GetVariables(languageID);

                    //Thematic focus
                    var thematicVariables = variableLanguages.Where(vl => vl.Variable.VariableCategory == VariableCategory.ThematicFocus &&
                                                                    CompareVariableValue(RecordLanguage.Record.Variables, vl, "true")).ToList();

                    foreach (var variableLanguage in thematicVariables)
                    {
                        this.ThematicFocus.Add(variableLanguage.DisplayName);
                    }
                    this.ThematicFocus = this.ThematicFocus.OrderBy(tf => tf).ToList();

                    //design process focus
                    var designProcessVariables = variableLanguages.Where(vl => vl.Variable.VariableCategory == VariableCategory.DesignProcess &&
                                                                         CompareVariableValue(RecordLanguage.Record.Variables, vl, "true")).ToList();

                    foreach (var variableLanguage in designProcessVariables)
                    {
                        this.DesignProcess.Add(variableLanguage.DisplayName);
                    }
                    this.DesignProcess = this.DesignProcess.OrderBy(dp => dp).ToList();

                    //Populate Sectors
                    var         sectorLanguages = PrioritySectorService.GetSectors(languageID);
                    var         tsmSectors      = SectorService.GetTSMSectors(languageID);
                    List <Guid> sectorIds       = this.RecordLanguage.Record.Sectors.Select(s => s.ID).ToList();
                    this.ServiceSectors = PopulateSectors(sectorIds, sectorLanguages, tsmSectors, SectorType.Service);
                    this.ProductSectors = PopulateSectors(sectorIds, sectorLanguages, tsmSectors, SectorType.Product);

                    //Populate Files
                    this.Files = new List <Document>();
                    if (RecordLanguage.Record.Documents != null)
                    {
                        this.Files = RecordLanguage.Record.Documents;
                    }

                    //Get Public
                    var isPub = RecordLanguage.Record.Variables.Where(v => v.VariableID == AppSettingsUtility.GetGuid(AppSettingsKeys.isDownload) &&
                                                                      v.LanguageID == languageID).FirstOrDefault();

                    if (isPub != null)
                    {
                        if (isPub.Value == "true")
                        {
                            this.isPublic = "ITCdownload";
                        }
                        else
                        {
                            this.isPublic = "Regulardownload";
                        }
                    }
                    else
                    {
                        this.isPublic = "Regulardownload";
                    }



                    //Link Record
                    var linkRecord = RecordLanguage.Record.Variables.Where(v => v.VariableID == AppSettingsUtility.GetGuid(AppSettingsKeys.RecordLink) &&
                                                                           v.LanguageID == languageID).FirstOrDefault();

                    if (linkRecord != null)
                    {
                        this.recordLink = linkRecord.Value;
                    }

                    this.ZipFilePath   = "";
                    this.LoginStat     = "";
                    this.urlPathForDoc = urlPath.ToString();
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteLog("DocumentDetailModel", "Populate", ex, "");
            }

            return(isExists);
        }
Ejemplo n.º 18
0
        public static SimpleSearchFilter GetSearchFilter(LuisResult result, string postalCode)
        {
            //Check if value exists
            if (PageSize <= 0)
            {
                PageSize       = AppSettingsUtility.GetInt("RecordsPerPage");
                MaxMileage     = AppSettingsUtility.GetInt("MaxMileage");
                MaxPrice       = AppSettingsUtility.GetInt("MaxPrice");
                SortBy         = AppSettingsUtility.GetString("SortBy");
                DefaultZipCode = AppSettingsUtility.GetString("DefaultZipCode");
            }


            var filter = new SimpleSearchFilter
            {
                MinMileage    = 0,
                MaxMileage    = MaxMileage,
                PageNo        = 1,
                PageSize      = PageSize,
                MinPrice      = 0,
                MaxPrice      = MaxPrice,
                Radius        = -1,
                SortBy        = SortBy,
                SortDirection = 0,
                PostalCode    = DefaultZipCode
            };

            if (!string.IsNullOrEmpty(postalCode))
            {
                filter.PostalCode = postalCode;
            }

            if (result != null && result.Entities != null && result.Entities.Count > 0)
            {
                if (result.Entities.Any(e => e.Type == BotConstants.LUIS_ENTITY_CONDITION))
                {
                    filter.StockType = result.Entities.FirstOrDefault(e => e.Type == BotConstants.LUIS_ENTITY_CONDITION).Entity;
                }

                if (result.Entities.Any(e => e.Type == BotConstants.LUIS_ENTITY_MAKE))
                {
                    filter.Make = result.Entities.FirstOrDefault(e => e.Type == BotConstants.LUIS_ENTITY_MAKE).Entity;
                }

                if (result.Entities.Any(e => e.Type == BotConstants.LUIS_ENTITY_MODEL))
                {
                    filter.Model = result.Entities.FirstOrDefault(e => e.Type == BotConstants.LUIS_ENTITY_MODEL).Entity;
                }

                if (result.Entities.Any(e => e.Type == BotConstants.LUIS_ENTITY_COLOR))
                {
                    filter.ExteriorColor = result.Entities.FirstOrDefault(e => e.Type == BotConstants.LUIS_ENTITY_COLOR).Entity;
                }

                if (result.Entities.Any(e => e.Type == BotConstants.LUIS_ENTITY_YEAR))
                {
                    filter.Year = result.Entities.FirstOrDefault(e => e.Type == BotConstants.LUIS_ENTITY_YEAR).Entity;
                }

                var priceOptions = GetPriceOptions(result);

                if (result.Entities.Any(e => e.Type == BotConstants.LUIS_ENTITY_PRICE_UNDER) && priceOptions.Count > 0)
                {
                    filter.MaxPrice = priceOptions.OrderByDescending(p => p).FirstOrDefault();
                }

                if (result.Entities.Any(e => e.Type == BotConstants.LUIS_ENTITY_PRICE_ABOVE) && priceOptions.Count > 0)
                {
                    filter.MinPrice = priceOptions.OrderBy(p => p).FirstOrDefault();
                }
            }

            return(filter);
        }
Ejemplo n.º 19
0
        protected override void HandleUnknownAction(string actionName = "")
        {
            try
            {
                log.Info("Begin HandleUnknownAction. view:{0}", _viewTemplate);
                var dynamicModuleManager = DynamicModuleManager.GetManager();

                /*if (string.IsNullOrEmpty(_viewTemplate))
                 * {
                 *  this.View(new EmptyResult()).ExecuteResult(ControllerContext);
                 *
                 * }*/

                var dynamicTypes     = new List <Type>();
                var dynamicTypeNames = AppSettingsUtility.GetValue <string>("RelatedItems.DynamicType.List").Split('|').ToList();

                foreach (var dynamicTypeName in dynamicTypeNames)
                {
                    if (!string.IsNullOrWhiteSpace(dynamicTypeName))
                    {
                        dynamicTypes.Add(TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model." + dynamicTypeName));
                    }
                }
                // set default
                if (dynamicTypes.Count == 0)
                {
                    dynamicTypes.Add(TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.OnSceneArticles.OnSceneArticle"));
                }


                var taxonomyManager = TaxonomyManager.GetManager();
                var currentContext  = System.Web.HttpContext.Current;
                var postUrl         = currentContext.Request.Url.AbsolutePath;

                if (postUrl.Contains('?'))
                {
                    postUrl = postUrl.Split('?').First();
                    log.Trace("postUrl: {0}", SitefinityExtensions.IsNullOrEmpty(postUrl) ? "There is no url available" : postUrl);
                }

                postUrl = currentContext.Request.Url.AbsolutePath.Split('/').Last();
                log.Debug("postUrl: {0}", SitefinityExtensions.IsNullOrEmpty(postUrl) ? "There is no url available" : postUrl);

                foreach (var dynamicType in dynamicTypes)
                {
                    var item = dynamicModuleManager.GetDataItems(dynamicType)
                               .FirstOrDefault(bp => bp.UrlName == postUrl && bp.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live);

                    if (item != null)
                    {
                        //log.Debug("item: {0}", SitefinityExtensions.IsNullOrEmpty(item.GetValue<Lstring>("Title").Value) ? "There is no title set" : item.GetValue<Lstring>("Title").Value);
                        //---item = dynamicModuleManager.Lifecycle.GetLive(item) as DynamicContent;
                        //log.Trace("Got the live version of the Blog Post.");
                        try
                        {
                            //var allCategories = Enumerable.ToArray(item.GetValue<IList<Guid>>("Category"));
                            var allCategories = item.GetValue <IList <Guid> >("Category")?.ToArray();
                            //log.Debug("Got a list of category ids for the post, {0}.", allCategories.Count());
                            List <Guid> categories = new List <Guid>();

                            //log.Trace("Set the list for Blended List Query.");
                            int hitCount = 0;
                            //log.Trace("Set the hitcount variable required for Sitefinity Search.");
                            if (allCategories != null && allCategories.Any())
                            {
                                foreach (var currGuid in allCategories)
                                {
                                    var currTaxon = taxonomyManager.GetTaxon <HierarchicalTaxon>(currGuid);

                                    if (currTaxon != null)
                                    {
                                        //log.Debug("Got taxonomy, {0}, for the id, {1}", SitefinityExtensions.IsNullOrEmpty(currTaxon.Title.Value) ? "There is no title set" : currTaxon.Title.Value);
                                        categories.Add(currGuid);
                                        //log.Trace("Taxon added to the list for the search.");
                                    }
                                }
                            }

                            IEnumerable <IDocument> resultListItems = BlendedNewsHelper.GetNewsDocs(Providers, _searchIndex, out hitCount,
                                                                                                    categories?.ToArray(), null, 0, this.NumberOfPosts + 10);

                            List <BlendedListItem> blendedListItems = new List <BlendedListItem>();
                            if (resultListItems != null)
                            {
                                var rs = SetBlendedListItems(resultListItems);
                                if (rs != null)
                                {
                                    blendedListItems = rs
                                                       .Where(bli => !bli.Link.Contains(item.UrlName) &&
                                                              !bli.Featured).Take(this.NumberOfPosts).ToList();
                                }
                            }
                            //string template = _viewTemplate;
                            //log.Info("Finishing HandleUnknownAction");
                            this.View(_viewTemplate, blendedListItems).ExecuteResult(ControllerContext);
                        }
                        catch (Exception ex)
                        {
                            log.Error("Source: {0}", ex.Source);
                            log.Error("Stack Trace: {0}", ex.StackTrace);
                            log.Error("HandleUnknownAction-relatedContentForDyn: {0}", ex.Message);
                        }
                    }
                    else
                    {
                        log.Debug("There was no item for the given url, ({0}).", SitefinityExtensions.IsNullOrEmpty(postUrl) ? "There is no url available" : postUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Info("exceptionRelatedContent:{0}, inner:{1}", ex.Message, ex.InnerException?.Message);
            }
        }
Ejemplo n.º 20
0
        private void AddMetaDataTagsFromArticle(DynamicContent dynamicContent)
        {
            Page.RemoveExistingPublishedTags();

            // add published date tags
            Page.AddCustomMetaTags("Published", dynamicContent.PublicationDate.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture));

            TaxonomyManager taxonomyManager = TaxonomyManager.GetManager();

            if (dynamicContent.DoesFieldExist("Category"))
            {
                TrackedList <Guid> categoryIds = dynamicContent.GetValue("Category") as TrackedList <Guid>;
                if (categoryIds != null && categoryIds.Any())
                {
                    var categoryList = string.Join(",", categoryIds.Select(cid => taxonomyManager.GetTaxon(cid).Title));
                    Page.AddCustomMetaTags("webcategory", categoryList);
                }
            }

            if (dynamicContent.DoesFieldExist("resourcetypes"))
            {
                TrackedList <Guid> resourcetypesIds = dynamicContent.GetValue("resourcetypes") as TrackedList <Guid>;
                if (resourcetypesIds != null && resourcetypesIds.Any())
                {
                    var resourcetypesList = string.Join(",", resourcetypesIds.Select(cid => taxonomyManager.GetTaxon(cid).Title));
                    Page.AddCustomMetaTags("resourcetypes", resourcetypesList);
                }
            }

            Page.RemoveExistingModuleTags();
            string modulePage = dynamicContent.GetType().Name;

            try
            {
                if (!AppSettingsUtility.GetValue <string>("MetaDataTags.Article.Name").IsNullOrWhitespace())
                {
                    modulePage = AppSettingsUtility.GetValue <string>("MetaDataTags.Article.Name");
                }
            }
            catch (Exception)
            {
            }

            Page.AddCustomMetaTags("Module", modulePage);


            Type type;

            if (dynamicContent.SystemParentItem != null)
            {
                type = dynamicContent.SystemParentItem.GetType();
            }
            else
            {
                type = dynamicContent.GetType();
            }

            string articleType = type.FullName.Split('.')[4];

            //Could change this to work with On-Scene Articles...
            if (articleType.ToLower().Contains("healthprogress"))
            {
                Page.AddCustomMetaTags("Publication", "Health Progress");
                //Health Progress
            }

            if (dynamicContent.DoesFieldExist("author"))
            {
                var authorname = dynamicContent.Author;
                if (authorname != null)
                {
                    Page.AddCustomMetaTags("ContentAuthor", authorname);
                }
            }
            var authorsFieldName = "organizationalauthors";

            if (dynamicContent.DoesFieldExist(authorsFieldName))
            {
                TrackedList <Guid> authorIds = dynamicContent.GetValue(authorsFieldName) as TrackedList <Guid>;
                if (authorIds != null)
                {
                    var authorList = string.Join(",", authorIds.Select(cid => taxonomyManager.GetTaxon(cid).Title));
                    Page.AddCustomMetaTags("contentauthor", authorList);
                }
            }
        }
Ejemplo n.º 21
0
        public ActionResult download(string id, string isPublic)
        {
            try
            {//intracen
                string UrlReferrerForDoc = Request.UrlReferrer.ToString();
                bool   contains          = UrlReferrerForDoc.Contains("intracen");
                if (contains == false)
                {
                    urlPathForDoc = UrlReferrerForDoc;
                }
            }
            catch { }
            if (isPublic == "ITCdownload")
            {
                //Authorization checking
                if (AppSettingsUtility.GetBool(AppSettingsKeys.EnableAuthorization) && Session[SiteConstants.SESSION_USER_AUTHORIZED] == null)
                {
                    string logonURL  = AppSettingsUtility.GetString(AppSettingsKeys.LogOnURL);
                    string returnURL = HttpUtility.UrlEncode(Request.Url.ToString());
                    string domain    = Request.Url.Host;
                    logonURL = logonURL.Replace("[returnURL]", returnURL).Replace("[authDomain]", domain);
                    return(Redirect(logonURL));
                }
            }

            if (System.Web.HttpContext.Current.Session[SiteConstants.SESSION_USER] != null)
            {
                TSM.Entity.User user = (TSM.Entity.User)System.Web.HttpContext.Current.Session[SiteConstants.SESSION_USER];

                string mail     = user.Email;
                string host     = mail.Split('@')[1].ToString();
                string mailCred = "intracen.org"; // "intracen.org";

                if (host != mailCred)
                {
                    return(Content("<script language='javascript' type='text/javascript'>alert('You are not authorized to download the document.'); window.close();</script>"));
                }
            }

            string zipFolderPath = Server.MapPath("~/UploadedFiles/Documents/tempZip/");
            string zipFilePath   = "document_" + DateTime.Now.Ticks.ToString() + ".zip";

            if (!Directory.Exists(zipFolderPath))
            {
                Directory.CreateDirectory(zipFolderPath);
            }

            string folderPath = Server.MapPath("~/UploadedFiles/Documents/");

            Guid recordID = Guid.Empty;

            if (!string.IsNullOrEmpty(id))
            {
                Guid.TryParse(id, out recordID);
            }

            if (recordID == null || recordID == Guid.Empty)
            {
                return(Redirect("/"));
            }

            var documents = RecordService.GetDocuments(recordID);

            if (documents == null || documents.Count == 0)
            {
                return(Redirect("/"));
            }

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

            foreach (var document in documents)
            {
                string file = folderPath + document.Path;
                files.Add(file);
            }
            string ZipFile = zipFolderPath + zipFilePath;

            ZipHelper.WriteZipFile(files, ZipFile, 6);

            byte[] fileBytes = System.IO.File.ReadAllBytes(ZipFile);
            string fileName  = "document.zip";

            Guid documentID = Guid.Empty;

            if (!string.IsNullOrEmpty(id))
            {
                Guid.TryParse(id, out documentID);
            }
            var  model    = new DocumentDetailModel();
            bool isExists = model.Populate(documentID, urlPathForDoc);

            model.ZipFilePath = ZipFile.ToString();
            model.LoginStat   = "Y";

            return(View("~/Views/Document/Index.cshtml", model));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Populate Model
        /// </summary>
        /// <param name="id"></param>
        public void Populate(Guid id, Guid languageID)
        {
            try
            {
                this.Page = PageService.GetPage(id);

                if (!ReferenceEquals(this.Page, null))
                {
                    this.Page_Language = this.Page.Content_Languages.Where(p => p.LanguageID == languageID).FirstOrDefault();
                    if (this.Page_Language == null)
                    {
                        Guid defaultLanguageID = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.DefaultLanguageID));
                        this.Page_Language = this.Page.Content_Languages.Where(p => p.LanguageID == defaultLanguageID).FirstOrDefault();

                        if (this.Page_Language == null)
                        {
                            this.Page_Language = new Content_Language();
                        }
                    }

                    this.ID              = id;
                    this.BrowserTitle    = this.Page_Language.PageTitle;
                    this.MetaKeywords    = this.Page_Language.PageKeywords;
                    this.MetaDescription = this.Page_Language.PageMetadata;
                    this.Title           = this.Page_Language.Title;
                    this.SubTitle        = this.Page_Language.SubTitle;
                    this.Summary         = this.Page_Language.Summary;
                    this.Type            = (ContentType)this.Page.Type;
                    this.URL             = this.Page.URL;
                    this.LanguageID      = languageID;


                    //Populate main contents & right section contents
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    if (!string.IsNullOrEmpty(this.Page_Language.Description))
                    {
                        try
                        {
                            this.MainContents = serializer.Deserialize <List <PageContent> >(this.Page_Language.Description);
                        }
                        catch
                        {
                        }
                    }

                    if (!string.IsNullOrEmpty(this.Page_Language.RightSection))
                    {
                        try
                        {
                            this.RightSectionContents = serializer.Deserialize <List <PageContent> >(this.Page_Language.RightSection);
                        }
                        catch
                        {
                        }
                    }

                    if (this.MainContents == null || this.MainContents.Count == 0)
                    {
                        this.MainContents = new List <PageContent>();
                        this.MainContents.Add(new PageContent {
                            Title = "", HTML = ""
                        });
                    }

                    if (this.RightSectionContents == null || this.RightSectionContents.Count == 0)
                    {
                        this.RightSectionContents = new List <PageContent>();
                        this.RightSectionContents.Add(new PageContent {
                            Title = "", HTML = ""
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteLog("ManagePageModel", "Populate", ex, "");
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Populate Record
        /// </summary>
        /// <param name="id"></param>
        /// <param name="languageID"></param>
        public void PopulateRecord(Guid id, Guid languageID)
        {
            try
            {
                //Populate record
                if (id != Guid.Empty)
                {
                    this.Record = RecordService.GetRecord(id);
                    if (this.Record != null && this.Record.Record_Languages != null && this.Record.Record_Languages.Count > 0)
                    {
                        Record_Language recordLanguage = new Record_Language();
                        this.IsActive = this.Record.IsActive;
                        this.IsPublic = this.Record.IsPublic;
                        if (this.Record.Record_Languages.Any(rl => rl.LanguageID == languageID))
                        {
                            recordLanguage = this.Record.Record_Languages.Where(rl => rl.LanguageID == languageID).FirstOrDefault();
                        }
                        else // populate with default language id
                        {
                            var defaultLanguageID = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.DefaultLanguageID));
                            recordLanguage = this.Record.Record_Languages.Where(rl => rl.LanguageID == defaultLanguageID).FirstOrDefault();
                        }

                        //populate name
                        if (recordLanguage != null)
                        {
                            this.Name = recordLanguage.Name;
                            this.Record.Record_Languages = new List<Record_Language>();
                            this.Record.Record_Languages.Add(recordLanguage);
                        }

                        //Populate selected Countries
                        if (this.Record.Countries != null && this.Record.Countries.Count > 0)
                        {
                            this.SelectedCountries = (from c in this.Record.Countries
                                                      select c.ID).ToList();
                        }

                        //Populate selected Regions
                        if (this.Record.Regions != null && this.Record.Regions.Count > 0)
                        {
                            this.SelectedRegions = (from r in this.Record.Regions
                                                    select r.ID).ToList();
                        }

                        //Populate selected Sectors
                        if (this.Record.Sectors != null && this.Record.Sectors.Count > 0)
                        {
                            this.SelectedSectors = (from s in this.Record.Sectors
                                                    select s.ID).ToList();

                        }
                        if (this.SelectedSectors != null && this.SelectedSectors.Count > 0)
                        {
                            this.Sector_Languages = PrioritySectorService.GetSectorLanguage(this.SelectedSectors);
                        }

                        //populate documents
                        this.Documents = string.Empty;
                        if (this.Record.Documents != null && this.Record.Documents.Count > 0)
                        {
                            foreach (var document in this.Record.Documents)
                            {
                                this.Documents += document.Path + "|";
                            }
                            this.Documents = this.Documents.TrimEnd('|');
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteLog("ManageRecordModel", "PopulateRecord", ex, string.Empty);
            }
        }
Ejemplo n.º 24
0
        public static IEnumerable <SearchResult> GetSearchResults(string catalog, SearchCriteria criteria, int skip,
                                                                  int take, int summaryWordCount, out int hitCount)
        {
            var searchService = ServiceBus.ResolveService <ISearchService>();
            var searchQuery   = ObjectFactory.Resolve <ISearchQuery>();

            var           queryBuilder = ObjectFactory.Resolve <IQueryBuilder>();
            StringBuilder sb           = new StringBuilder();


            searchQuery.Skip              = skip;
            searchQuery.Take              = take;
            searchQuery.OrderBy           = criteria.OrderBy == null ? new string[] { "PublicationDate DESC" } : new string[] { criteria.OrderBy };
            searchQuery.HighlightedFields = null;
            searchQuery.IndexName         = catalog;
            searchQuery.SearchGroup       = BuildSearchQuery(criteria, new[] { "Title", "Content", "DocumentText" });

            var resultSet = searchService.Search(searchQuery);

            hitCount = resultSet.HitCount;

            var results         = new List <SearchResult>();
            var taxonomyManager = TaxonomyManager.GetManager();

            log.InfoFormat("ResourceLib:{0};",
                           criteria.ToQueryString());

            var searchResult = new SearchResult();

            foreach (IDocument item in resultSet.SetContentLinks())
            {
                try
                {
                    var fields = item.Fields;
                    searchResult = new SearchResult()
                    {
                        CategoryPair    = new List <CategoryPair>(),
                        Author          = new List <CategoryPair>(),
                        ResourceTypes   = new List <CategoryPair>(),
                        Title           = item.GetValue("Title")?.ToString() ?? "",
                        Link            = item.GetValue("Link")?.ToString() ?? "",
                        PublicationDate = DateTime.MinValue,
                        DocumentFolder  = item.GetValue("DocumentLibrary")?.ToString() ?? "",
                        Summary         = item.GetValue("Summary")?.ToString() ?? "",
                        Type            = item.GetValue("ContentType")?.ToString() ?? "",
                        ImageUrl        = item.GetValue("ThumbnailUrl")?.ToString() ?? item.GetValue("ImageUrl")?.ToString() ?? "",
                        EventStart      = DateTime.MinValue,
                        EventEnd        = DateTime.MinValue
                    };

                    searchResult.Type = TypeResolutionService.ResolveType(searchResult.Type)?.Name ?? "";

                    if (!string.IsNullOrEmpty(item.GetValue("PublishDate")?.ToString()))
                    {
                        DateTime d1 = DateTime.MinValue;
                        DateTime.TryParse(item.GetValue("PublishDate").ToString(), out d1);
                        searchResult.PublicationDate = d1;
                    }
                    if (fields.Any(f => f.Name == "EventStart") && !string.IsNullOrWhiteSpace(item.GetValue("EventStart")?.ToString()))
                    {
                        DateTime d1 = DateTime.MinValue;
                        DateTime.TryParse(item.GetValue("EventStart").ToString(), out d1);
                        searchResult.EventStart = d1;
                    }
                    if (fields.Any(f => f.Name == "EventEnd") && !string.IsNullOrWhiteSpace(item.GetValue("EventEnd")?.ToString()))
                    {
                        DateTime d1 = DateTime.MinValue;
                        DateTime.TryParse(item.GetValue("EventEnd").ToString(), out d1);
                        searchResult.EventEnd = d1;
                    }

                    /*if (string.IsNullOrWhiteSpace(searchResult.Summary))
                     * {
                     *  searchResult.Summary = SummaryParser.GetSummary(content, new SummarySettings(SummaryMode.Words, summaryWordCount, true, true));
                     * }*/

                    sb.AppendFormat("getCategories");
                    if (fields.Any(f => f.Name == "CategoryIds"))
                    {
                        var parentGuidId = AppSettingsUtility.GetValue <Guid>("ResourceLibraryTaxonomyId");
                        item.GetValue("CategoryIds")?.ToString().Split(' ')?
                        .ToList()
                        .ForEach(m =>
                        {
                            if (m.IsGuid())
                            {
                                var category = taxonomyManager.GetTaxon(Guid.Parse(m)) as HierarchicalTaxon;
                                //while (category?.Parent != null)
                                //{
                                if (category?.Parent?.Id == parentGuidId)
                                {
                                    searchResult.CategoryPair.Add(new CategoryPair()
                                    {
                                        Name = category.Title.Value,
                                        Guid = m.Replace("-", string.Empty)
                                    });
                                    category = taxonomyManager.GetTaxon(category.Parent.Id) as HierarchicalTaxon;
                                }

                                //};
                            }
                        });
                    }

                    sb.AppendFormat("getAuthors");
                    if (fields.Any(f => f.Name == "OrganizationalAuthorsIds") && !string.IsNullOrEmpty(item.GetValue("OrganizationalAuthorsIds")?.ToString()))
                    {
                        item.GetValue("OrganizationalAuthorsIds").ToString().Split(' ').ToList()
                        .ForEach(m =>
                        {
                            var taxonomyGuidId = AppSettingsUtility.GetValue <Guid>("ResourceLibraryTaxonomyAuthorId");
                            if (m.IsGuid())
                            {
                                var category = taxonomyManager.GetTaxon(Guid.Parse(m)) as HierarchicalTaxon;
                                if (category?.Taxonomy?.Id != null && category.Taxonomy.Id == taxonomyGuidId)
                                {
                                    searchResult.Author.Add(new CategoryPair()
                                    {
                                        Name = category.Title.Value,
                                        Guid = m.Replace("-", string.Empty)
                                    });
                                }
                            }
                        });
                    }

                    sb.AppendFormat("getTypes");
                    if (fields.Any(f => f.Name == "ResourceTypesIds") &&
                        !string.IsNullOrEmpty(item.GetValue("ResourceTypesIds")?.ToString()))
                    {
                        item.GetValue("ResourceTypesIds").ToString().Split(' ').ToList()
                        .ForEach(m =>
                        {
                            var taxonomyGuidId = AppSettingsUtility.GetValue <Guid>("ResourceLibraryTaxonomyTypeId");
                            if (m.IsGuid())
                            {
                                var category = taxonomyManager.GetTaxon(Guid.Parse(m)) as HierarchicalTaxon;
                                if (category?.Taxonomy?.Id != null && category.Taxonomy.Id == taxonomyGuidId)
                                {
                                    searchResult.ResourceTypes.Add(new CategoryPair()
                                    {
                                        Name = category.Title.Value,
                                        Guid = m.Replace("-", string.Empty)
                                    });
                                }
                            }
                        });
                    }

                    results.Add(searchResult);
                    log.InfoFormat("Resources-result:{0} item:{1} \r", sb.ToString(), StringExtensions.ToJson(searchResult));
                }
                catch (Exception ex)
                {
                    log.InfoFormat("testfailed:{0}, details:{1}", ex.Message, sb.ToString());
                }
            }

            return(results);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Save Records
        /// </summary>
        /// <returns></returns>
        public bool Save()
        {
            bool isSuccess = false;

            try
            {

                var record = new Record();

                //For add
                if (this.ID == Guid.Empty)
                {
                    record.ID = Guid.NewGuid();
                    record.CreatedBy = TSMContext.CurrentUser.ID;
                    record.CreatedDate = DateTime.UtcNow;
                }
                else // for update
                {
                    record = RecordService.GetRecord(this.ID);
                    record.LastModifiedBy = TSMContext.CurrentUser.ID;
                    record.LastModifiedDate = DateTime.UtcNow;
                }

                record.IsActive = this.IsActive;
                record.IsPublic = this.IsPublic;
                record.IsDeleted = false;

                //Record Language
                record.Record_Languages = new List<Record_Language>();
                record.Record_Languages.Add(new Record_Language
                {
                    ID = record.ID,
                    LanguageID = this.LanguageID,
                    Name = this.Name.Trim()
                });


                //for Documents
                List<Guid> deletedFiles = new List<Guid>();
                List<Document> newDocuments = new List<Document>();
                if (!string.IsNullOrEmpty(this.Documents))
                {
                    List<string> files = this.Documents.Split('|').ToList();
                    if (record.Documents == null)
                    {
                        record.Documents = new List<Document>();
                    }

                    //Add new files
                    foreach (string file in files)
                    {
                        if (!record.Documents.Any(d => d.Path == file))
                        {
                            var document = new Document
                            {
                                ID = Guid.NewGuid(),
                                RecordID = record.ID,
                                Size = 0,
                                Type = GetDocumentType(file),
                                Path = file
                            };
                            newDocuments.Add(document);
                        }
                    }

                    //Delete deleted files
                    foreach (var document in record.Documents)
                    {
                        if (!files.Any(f => f == document.Path))
                        {
                            deletedFiles.Add(document.ID);
                        }
                    }
                    record.Documents.RemoveAll(d => deletedFiles.Any(df => df == d.ID));

                }

                //for record variables
                record.Variables = new List<Record_Variable>();
                foreach (var recordVariable in this.RecordVariables)
                {
                    string value = string.Empty;
                    if (recordVariable.Type == VariableType.SingleChoice || recordVariable.Type == VariableType.Text || recordVariable.Type == VariableType.DateTime)
                    {
                        if (!string.IsNullOrEmpty(recordVariable.StringValue))
                        {
                            value = recordVariable.StringValue.Trim();
                        }
                    }
                    else if (recordVariable.Type == VariableType.Boolean)
                    {
                        value = recordVariable.BoolValue ? "true" : "false";
                    }
                    else if (recordVariable.Type == VariableType.MultipleChoice)
                    {
                        if (recordVariable.SelectedChoices.Count > 0)
                        {
                            foreach (string selectedChoice in recordVariable.SelectedChoices)
                            {
                                value += selectedChoice + "|";
                            }
                            value = value.TrimEnd('|');
                        }
                    }

                    if (!string.IsNullOrEmpty(value))
                    {
                        record.Variables.Add(new Record_Variable
                        {
                            ID = Guid.NewGuid(),
                            RecordID = record.ID,
                            VariableID = recordVariable.VariableID,
                            LanguageID = this.LanguageID,
                            Value = value.Trim()
                        });
                    }

                }

                //Save to service
                record.Documents = newDocuments;
                record.Countries = new List<Country>();
                record.Regions = new List<Region>();
                record.Sectors = new List<Sector>();
                record = RecordService.Save(record, this.LanguageID, deletedFiles, SelectedCountries, SelectedRegions, SelectedSectors, newDocuments);

                //update xml for record
                UpdateXML(record);

                this.ID = record.ID;
                isSuccess = true;

                //Lucene Search
                TSM.Entity.ComplexType.SiteSearchItem siteSearchItem = new Entity.ComplexType.SiteSearchItem();
                Guid descriptionVariableID = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.DescriptionVariableID));
                RecordData recordData = new RecordData();

                //SiteSearch Item Values
                siteSearchItem.ID = record.ID.ToString();
                siteSearchItem.Title = this.Name.Trim();
                siteSearchItem.Description = record.Variables.Where(r => r.VariableID == descriptionVariableID && r.LanguageID == this.LanguageID).FirstOrDefault().Value.ToString();

                //For URL we need to use Eng Language Only
                Guid engLanguageID = AppSettingsUtility.GetGuid(AppSettingsKeys.DefaultLanguageID);
                string enTitle = record.Record_Languages.Where(rl => rl.LanguageID == engLanguageID).FirstOrDefault().Name;

                string url = recordData.GetRecordUrl(record.ID, enTitle);
                siteSearchItem.URL = url;

                siteSearchItem.IsDeleted = record.IsDeleted || !record.IsActive;

                string path = HostingEnvironment.ApplicationPhysicalPath + "LuceneIndex";//path to LuceneIndex folder
                SiteSearchService.SaveToIndexAsync(siteSearchItem, path);
            }
            catch (Exception ex)
            {
                ErrorLog.WriteLog("ManageRecordModel", "Save", ex, string.Empty);
            }

            return isSuccess;
        }
Ejemplo n.º 26
0
        public static List <Record_Variable> GetRecordInYear(Guid languageID, List <Guid> listOfRecordId)
        {
            Guid yearVariableID          = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.YearVariableID));
            Guid startImplementationYear = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.StartYearVariableID));
            Guid endImplementationYear   = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.EndYearVariableID));

            //using (var context = new TSMContext())
            //{

            //   //  var filteredRecords = GetRecordList(languageID, selectedRegions, selectedCountries, selectedSectors, selectedDocumentTypes, documentTypeVariableID);
            //     //var filteredRecordsID = filteredRecords.Select(r => r.ID).ToList();
            //    var filteredRecordsID = listOfRecordId;
            //     var documentTypeVariableID=
            //    var result = from r1 in context.Record_Variables
            //                 where filteredRecordsID.Contains(r1.RecordID) && r1.VariableID == yearVariableID && r1.LanguageID == languageID
            //                 group r1 by r1.Value into grps
            //                 select new
            //                 {
            //                     value = grps.Key,
            //                     recordCount = grps.Count()
            //                 };

            //    List<Record_Variable> recordVariables = new List<Record_Variable>();
            //    Record_Variable recordVaraible;
            //    foreach (var record in result)
            //    {
            //        recordVaraible = new Record_Variable();
            //        recordVaraible.Value = record.value;
            //        recordVaraible.RecordCount = record.recordCount;
            //        recordVariables.Add(recordVaraible);
            //    }

            //    return recordVariables;
            //}

            List <Record_Variable> recordVariables = new List <Record_Variable>();
            List <Record_Variable> results         = new List <Record_Variable>();
            List <Guid>            recordIds       = new List <Guid>();

            using (var context = new TSMContext())
            {
                var filteredRecordsID = listOfRecordId;
                //recordVariables = context.Record_Variables.Where(rv => filteredRecordsID.Contains(rv.RecordID)).ToList();
                recordVariables = context.Record_Variables.Where(rv => filteredRecordsID.Contains(rv.RecordID) && rv.LanguageID == languageID && (rv.VariableID == yearVariableID || rv.VariableID == startImplementationYear || rv.VariableID == endImplementationYear)).ToList();
                recordIds       = context.Record_Languages.Where(rl => rl.LanguageID == languageID).Select(rl => rl.ID).Distinct().ToList();
            }

            int currentYear = DateTime.Now.Year;
            int startYear   = 1980;

            if (recordVariables.Count > 0)
            {
                startYear = Convert.ToInt32(recordVariables.Where(rv => rv.VariableID == startImplementationYear).OrderBy(rv => rv.Value).FirstOrDefault().Value);
            }

            var recordYears = new List <RecordYear>();

            foreach (var recordId in recordIds)
            {
                if (recordVariables.Any(rv => rv.RecordID == recordId))
                {
                    var recordYear = new RecordYear();
                    recordYear.RecordID = recordId;


                    //Start
                    var start = recordVariables.Where(rv => rv.RecordID == recordId && rv.VariableID == startImplementationYear && rv.Value != "").FirstOrDefault();
                    if (start != null)
                    {
                        recordYear.StartYear = Convert.ToInt32(start.Value);
                    }

                    //End
                    var end = recordVariables.Where(rv => rv.RecordID == recordId && rv.VariableID == endImplementationYear && rv.Value != "").FirstOrDefault();
                    if (end != null)
                    {
                        recordYear.EndYear = Convert.ToInt32(end.Value);
                    }

                    //Year
                    var year = recordVariables.Where(rv => rv.RecordID == recordId && rv.VariableID == yearVariableID && rv.Value != "").FirstOrDefault();
                    if (year != null && recordYear.StartYear == 0)
                    {
                        recordYear.StartYear = Convert.ToInt32(year.Value);
                        recordYear.EndYear   = recordYear.StartYear + 5;
                    }

                    recordYears.Add(recordYear);
                }
            }

            for (int count = startYear; count <= currentYear; count++)
            {
                var result = new Record_Variable();
                result.Value = count.ToString();

                result.RecordCount = recordYears.Where(ry => ry.StartYear <= count && ry.EndYear >= count).Count();

                results.Add(result);
            }

            return(results);
        }
Ejemplo n.º 27
0
        public void LoadRollbarAppSettingsTest()
        {
            var sever = new Server();

            RollbarConfig config = new RollbarConfig("default=none");

            Assert.IsNull(config.Person);
            Assert.IsNull(config.Server);

            AppSettingsUtility.LoadAppSettings(config, Path.Combine(Environment.CurrentDirectory, "TestData"), "appsettings.json");

            // The test data looks like this:
            //===============================
            //"Rollbar": {
            //    "AccessToken": "17965fa5041749b6bf7095a190001ded",
            //    "Environment": "unit-tests",
            //    "Enabled": true,
            //    "MaxReportsPerMinute": 160,
            //    "ReportingQueueDepth": 120,
            //    "LogLevel": "Info",
            //    "ScrubFields": [
            //      "ThePassword",
            //      "TheSecret"
            //    ],
            //    "Server": {
            //      "Root": "C://Blah/Blah",
            //      "Cpu": "x64"
            //    },
            //    "Person": {
            //      "UserName": "******"
            //    },
            //    "PersonDataCollectionPolicies": "Username, Email",
            //    "IpAddressCollectionPolicy": "CollectAnonymized",
            //  }

            Assert.AreEqual("17965fa5041749b6bf7095a190001ded", config.AccessToken);
            Assert.AreEqual("unit-tests", config.Environment);
            Assert.AreEqual(true, config.Enabled);
            Assert.AreEqual(160, config.MaxReportsPerMinute);
            Assert.AreEqual(120, config.ReportingQueueDepth);
            Assert.AreEqual(ErrorLevel.Info, config.LogLevel.Value);
            Assert.IsTrue(config.ScrubFields.Length >= 2);
            Assert.AreEqual("jbond", config.Person.UserName);
            Assert.AreEqual(
                PersonDataCollectionPolicies.Username | PersonDataCollectionPolicies.Email
                , config.PersonDataCollectionPolicies
                );
            Assert.AreEqual(
                IpAddressCollectionPolicy.CollectAnonymized
                , config.IpAddressCollectionPolicy
                );

            Assert.IsNotNull(config.Server);
            Assert.IsTrue(config.Server.ContainsKey("cpu"));
            Assert.IsTrue(config.Server.ContainsKey("root"));
            Assert.IsFalse(config.Server.ContainsKey("Cpu"));
            Assert.IsFalse(config.Server.ContainsKey("Root"));
            Assert.AreEqual(config.Server["cpu"], config.Server.Cpu);
            Assert.AreEqual(config.Server["root"], config.Server.Root);
            Assert.AreEqual("x64", config.Server.Cpu);
            Assert.AreEqual("C://Blah/Blah", config.Server.Root);
        }
Ejemplo n.º 28
0
        public static IEnumerable <SearchResult> GetSearchResults_stv(string catalog, SearchCriteria criteria, int skip, int take, int summaryWordCount, out int hitCount)
        {
            var searchService = ServiceBus.ResolveService <ISearchService>();
            var searchQuery   = ObjectFactory.Resolve <ISearchQuery>();

            var           queryBuilder = ObjectFactory.Resolve <IQueryBuilder>();
            StringBuilder sb           = new StringBuilder();


            searchQuery.Skip              = skip;
            searchQuery.Take              = take;
            searchQuery.OrderBy           = criteria.OrderBy == null ? new string[] { "PublicationDate DESC" } : new string[] { criteria.OrderBy };
            searchQuery.HighlightedFields = null;
            searchQuery.IndexName         = catalog;
            searchQuery.SearchGroup       = BuildSearchQuery(criteria, new[] { "Title", "Content", "DocumentText" });

            var resultSet = searchService.Search(searchQuery);

            hitCount = resultSet.HitCount;

            var results         = new List <SearchResult>();
            var taxonomyManager = TaxonomyManager.GetManager();

            log.InfoFormat("ResourceLib:{0};",
                           criteria.ToQueryString());

            foreach (var result in resultSet.SetContentLinks())
            {
                var searchResult = new SearchResult();

                try
                {
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("CategoryIds").ToString()))
                    {
                        var categoryIds = result.GetValue("CategoryIds").ToString().Split(' ').ToList();

                        searchResult.CategoryPair = new List <CategoryPair>();
                        var parentGuidId = AppSettingsUtility.GetValue <Guid>("ResourceLibraryTaxonomyId");

                        foreach (var categoryId in categoryIds)
                        {
                            log.InfoFormat("ResourceLibraryTaxonomyId-cateids:{0}, parentGuidId:{1}", categoryIds, parentGuidId);
                            var category = taxonomyManager.GetTaxon(Guid.Parse(categoryId)) as HierarchicalTaxon;

                            do
                            {
                                if (category.Parent != null && category.Parent.Id == parentGuidId)
                                {
                                    category = taxonomyManager.GetTaxon(Guid.Parse(categoryId)) as HierarchicalTaxon;
                                    var categoryPair = new CategoryPair();
                                    categoryPair.Name = category.Title.Value;
                                    categoryPair.Guid = categoryId.ToString().Replace("-", "");

                                    log.InfoFormat("CateInParent, Title:{0}, guid:{1}", categoryPair.Name, categoryPair.Guid);
                                    sb.Append(String.Format("CateInParent, Title:{0}, guid:{1}", categoryPair.Name,
                                                            categoryPair.Guid));
                                    searchResult.CategoryPair.Add(categoryPair);
                                    break;
                                }

                                category = taxonomyManager.GetTaxon(category.Parent.Id) as HierarchicalTaxon;
                            } while (category.Parent != null);
                        }
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("OrganizationalAuthorsIds").ToString()))
                    {
                        var categoryIds = result.GetValue("OrganizationalAuthorsIds").ToString().Split(' ').ToList();
                        searchResult.Author = new List <CategoryPair>();
                        var taxonomyGuidId = AppSettingsUtility.GetValue <Guid>("ResourceLibraryTaxonomyAuthorId");

                        foreach (var categoryId in categoryIds)
                        {
                            var category = taxonomyManager.GetTaxon(Guid.Parse(categoryId)) as HierarchicalTaxon;

                            if (category.Taxonomy.Id == taxonomyGuidId)
                            {
                                var categoryPair = new CategoryPair();
                                categoryPair.Name = category.Title.Value;
                                categoryPair.Guid = categoryId.ToString().Replace("-", "");
                                searchResult.Author.Add(categoryPair);

                                log.InfoFormat("ResourceLibraryTaxonomyAuthorId-Title:{0}, guid:{1}", categoryPair.Name, categoryPair.Guid);
                                sb.AppendFormat("ResourceLibraryTaxonomyAuthorId-Title:{0}, guid:{1}", categoryPair.Name,
                                                categoryPair.Guid);
                            }
                        }
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("ResourceTypesIds").ToString()))
                    {
                        var categoryIds = result.GetValue("ResourceTypesIds").ToString().Split(' ').ToList();
                        searchResult.ResourceTypes = new List <CategoryPair>();
                        var taxonomyGuidId = AppSettingsUtility.GetValue <Guid>("ResourceLibraryTaxonomyTypeId");

                        foreach (var categoryId in categoryIds)
                        {
                            var category = taxonomyManager.GetTaxon(Guid.Parse(categoryId)) as HierarchicalTaxon;

                            if (category.Taxonomy.Id == taxonomyGuidId)
                            {
                                var categoryPair = new CategoryPair();
                                categoryPair.Name = category.Title.Value;
                                categoryPair.Guid = categoryId.ToString().Replace("-", "");
                                searchResult.ResourceTypes.Add(categoryPair);

                                log.InfoFormat("ResourceLibraryTaxonomyTypeId-Title:{0}, guid:{1}", categoryPair.Name, categoryPair.Guid);
                                sb.AppendFormat("ResourceLibraryTaxonomyTypeId-Title:{0}, guid:{1}", categoryPair.Name, categoryPair.Guid);
                            }
                        }
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("Title").ToString()))
                    {
                        searchResult.Title = result.GetValue("Title").ToString();
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("Link").ToString()))
                    {
                        searchResult.Link = result.GetValue("Link").ToString();
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("PublishDate").ToString()))
                    {
                        searchResult.PublicationDate = DateTime.Parse(result.GetValue("PublishDate").ToString());
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("DocumentLibrary").ToString()))
                    {
                        searchResult.DocumentFolder = result.GetValue("DocumentLibrary").ToString();
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("Summary").ToString()))
                    {
                        searchResult.Summary = result.GetValue("Summary").ToString();
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("ContentType").ToString()))
                    {
                        searchResult.Type = result.GetValue("ContentType").ToString();
                    }

                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("ThumbnailUrl").ToString()))
                    {
                        searchResult.ImageUrl = result.GetValue("ThumbnailUrl").ToString();
                    }
                    else if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("ImageUrl").ToString()))
                    {
                        searchResult.ImageUrl = result.GetValue("ImageUrl").ToString();
                    }

                    var contentType = TypeResolutionService.ResolveType(searchResult.Type);

                    searchResult.Type = contentType.Name;



                    if (result.Fields.Any(f => f.Name == "EventStart") && !string.IsNullOrWhiteSpace(result.GetValue("EventStart").ToString()))
                    {
                        searchResult.EventStart = DateTime.Parse(result.GetValue("EventStart").ToString());
                    }

                    if (result.Fields.Any(f => f.Name == "EventEnd") && !string.IsNullOrWhiteSpace(result.GetValue("EventEnd").ToString()))
                    {
                        searchResult.EventEnd = DateTime.Parse(result.GetValue("EventEnd").ToString());
                    }
                    var content      = result.GetValue("Content").ToString().StripHtmlTags();
                    var docLink      = result.GetValue("DocumentLink");
                    var documentText = result.GetValue("DocumentText");
                    if (string.IsNullOrWhiteSpace(content) && !string.IsNullOrWhiteSpace(docLink.ToString()))
                    {
                        searchResult.Link = docLink.ToString();
                        content           = documentText.ToString();
                    }

                    if (string.IsNullOrWhiteSpace(searchResult.Summary))
                    {
                        searchResult.Summary = SummaryParser.GetSummary(content, new SummarySettings(SummaryMode.Words, summaryWordCount, true, true));
                    }
                }
                catch (Exception ex)
                {
                    //ex.ToString();
                    log.InfoFormat("Resources-Exception:{0}, details:{1}", ex.Message, sb.ToString());
                }

                results.Add(searchResult);
            }

            return(results);
        }
Ejemplo n.º 29
0
 public static List <Tuple <string, string, int> > SearchTypes()
 {
     return(SearchTypes(AppSettingsUtility.GetValue <string>("ContentListContentTypeFilterMapList")));
 }
Ejemplo n.º 30
0
        public static string GetVariableValueByVariableId(Guid languageId, Guid RecordId, List <string> variableIDs, string variableID)
        {
            List <Record_Variable> recordVariables = new List <Record_Variable>();
            var cacheProvider = CacheFactory.Get();

            if (!cacheProvider.Exists(CacheKeys.CACHE_RECORD_VARIABLES))
            {
                using (var context = new TSMContext())
                {
                    recordVariables = context.Record_Variables.ToList();
                }
                cacheProvider.Add <List <Record_Variable> >(recordVariables, CacheKeys.CACHE_RECORD_VARIABLES, SiteConstants.CacheDuration);
            }
            else
            {
                recordVariables = cacheProvider.Get <List <Record_Variable> >(CacheKeys.CACHE_RECORD_VARIABLES);
            }


            // var variable = recordVariables.Where(rv => variableIDs.Contains(rv.VariableID.ToString()) && rv.RecordID == RecordId && rv.LanguageID == languageId).Select(v => v.Value).ToList();
            var variable = recordVariables.Where(rv => rv.VariableID.ToString() == variableID && rv.RecordID == RecordId && rv.LanguageID == languageId).Select(v => v.Value.ToString()).ToList();

            Guid   RegID           = new Guid(AppSettingsUtility.GetString(AppSettingsKeys.Regional));
            string DownloadITCOnly = AppSettingsUtility.GetString(AppSettingsKeys.isDownload);

            string RegionalID    = RegID.ToString();
            string variableValue = "";
            string val           = "";

            if (variable.Count > 0)
            {
                if ((RegionalID != string.Empty) && (variableID == RegionalID))
                {
                    if (variable[0] == "0")
                    {
                        val           = "false";
                        variableValue = val;
                    }
                    else if (variable[0] == "1")
                    {
                        val           = "true";
                        variableValue = val;
                    }
                    else
                    {
                        variableValue = string.Join(",", variable);
                    }
                }
                else if ((DownloadITCOnly != string.Empty) && (variableID == DownloadITCOnly))
                {
                    if (variable[0] == "")
                    {
                        variableValue = "true";
                    }
                    else
                    {
                        variableValue = string.Join(",", variable);
                    }
                }
                else
                {
                    variableValue = string.Join(",", variable);
                }
            }
            else
            {
                variableValue = string.Join(",", variable);
            }

            return(variableValue);
        }