示例#1
0
文件: XStorage.cs 项目: fkdl/xcore
 /// <summary>
 /// FormAPI参数
 /// </summary>
 /// <param name="expire">过期时间(单位:秒)</param>
 /// <param name="max">文件最大大小</param>
 /// <returns></returns>
 public static String FormApi(int expire = 5400, int max = 200)
 {
     if (Using)
     {
         max = max * 1024 * 1024;
         var dir       = DateTools.Format("yyyyMM/MMdd/");
         var json      = "{\"expiration\":\"" + DateTime.UtcNow.AddSeconds(expire).ToString("yyyy-MM-ddTHH:mm:ssZ") + "\",\"conditions\":[[\"content-length-range\", 0, " + max + "],[\"starts-with\",\"$key\",\"" + dir + "\"]]}";
         var policy    = Encryptor.Base64Encrypt(json);
         var signature = System.Convert.ToBase64String(Encryptor.GetHMACSHA1(policy, ossaccesskeySecret));
         var host      = ossdomain.IndexOf("://") < 0 ? "//" + ossdomain : ossdomain;
         return(Json.ToString(new { host = string.IsNullOrEmpty(XStorageUrl) ? host : XStorageUrl, ossdomain = host, ossaccesskeyid, dir, policy, signature }));
     }
     return("");
 }
        public static IQueryExpression FilterByDateRange(this IQueryExpression expression, string fieldName, DateTime startDate, DateTime endDate, bool includeEmptyField = false)
        {
            var strStartDate = DateTools.DateToString(startDate, DateTools.Resolution.SECOND);
            var strEndDate   = DateTools.DateToString(endDate, DateTools.Resolution.SECOND);
            var rangeQuery   = new RangeQuery(strStartDate, strEndDate, fieldName, true);

            if (includeEmptyField)
            {
                var groupQuery = new GroupQuery(LuceneOperator.NOT);
                groupQuery.QueryExpressions.Add(new AllQuery());
                groupQuery.QueryExpressions.Add(new FieldQuery(fieldName, @"[* TO *]"));
                return(expression.And(rangeQuery.Or(groupQuery)));
            }
            return(expression.And(rangeQuery));
        }
示例#3
0
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="T:Raven.Imports.Newtonsoft.Json.JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var input = reader.Value as string;

            if (input != null && luceneDateTimePattern.IsMatch(input))
            {
                var stringToDate = DateTools.StringToDate(input);
                if (objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?))
                {
                    return(new DateTimeOffset(stringToDate, DateTimeOffset.Now.Offset));
                }
                return(DateTime.SpecifyKind(stringToDate, DateTimeKind.Local));
            }
            return(reader.Value);
        }
        protected override NewsPost ConvertTo(Document doc)
        {
            NewsPost newsPost = new NewsPost();

            newsPost.Id              = Convert.ToInt32(doc.Get("Id"));
            newsPost.Name            = doc.Get("Name");
            newsPost.Description     = doc.Get("Description");
            newsPost.ImageId         = Convert.ToInt32(doc.Get("ImageId"));
            newsPost.AuthorId        = Convert.ToInt32(doc.Get("AuthorId"));
            newsPost.IsVisible       = Convert.ToBoolean(doc.Get("IsVisible"));
            newsPost.PublicationDate = DateTools.StringToDate(doc.Get("PublicationDate"));
            newsPost.EditDate        = DateTools.StringToDate(doc.Get("EditDate"));
            newsPost.CreatedDate     = DateTools.StringToDate(doc.Get("CreatedDate"));
            return(newsPost);
        }
示例#5
0
 public Object StringToObject(String stringValue)
 {
     if (StringHelper.IsEmpty(stringValue))
     {
         return(null);
     }
     try
     {
         return(DateTools.StringToDate(stringValue));
     }
     catch (Exception e)
     {
         throw new HibernateException("Unable to parse into date: " + stringValue, e);
     }
 }
示例#6
0
 private static LuceneSearchModel _mapLuceneDocumentToData(Document doc, float score = 0)
 {
     return(new LuceneSearchModel
     {
         Id = Guid.Parse(doc.Get(AppConstants.LucId)),
         TopicName = doc.Get(AppConstants.LucTopicName),
         PostContent = doc.Get(AppConstants.LucPostContent),
         DateCreated = DateTools.StringToDate(doc.Get(AppConstants.LucDateCreated)),
         TopicId = Guid.Parse(doc.Get(AppConstants.LucTopicId)),
         UserId = Guid.Parse(doc.Get(AppConstants.LucUserId)),
         Username = doc.Get(AppConstants.LucUsername),
         TopicUrl = doc.Get(AppConstants.LucTopicUrl),
         Score = score
     });
 }
示例#7
0
        public virtual void TestRound()
        {
            // we use default locale since LuceneTestCase randomizes it
            //Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"), Locale.Default);
            //cal.clear();
            DateTime cal = new DateTime(2004, 2, 3, 22, 8, 56, 333, new GregorianCalendar()); // hour, minute, second -  year=2004, month=february(!), day=3
            //cal.set(DateTime.MILLISECOND, 333);
            DateTime date = cal;

            Assert.AreEqual("2004-02-03 22:08:56:333", IsoFormat(date));

            DateTime dateYear = DateTools.Round(date, DateTools.Resolution.YEAR);

            Assert.AreEqual("2004-01-01 00:00:00:000", IsoFormat(dateYear));

            DateTime dateMonth = DateTools.Round(date, DateTools.Resolution.MONTH);

            Assert.AreEqual("2004-02-01 00:00:00:000", IsoFormat(dateMonth));

            DateTime dateDay = DateTools.Round(date, DateTools.Resolution.DAY);

            Assert.AreEqual("2004-02-03 00:00:00:000", IsoFormat(dateDay));

            DateTime dateHour = DateTools.Round(date, DateTools.Resolution.HOUR);

            Assert.AreEqual("2004-02-03 22:00:00:000", IsoFormat(dateHour));

            DateTime dateMinute = DateTools.Round(date, DateTools.Resolution.MINUTE);

            Assert.AreEqual("2004-02-03 22:08:00:000", IsoFormat(dateMinute));

            DateTime dateSecond = DateTools.Round(date, DateTools.Resolution.SECOND);

            Assert.AreEqual("2004-02-03 22:08:56:000", IsoFormat(dateSecond));

            DateTime dateMillisecond = DateTools.Round(date, DateTools.Resolution.MILLISECOND);

            Assert.AreEqual("2004-02-03 22:08:56:333", IsoFormat(dateMillisecond));

            // long parameter:
            long dateYearLong = DateTools.Round(date.Ticks / TimeSpan.TicksPerMillisecond, DateTools.Resolution.YEAR);

            Assert.AreEqual("2004-01-01 00:00:00:000", IsoFormat(new DateTime(dateYearLong)));

            long dateMillisecondLong = DateTools.Round(date.Ticks / TimeSpan.TicksPerMillisecond, DateTools.Resolution.MILLISECOND);

            Assert.AreEqual("2004-02-03 22:08:56:333", IsoFormat(new DateTime(dateMillisecondLong)));
        }
示例#8
0
文件: KeyValue.cs 项目: g82tt/xcore
        public static void Edit(string key, string value, string description)
        {
            if (GetByKey(key) != null)
            {
                XmlParamter xpKey = new XmlParamter("Key", key);
                xpKey.Direction = System.IO.ParameterDirection.Equal;
                XmlParamter xpValue = new XmlParamter("Value", value);
                xpValue.Direction = System.IO.ParameterDirection.Update;
                XmlParamter xpDescription = new XmlParamter("Description", description);
                xpDescription.Direction = System.IO.ParameterDirection.Update;
                XmlParamter xpUpdateTime = new XmlParamter("UpdateTime", DateTools.GetNow().ToString("yyyy-MM-dd HH:mm:ss"));
                xpUpdateTime.Direction = System.IO.ParameterDirection.Update;

                XMLHelper.UpdateData(path, "KeyValue", xpKey, xpValue, xpDescription, xpUpdateTime);
            }
        }
        public void TestDifferenceInMonths()
        {
            Assert.AreEqual(0, DateTools.DifferenceInMonths(new DateTime(2018, 1, 15), new DateTime(2018, 1, 7)));
            Assert.AreEqual(0, DateTools.DifferenceInMonths(new DateTime(2018, 2, 1), new DateTime(2018, 1, 7)));
            Assert.AreEqual(0, DateTools.DifferenceInMonths(new DateTime(2018, 2, 6), new DateTime(2018, 1, 7)));
            Assert.AreEqual(1, DateTools.DifferenceInMonths(new DateTime(2018, 2, 7), new DateTime(2018, 1, 7)));
            Assert.AreEqual(1, DateTools.DifferenceInMonths(new DateTime(2018, 2, 8), new DateTime(2018, 1, 7)));
            Assert.AreEqual(1, DateTools.DifferenceInMonths(new DateTime(2018, 3, 1), new DateTime(2018, 1, 7)));
            Assert.AreEqual(-1, DateTools.DifferenceInMonths(new DateTime(2018, 1, 7), new DateTime(2018, 3, 1)));

            Assert.AreEqual(0, DateTools.DifferenceInMonths(new DateTime(2018, 1, 1), new DateTime(2017, 12, 7)));
            Assert.AreEqual(0, DateTools.DifferenceInMonths(new DateTime(2018, 1, 6), new DateTime(2017, 12, 7)));
            Assert.AreEqual(1, DateTools.DifferenceInMonths(new DateTime(2018, 1, 7), new DateTime(2017, 12, 7)));
            Assert.AreEqual(1, DateTools.DifferenceInMonths(new DateTime(2018, 1, 8), new DateTime(2017, 12, 7)));
            Assert.AreEqual(-1, DateTools.DifferenceInMonths(new DateTime(2017, 12, 7), new DateTime(2018, 1, 8)));
        }
示例#10
0
 /// <summary>
 /// 写入日志
 /// </summary>
 /// <param name="msg"></param>
 public static void Write(LogMessage msg)
 {
     try
     {
         var fi = new System.IO.FileInfo(IO.PathTool.Map(XCore.LogPath, DateTools.FormatDate(), msg.LogLevel + ".log"));
         if (!fi.Directory.Exists)
         {
             fi.Directory.Create();
         }
         var fs = fi.Exists ? fi.AppendText() : fi.CreateText();
         fs.WriteLine(string.Format("{0} {1} - {2}", DateTools.Format(msg.LogTime), msg.LogLevel, msg.Message));
         fs.Flush();
         fs.Dispose();
     }
     catch { }
 }
示例#11
0
        /// <summary>
        /// Processes a json-object.
        /// </summary>
        /// <param name="logEvent">Log event data.</param>
        private void ProcessObject(LogEventData logEvent)
        {
            var doc = new Document();

            doc.Add(new Field("Timestamp", DateTools.DateToString(logEvent.Timestamp, DateTools.Resolution.MILLISECOND),
                              Field.Store.NO, Field.Index.ANALYZED));
            doc.Add(new Field("Level", logEvent.Level.ToString(), Field.Store.NO, Field.Index.ANALYZED));
            doc.Add(new Field("Message", logEvent.Message, Field.Store.NO, Field.Index.ANALYZED));

            ProcessException(logEvent.Exception, doc);
            ProcessProperties(logEvent.Properties, doc);

            doc.Add(new Field("Raw", JsonConvert.SerializeObject(logEvent), Field.Store.YES, Field.Index.NO));

            Context.ActorSelection(ActorPaths.Indexer.Path).Tell(doc);
        }
示例#12
0
        protected virtual SearchEngineResult CreateSearchResult(Document doc, float score)
        {
            var result = new SearchEngineResult
            {
                BlogName    = doc.Get(BlogName),
                EntryId     = NumericUtils.PrefixCodedToInt(doc.Get(Entryid)),
                PublishDate = DateTools.StringToDate(doc.Get(Pubdate)),
                Title       = doc.Get(Title),
                Score       = score
            };
            string entryName = doc.Get(EntryName);

            result.EntryName = !String.IsNullOrEmpty(entryName) ? entryName : null;

            return(result);
        }
示例#13
0
        private void SetDocumentValue(IDictionary <string, object> values)
        {
            EnsureDocument();
            foreach (var kvp in values)
            {
                var f = document.GetFieldable(kvp.Key);
                if (f != null)
                {
                    if (kvp.Value == null)
                    {
                        ((LN.Documents.Field)f).SetValue(string.Empty);
                    }
                    else
                    {
                        Field p = DocumentBuilder.GetField(TypeName, kvp.Key);
                        switch (p.FieldType)
                        {
                        case FieldType.Int:
                            ((NumericField)f).SetIntValue((int)kvp.Value);
                            break;

                        case FieldType.Long:
                            ((NumericField)f).SetLongValue((long)kvp.Value);
                            break;

                        case FieldType.Float:
                            ((NumericField)f).SetFloatValue((float)kvp.Value);
                            break;

                        case FieldType.Double:
                            ((NumericField)f).SetDoubleValue((double)kvp.Value);
                            break;

                        case FieldType.DateTime:
                            ((LN.Documents.Field)f).SetValue(DateTools.DateToString((DateTime)kvp.Value, DateTools.Resolution.MILLISECOND));
                            break;

                        case FieldType.String:
                        default:
                            ((LN.Documents.Field)f).SetValue(kvp.Value.ToString());
                            break;
                        }
                    }
                }
            }
        }
        public void TestWithinMonths()
        {
            Assert.IsTrue(DateTools.WithinMonths(new DateTime(2018, 1, 15), new DateTime(2018, 1, 7), 1));
            Assert.IsTrue(DateTools.WithinMonths(new DateTime(2018, 2, 1), new DateTime(2018, 1, 7), 1));
            Assert.IsTrue(DateTools.WithinMonths(new DateTime(2018, 2, 6), new DateTime(2018, 1, 7), 1));
            Assert.IsFalse(DateTools.WithinMonths(new DateTime(2018, 2, 6), new DateTime(2018, 1, 7), 0));
            Assert.IsTrue(DateTools.WithinMonths(new DateTime(2018, 2, 7), new DateTime(2018, 1, 7), 2));
            Assert.IsTrue(DateTools.WithinMonths(new DateTime(2018, 2, 8), new DateTime(2018, 1, 7), 2));
            Assert.IsTrue(DateTools.WithinMonths(new DateTime(2018, 3, 1), new DateTime(2018, 1, 7), 2));
            Assert.IsFalse(DateTools.WithinMonths(new DateTime(2018, 3, 1), new DateTime(2018, 1, 7), 1));

            Assert.IsTrue(DateTools.WithinMonths(new DateTime(2018, 1, 1), new DateTime(2017, 12, 7), 1));
            Assert.IsTrue(DateTools.WithinMonths(new DateTime(2017, 12, 7), new DateTime(2018, 1, 1), 1));
            Assert.IsTrue(DateTools.WithinMonths(new DateTime(2018, 1, 6), new DateTime(2017, 12, 7), 1));
            Assert.IsTrue(DateTools.WithinMonths(new DateTime(2018, 1, 7), new DateTime(2017, 12, 7), 2));
            Assert.IsTrue(DateTools.WithinMonths(new DateTime(2018, 1, 8), new DateTime(2017, 12, 7), 2));
        }
示例#15
0
        } // doIndex

        private static void removeAllDuplicateAndDeletedFiles(IndexableFileInfo[] fileInfos, string LuceneIndexDir, IndexCreationMode indexCreationMode)
        {
            if (indexCreationMode != IndexCreationMode.AppendToExistingIndex)
            {
                return;
            }

            IndexReader reader = IndexReader.Open(LuceneIndexDir);

            try
            {
                int numDocs = reader.NumDocs();
                for (int i = 0; i < numDocs; i++)
                {
                    Document docToCheck         = reader.Document(i);
                    bool     removeDocFromIndex = true;
                    string   filenameField      = docToCheck.GetField("filename").StringValue();
                    string   lastModified       = (docToCheck.GetField("LastModified").StringValue());

                    foreach (IndexableFileInfo fi in fileInfos)
                    {
                        if (String.Compare(fi.Filename, filenameField, true) == 0 && DateTools.DateToString(fi.LastModified, DateTools.Resolution.SECOND) == lastModified)
                        {
                            removeDocFromIndex = false;
                            break;
                        }
                    } // foreach

                    if (removeDocFromIndex)
                    {
                        reader.DeleteDocument(i);
                        if (!reader.HasDeletions())
                        {
                            throw new Exception("error: deletion failed!!");
                        }
                    }
                } // for each lucene doc
            }
            finally
            {
                reader.Close();
            }
            LuceneIndexer indexer = new LuceneIndexer(LuceneIndexDir, indexCreationMode); // open up the index again

            indexer.CloseIndexWriter(OptimizeMode.DoOptimization);                        // just to optimize the index (which removes deleted items).
        }
示例#16
0
        /// <summary>
        /// Searches for data sorted by date.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="queryString">The query string.</param>
        /// <returns>Search result wrapper.</returns>
        public SearchResult SearchByDate(IUnitOfWork session, string queryString)
        {
            SearchContext searchContext = session.UnitOfWorkContext as SearchContext;

            if (searchContext == null)
            {
                throw new Exception("SearchContext not part of IUnitOfWork!");
            }
            var queryParser = searchContext.GetQueryParser(new[] { "Text", "Title", "User" });
            var query       = queryParser.Parse(queryString);

            Filter filter = RangeFilter.Less("Published", DateTools.DateToString(DateTime.Now.AddSeconds(1), DateTools.Resolution.SECOND));

            var topDocs = searchContext.IndexSearcher.Search(query, filter, MaximalSearchDepth, new Sort("Date", true));

            return(new SearchResult(topDocs, searchContext.IndexSearcher));
        }
示例#17
0
        private Document CreateDocument(string text, long time)
        {
            Document document = new Document();

            // Add the text field.
            Field textField = NewTextField(TEXT_FIELD, text, Field.Store.YES);

            document.Add(textField);

            // Add the date/time field.
            string dateTimeString = DateTools.TimeToString(time, DateResolution.SECOND);
            Field  dateTimeField  = NewStringField(DATE_TIME_FIELD, dateTimeString, Field.Store.YES);

            document.Add(dateTimeField);

            return(document);
        }
示例#18
0
        /// <summary>
        /// Converts the list item to document.
        /// </summary>
        /// <param name="listItem">The list item.</param>
        /// <returns>Document.</returns>
        public static Document ConvertListItemToDocument(SPListItem listItem)
        {
            var tokenDictionary = new Dictionary <string, AbstractField>();

            foreach (var field in listItem.Fields.OfType <SPField>().Where(f => f.Hidden == false))
            {
                switch (field.Type)
                {
                case SPFieldType.DateTime:
                    var dateString = DateTools.DateToString((DateTime)listItem[field.Id], DateTools.Resolution.MILLISECOND);
                    var dateField  = new Field(field.Title, dateString, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES);

                    tokenDictionary.Add(field.Title, dateField);
                    break;

                case SPFieldType.Integer:
                    var intField = new NumericField(field.Title, Field.Store.YES, true);
                    intField.SetIntValue((int)listItem[field.Id]);
                    tokenDictionary.Add(field.Title, intField);
                    break;

                case SPFieldType.Number:
                    var numberField = new NumericField(field.Title, Field.Store.YES, true);
                    numberField.SetFloatValue(Convert.ToSingle(listItem[field.Id]));
                    tokenDictionary.Add(field.Title, numberField);
                    break;

                default:
                    var textValue   = field.GetFieldValueAsText(listItem[field.Id]);
                    var stringField = new Field(field.Title, textValue, Field.Store.YES, Field.Index.ANALYZED,
                                                Field.TermVector.WITH_POSITIONS_OFFSETS);
                    tokenDictionary.Add(field.Title, stringField);
                    break;
                }
            }

            var doc = new Document();

            //Add individual fields.
            foreach (var kvp in tokenDictionary)
            {
                doc.Add(kvp.Value);
            }

            return(doc);
        }
示例#19
0
        /// <summary>
        /// 将索引文档转换为产品
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public static Product ConvertDocumentToProduct(Document doc)
        {
            Product product = new Product();

            product.ProductID       = Convert.ToInt32(doc.Get(ProductIndexField.ProductID));
            product.ProductName     = doc.Get(ProductIndexField.ProductName);
            product.BrandID         = Convert.ToInt32(doc.Get(ProductIndexField.BrandID));
            product.ProductContent  = doc.Get(ProductIndexField.ProductContent);
            product.ProductAbstract = doc.Get(ProductIndexField.ProductAbstract);
            product.CreateTime      = DateTools.StringToDate(doc.Get(ProductIndexField.DateCreated));
            string[] tagNames = doc.GetValues(ProductIndexField.ProductKeywords);
            if (tagNames != null && tagNames.Length > 0)
            {
                product.ProductKeywords = string.Join(";", tagNames);
            }
            return(product);
        }
            private DateTime ParseDateTimeValue(string val)
            {
                if (LoadedFromExamine)
                {
                    try
                    {
                        //we might need to parse the date time using Lucene converters
                        return(DateTools.StringToDate(val));
                    }
                    catch (FormatException)
                    {
                        //swallow exception, its not formatted correctly so revert to just trying to parse
                    }
                }

                return(DateTime.Parse(val));
            }
示例#21
0
        /// <summary>
        /// BlogThread转换成<see cref="Lucene.Net.Documents.Document"/>
        /// </summary>
        /// <param name="blogThread">日志实体</param>
        /// <returns>Lucene.Net.Documents.Document</returns>
        public static Document Convert(BlogThread blogThread)
        {
            Document doc = new Document();

            //索引日志基本信息
            doc.Add(new Field(BlogIndexDocument.ThreadId, blogThread.ThreadId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field(BlogIndexDocument.TenantTypeId, blogThread.TenantTypeId, Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field(BlogIndexDocument.OwnerId, blogThread.OwnerId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field(BlogIndexDocument.IsEssential, blogThread.IsEssential ? "1" : "0", Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field(BlogIndexDocument.Keywords, blogThread.Keywords ?? "", Field.Store.NO, Field.Index.ANALYZED));
            doc.Add(new Field(BlogIndexDocument.Summary, blogThread.Summary ?? "", Field.Store.NO, Field.Index.ANALYZED));
            doc.Add(new Field(BlogIndexDocument.UserId, blogThread.UserId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field(BlogIndexDocument.Subject, blogThread.Subject.ToLower(), Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field(BlogIndexDocument.Body, HtmlUtility.TrimHtml(blogThread.GetBody(), 0).ToLower(), Field.Store.NO, Field.Index.ANALYZED));
            doc.Add(new Field(BlogIndexDocument.Author, blogThread.Author, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field(BlogIndexDocument.DateCreated, DateTools.DateToString(blogThread.DateCreated, DateTools.Resolution.DAY), Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field(BlogIndexDocument.AuditStatus, ((int)blogThread.AuditStatus).ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field(BlogIndexDocument.PrivacyStatus, ((int)blogThread.PrivacyStatus).ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));

            //索引日志tag
            foreach (string tagName in blogThread.TagNames)
            {
                doc.Add(new Field(BlogIndexDocument.Tag, tagName.ToLower(), Field.Store.YES, Field.Index.ANALYZED));
            }

            //索引日志用户分类名称
            IEnumerable <string> ownerCategoryNames = blogThread.OwnerCategoryNames;

            if (ownerCategoryNames != null)
            {
                foreach (string ownerCategoryName in ownerCategoryNames)
                {
                    doc.Add(new Field(BlogIndexDocument.OwnerCategoryName, ownerCategoryName.ToLower(), Field.Store.YES, Field.Index.ANALYZED));
                }
            }

            //索引日志站点分类ID
            long?siteCategoryId = blogThread.SiteCategoryId;

            if (siteCategoryId.HasValue)
            {
                doc.Add(new Field(BlogIndexDocument.SiteCategoryId, siteCategoryId.Value.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            }

            return(doc);
        }
示例#22
0
        public virtual void TestStringtoTime()
        {
            long time = DateTools.StringToTime("197001010000");

            // we use default locale since LuceneTestCase randomizes it
            //Calendar cal = new GregorianCalendar(TimeZone.GetTimeZone("GMT"), Locale.Default);
            //cal.Clear();

            DateTime cal = new DateTime(1970, 1, 1, 0, 0, 0, 0, new GregorianCalendar()); // hour, minute, second -  year=1970, month=january, day=1

            //cal.set(DateTime.MILLISECOND, 0);
            Assert.AreEqual(cal.Ticks, time);

            cal = new DateTime(1980, 2, 2, 11, 5, 0, 0, new GregorianCalendar()); // hour, minute, second -  year=1980, month=february, day=2
            //cal.set(DateTime.MILLISECOND, 0);
            time = DateTools.StringToTime("198002021105");
            Assert.AreEqual(cal.Ticks, time);
        }
示例#23
0
        public bool AllDatesAreWithinRange(string minDateStr, string maxDateStr)
        {
            //input dates are in the form YYYY-MM-DD
            DateTime minDate = DateTools.DateParser(minDateStr);
            DateTime maxDate = DateTools.DateParser(maxDateStr);

            foreach (List <string> dataItem in dto.LatestCAD.data)
            {
                //resp date format YYYY-MMM-DD where MMM is the month name abbreviation
                DateTime respDate = DateTools.DateParser(dataItem[3].Substring(0, 11));

                if (respDate < minDate || respDate > maxDate)
                {
                    return(false);
                }
            }
            return(true);
        }
        /// <summary>
        /// Helper to convert from a string value stored in Lucene to a DateTime?
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        internal static DateTime?LuceneStringToDate(this string value)
        {
            DateTime?date = null;

            if (!string.IsNullOrWhiteSpace(value))
            {
                try
                {
                    date = DateTools.StringToDate(value);
                }
                catch
                {
                    LogHelper.Info(typeof(DateTimeExtensions), $"Unable to convert string '{value}' into a DateTime");
                }
            }

            return(date);
        }
示例#25
0
 private CardCriterion _mapLuceneDocumentToData(Document doc) //mapHitToDataModel
 {
     return(new CardCriterion
            //by creating a new Modelobject from scratch, fields dateMin and Max are setted up to default
     {
         EditionId = Convert.ToUInt32(doc.Get("EditionId")),
         CardId = Convert.ToUInt32(doc.Get("CardId")),
         Territory = doc.Get("Territory"),
         CardKind = doc.Get("CardKind"),
         CardName = doc.Get("CardName").Trim(),
         CardEdition = doc.Get("CardEdition").Trim(),
         FileExt = doc.Get("FileExt"),
         CardAdoptionKindSubject = doc.Get("CardAdoptionKindSubject"),
         CardAdoptionSubject = doc.Get("CardAdoptionSubject"),
         CardAdoptionDate = DateTools.StringToDate(doc.Get("CardAdoptionDate")),
         CardAdoptionNumber = doc.Get("CardAdoptionNumber"),
     });
 }
        public async Task <ActionResult <Notes> > GetLatestNotes()
        {
            var notes = await _context.Notes
                        .Include(n => n.Message)
                        .Where(n => EF.Functions.DateDiffDay(
                                   DateTools.GetNominalDateForDayOfWeek(
                                       DayOfWeek.Sunday),
                                   n.Message.Date) % 7 == 0)
                        .OrderByDescending(n => n.Message.Date)
                        .FirstOrDefaultAsync();

            if (notes == null)
            {
                return(NotFound());
            }

            return(notes);
        }
        protected override FrameworkElement GenerateDayHeader(DayOfWeek dayOfWeek)
        {
            Grid grid = new Grid()
            {
                Background = CalendarView.GridDayHeaderBackground,
                Margin     = new Thickness(1.5, 0, 1.5, 1.5)
            };

            grid.Children.Add(new TextBlock()
            {
                Text       = DateTools.ToLocalizedString(dayOfWeek),
                Foreground = CalendarView.GridDayHeaderForeground,
                Margin     = new Thickness(14, 2, 14, 2),
                FontSize   = 16
            });

            return(grid);
        }
        public async Task <ActionResult <Audio> > GetLatestAudio()
        {
            var audio = await _context.Audio
                        .Include(a => a.Message)
                        .Where(a => EF.Functions.DateDiffDay(
                                   DateTools.GetNominalDateForDayOfWeek(
                                       DayOfWeek.Sunday),
                                   a.Message.Date) % 7 == 0)
                        .OrderByDescending(a => a.Message.Date)
                        .FirstOrDefaultAsync();

            if (audio == null)
            {
                return(NotFound());
            }

            return(audio);
        }
示例#29
0
 public static LineViewModel Get(ILuceneSearcher luceneSearcher, Document document)
 {
     return(new LineViewModel
     {
         MonitorId = document.Get(LogField.MONITOR_ID),
         GroupDepth = Int32.Parse(document.Get(LogField.GROUP_DEPTH)),
         PreviousEntryType = document.Get(LogField.PREVIOUS_ENTRY_TYPE),
         PreviousLogTime = DateTools.StringToDate(document.Get(LogField.PREVIOUS_LOG_TIME)).ToString("dd/MM/yyyy HH:mm:ss.fff"),
         LogLevel = document.Get(LogField.LOG_LEVEL),
         Text = document.Get(LogField.TEXT),
         Tags = document.Get(LogField.TAGS),
         SourceFileName = document.Get(LogField.SOURCE_FILE_NAME),
         LineNumber = document.Get(LogField.LINE_NUMBER),
         LogTime = DateTools.StringToDate(document.Get(LogField.LOG_TIME)).ToString("dd/MM/yyyy HH:mm:ss.fff"),
         Exception = ExceptionViewModel.Get(luceneSearcher, document),
         AppName = document.Get(LogField.APP_NAME)
     });
 }
示例#30
0
        /// <summary>
        /// Doesn't do any saving or setting of any other dependent properties
        /// </summary>
        /// <param name="startsOn"></param>
        /// <param name="currentWeek"></param>
        public bool SetWeekSimple(DayOfWeek startsOn, Schedule.Week currentWeek)
        {
            DateTime today = DateTime.SpecifyKind(DateTime.Today, DateTimeKind.Utc);

            if (currentWeek == Schedule.Week.WeekTwo)
            {
                today = today.AddDays(-7);
            }

            DateTime answer = DateTools.Last(startsOn, today);

            if (answer != WeekOneStartsOn)
            {
                WeekOneStartsOn = answer;
                return(true);
            }

            return(false);
        }