Example #1
0
 /// <summary>
 /// Writes an Entry in the Log.
 /// </summary>
 /// <param name="message">The Message.</param>
 /// <param name="type">The Type of the Entry.</param>
 /// <param name="user">The User that generated the Entry.</param>
 public static void LogEntry(string message, EntryType type, string user)
 {
     try {
         Settings.Provider.LogEntry(message, type, user);
     }
     catch { }
 }
        private decimal GetSum(ISession session, Guid accountId, DateTime date, EntryType entryType)
        {
            // TODO : try to get the lamda version working
            // currently gives this error: "could not resolve property" regarding Transaction.Date

            //return session.QueryOver<Entry>().Where(x =>
            //    (x.Account.Id == accountId) &&
            //    (x.Transaction.Date <= date) &&
            //    (x.Type == entryType))
            //    .List()
            //    .Sum(x => x.Amount);

            var entries = session.CreateCriteria<Entry>()
                .Add(Expression.Eq("Type", entryType))
                .Add(Expression.Eq("Account.Id", accountId))
                .CreateCriteria("Transaction")
                    .Add(Expression.Eq("Deleted", false))
                    .Add(Expression.Le("Date", date))
                    .List();

            decimal sum = 0;
            foreach (Entry entry in entries)
            {
                sum += entry.Amount;
            }
            return sum;
        }
Example #3
0
 public static string EntryTypeToString(EntryType tp)
 {
     switch (tp)
     {
         case EntryType.Nickname:
             return "nickname";
         case EntryType.ScreenName:
             return "screen_name";
         case EntryType.Sex:
             return "sex";
         case EntryType.City:
             return "city";
         case EntryType.Country:
             return "country";
         case EntryType.Timezone:
             return "timezone";
         case EntryType.Photo:
             return "photo";
         case EntryType.PhotoMedium:
             return "photo_medium";
         case EntryType.HasMobile:
             return "has_mobile";
         case EntryType.Rate:
             return "rate";
         case EntryType.Contacts:
             return "contacts";
         case EntryType.Education:
             return "education";
         case EntryType.Online:
             return "online";
         default:
             return String.Format("{0}", tp);
     }
 }
Example #4
0
		private XElement CreateUrlElement(EntryType entryType, object id) {
			
			return new XElement(XName.Get("url", ns_sitemap),
				 new XElement(XName.Get("loc", ns_sitemap), GenerateEntryUrl(entryType, id))
			);

		}
Example #5
0
        public ActionResult Index(string filter, EntryType searchType = EntryType.Undefined, bool allowRedirect = true,
            string tag = null,
            string sort = null,
            int? artistId = null,
            ArtistType? artistType = null,
            DiscType? discType = null,
            SongType? songType = null,
            bool? onlyWithPVs = null
            )
        {
            filter = !string.IsNullOrEmpty(filter) ? filter.Trim() : string.Empty;

            if (allowRedirect && !string.IsNullOrEmpty(filter)) {

                var redirectResult = TryRedirect(filter, searchType);

                if (redirectResult != null)
                    return redirectResult;

            }

            ViewBag.Query = filter;
            ViewBag.SearchType = searchType != EntryType.Undefined ? searchType.ToString() : "Anything";
            ViewBag.Tag = tag;
            ViewBag.Sort = sort;
            ViewBag.ArtistId = artistId;
            ViewBag.ArtistType = artistType;
            ViewBag.DiscType = discType;
            ViewBag.SongType = songType;
            ViewBag.OnlyWithPVs = onlyWithPVs;

            SetSearchEntryType(searchType);
            return View();
        }
Example #6
0
 public GlobalSearchBoxModel(EntryType? objectType, string searchTerm)
 {
     AllObjectTypes = new TranslateableEnum<EntryType>(() => global::Resources.EntryTypeNames.ResourceManager, new[] {
         EntryType.Undefined, EntryType.Artist, EntryType.Album, EntryType.Song, EntryType.Tag, EntryType.User
     });
     ObjectType = objectType ?? EntryType.Artist;
     GlobalSearchTerm = searchTerm ?? string.Empty;
 }
Example #7
0
			public Entry(Entry other)
			{
				this.type = other.type;
				this.typeName = other.typeName;
				this.memberName = other.memberName;
				this.summary = other.summary;
				this.remarks = other.remarks;
			}
Example #8
0
 private void populateFromResultTable(Hashtable table)
 {
     this.id = Convert.ToInt16(table["id"]);
     this.entrytype = (EntryType)Convert.ToInt16(table["type"]);
     this.datetime = DateTime.Parse(table["datetime"].ToString());
     this.debit = table["debit"].ToString().Equals("") ? 0.00 : Convert.ToDouble(table["debit"]);
     this.credit = table["credit"].ToString().Equals("") ? 0.00 : Convert.ToDouble(table["credit"]);
 }
 public EntryForPictureDisplayContract(EntryType entryType, int entryId, string name, int version, PictureContract pictureContract)
 {
     EntryType = entryType;
     EntryId = entryId;
     Name = name;
     Version = version;
     Picture = pictureContract;
 }
Example #10
0
		private EntryForApiContract AssertHasEntry(PartialFindResult<EntryForApiContract> result, string name, EntryType entryType) {
			
			var entry = result.Items.FirstOrDefault(a => string.Equals(a.DefaultName, name, StringComparison.InvariantCultureIgnoreCase)
				&& a.EntryType == entryType);

			Assert.IsNotNull(entry, "Entry found");
			return entry;

		}
Example #11
0
 public MenuEntry(MenuScreen nMenu, EntryType nType, string nText, List<object> nValues, int nDefaultIndex, OptionEntrySelected nCallback)
 {
     mName = nText;
     mType = nType;
     mMenu = nMenu;
     mValues = nValues;
     mCallback = nCallback;
     mSelectedIndex = nDefaultIndex;
 }
Example #12
0
 public BootMenuItem(string n, string d, EntryType t, string ison = "", bool st = true, string code = "")
 {
     Name = n;
     Description = d;
     Type = t;
     Start = st;
     IsoName = Path.GetFileName(ison);
     CustomCode = code;
 }
 /// <summary>
 /// Constructs a new menu entry with the specified text.
 /// </summary>
 public MenuEntry(MenuScreen menu, string text, EntryType type, GameScreen screen)
 {
     _text = text;
     _screen = screen;
     _type = type;
     _menu = menu;
     _scale = 0.9f;
     _alpha = 1.0f;
 }
        private Entry GetEntry(DateTime date, decimal amount, Account account, EntryType entryType = EntryType.Debit)
        {
            var transaction = new IncomeTransaction { Date = date };
            var entry = new Entry { Amount = amount, Account = account, Transaction = transaction, Type = entryType };
            transaction.Entries.Add(entry);

            Repository.Save(transaction);

            return entry;
        }
Example #15
0
 /// <summary>
 /// Constructs a new menu entry with the specified text.
 /// </summary>
 public MenuEntry( MenuScreen menu, string text, EntryType type, GameScreen screen, Texture2D preview )
 {
     _text = text;
     _screen = screen;
     _type = type;
     _menu = menu;
     _scale = 0.9f;
     _alpha = 1.0f;
     Preview = preview;
 }
Example #16
0
 public static String GetHerIconByType(EntryType type)
 {
     if (type == EntryType.SinaWeibo)
         return GetHerSinaWeiboIconUrl();
     else if (type == EntryType.Renren)
         return GetHerRenrenIconUrl();
     else if (type == EntryType.Douban)
         return GetHerDoubanIconUrl();
     return "";
 }
        private MemberValue(Component component, EntryType entryType,
      MemberInfo info, bool inherited)
        {
            this.component = component;
              this.entryType = entryType;
              this.info = info;

              Dummy = GetValue();
              IsInherited = inherited;
        }
        // ReSharper restore InconsistentNaming
        /// <summary>
        ///     Initializes log output base class
        /// </summary>
        /// <param name="typeOfEntriesToOutput">Desired combination of EntryType to filter items to be collected for outputting.</param>
        /// <param name="writeAllEntriesIfKeyFound">
        ///     If true and optionalKey is specified, the entire log collection is written if key is found in the collection.
        ///     If false and optionalKey is specified, only log items with the key will be written.
        /// </param>
        /// <param name="optionalKey">
        ///     Optional item keys to output or to decide whether log collection needs to be written to
        ///     output. All items are written if not specified.
        /// </param>
        protected LogOutputAspectBase(EntryType typeOfEntriesToOutput, bool writeAllEntriesIfKeyFound, IEnumerable<string> optionalKey)
        {
            this.keys = optionalKey == null ? new string[0] : optionalKey.Where(key => !key.IsBlank()).ToArray();

            if(writeAllEntriesIfKeyFound && keys.Length == 0)
                throw new ArgumentNullException("optionalKey parameter value must be specified when writeAllEntriesIfKeyFound = true.");

            this.entryTypeFilter = typeOfEntriesToOutput;
            this.writeAllEntriesIfKeyFound = writeAllEntriesIfKeyFound;
        }
 public DirectoryEntry(string name, string fullname, string ext, string size, DateTime date, string imagepath, EntryType type)
 {
     _name = name;
     _fullpath = fullname;
     _ext = ext;
     _size = size;
     _date = date;
     _imagepath = imagepath;
     _type = type;
 }
Example #20
0
 public ImageLine(string n, string fp, string d, string cat = "", string code = "",
     EntryType typ = EntryType.Nope)
 {
     Name = n;
     FilePath = fp;
     Category = cat;
     Description = d;
     CustomCode = code;
     EntryType = typ;
     SizeB = new FileInfo(fp).Length;
 }
 /// <summary>
 /// Constructs a new menu entry with the specified text.
 /// </summary>
 public MenuEntry(GameScreen owningScreen, string text, EntryType type, GameScreen linkScreen)
 {
     _text = text;
     _owningScreen = owningScreen;
     _linkScreen = linkScreen;
     _type = type;
     _scale = 0.9f;
     _alpha = 1.0f;
     _settingsChange = null;
     _optionRequiresRestart = false;
 }
        public IEntry GetJournalEntry(int entryId, EntryType entryType)
        {
            IEntry entry = null;

            using (var entities = new DietjournalEntities())
            {
                var entryCollection = GetEntryTypeEntries(entities, entryType);
                entry = entryCollection.FirstOrDefault(e => e.Id == entryId);
            }

            return entry;
        }
Example #23
0
    public static void Log(EntryType type, string message, params object[] args)
    {
        try
        {
            lock (Lock)
            {
                if (LoggingLevel == LogLevel.ErrorOnly && (type == EntryType.Information || type == EntryType.Warning))
                {
                    return;
                }

                if (args != null)
                {
                    message = string.Format(message, args);
                }
                //var entry = string.Format("{0}\t{1}\t{2}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.ffff"), type, message);
                var entry = string.Format("{0}:\t{1}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.ffff"), message);

                if (LogPath.Length <= 0) return;

                using (var sw = new StreamWriter(LogPath, true))
                {
                    sw.WriteLine(entry);
                    sw.Flush();
                }
            }
        }
        catch (ArgumentNullException ex)
        {
            try
            {
                Log(EntryType.LoggingError, ex.Message);
            }
            catch
            {
            }
        }
        catch (FormatException ex)
        {
            try
            {
                Log(EntryType.LoggingError, ex.Message);
            }
            catch
            {
            }
        }
        catch
        {
            // unable to log
        }
    }
Example #24
0
 public Entry(EntryType type, string position, string speed, string gntspeed, string ops_name, string ops_speed, string eta, char eta_app, string etd, char etd_app)
 {
     m_type = type;
     m_position = position;
     m_speed = speed;
     m_gnt_speed = gntspeed;
     m_ops_name = ops_name;
     m_ops_speed = ops_speed;
     m_eta = eta;
     m_eta_app = eta_app;
     m_etd = etd;
     m_etd_app = etd_app;
 }
Example #25
0
        public void Log(EntryType type, object data)
        {
            if (_sw == null)
                return;

            LogEntry le = new LogEntry();
            le.Data = data;
            le.Time = DateTime.Now;
            le.Type = type;
            le.Focus = Model.Default.Focus;

            _logEntries.Add(le);
            WriteToLogFile(le);
        }
Example #26
0
        /// <summary>
        /// Adds an entry to the log.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="entryType">The type.</param>
        private static void AddEntry(string message, EntryType entryType)
        {
            lock (LockObject)
            {
                var logAbsolutePath = AppDomain.CurrentDomain.BaseDirectory + LogFileRelativePath;

                var writer = File.Exists(logAbsolutePath)
                                 ? new StreamWriter(File.Open(logAbsolutePath, FileMode.Append))
                                 : new StreamWriter(File.Open(logAbsolutePath, FileMode.Create));

                writer.WriteLine(string.Format("{0:yyyy-MM-dd hh:mm:ss} {1}: {2}", DateTime.Now, entryType.ToString().ToUpper(), message));
                writer.Close();
            }
        }
Example #27
0
        public Contest(
            EntryType participationType = EntryType.Open,
            EntryType votingType = EntryType.Open,
            RankingType rewardType = RankingType.Multiple,
            DeadlineType deadlineType = DeadlineType.Time)
        {
            this._winners = new HashSet<ContestEntry>();
            this._contestEntries = new HashSet<ContestEntry>();
            this._participants = new HashSet<User>();

            this._participationStrategy = new ParticipationStrategy(participationType);
            this._votingStrategy = new VotingStrategy(votingType);
            this._rewardStrategy = new RewardStrategy(rewardType);
            this._deadlineStrategy = new DeadlineStrategy(deadlineType);
        }
Example #28
0
 public SavedSwarmButton(ControlScreen menu, string text, EntryType type, List<Color> colors, ControlScreen screen, Texture2D texture)
     : base(menu,text,type,screen,texture)
 {
     if (colors != null && colors.Count > 0)
     {
         Color1 = colors[0];
         if (colors.Count > 1)
         {
             Color2 = colors[1];
         }
         if (colors.Count > 2)
         {
             Color3 = colors[2];
         }
     }
 }
Example #29
0
        /// <summary>
        /// Constructs a new menu entry with the specified text.
        /// </summary>
        /// 
        public MenuEntry(MenuScreen menu, string text, EntryType type, GameScreen screen, Texture2D texture)
        {
            _text = text;
            _screen = screen;
            _type = type;
            _menu = menu;
            #if NETFX_CORE
            BaseScale = 1f;
            #else
            BaseScale = 1f;
            #endif
            _scale = 0.7f;

            _alpha = 1.0f;
            _menuItemBackground = texture;
        }
Example #30
0
 protected override void WriteHeader(string name, DateTime lastModificationTime, long count, int userId, int groupId, int mode, EntryType entryType)
 {
     var tarHeader = new UsTarHeader()
     {
         FileName = name,
         LastModification = lastModificationTime,
         SizeInBytes = count,
         UserId = userId,
         UserName = Convert.ToString(userId,8),
         GroupId = groupId,
         GroupName = Convert.ToString(groupId,8),
         Mode = mode,
         EntryType = entryType
     };
     OutStream.Write(tarHeader.GetHeaderValue(), 0, tarHeader.HeaderSize);
 }
        private Entry AddEntry(string relativeFilePath, string shortPath, EntryType type)
        {
            if (type == EntryType.Directory)
            {
                relativeFilePath = PathHelper.EnsureTrailingSlash(relativeFilePath);
                shortPath        = PathHelper.EnsureTrailingSlash(shortPath);
            }

            Entry entry;

            if (!_entries.TryGetValue(relativeFilePath, out entry))
            {
                entry = new Entry(relativeFilePath, shortPath, type)
                {
                    State = Added
                };

                _entries[relativeFilePath] = entry;
                return(entry);
            }

            switch (entry.State)
            {
            case Unchanged:
            case RenamedThenAdded:
            case Added:
                break;

            case Deleted:
                entry.State = Unchanged;
                break;

            case Renamed:
                entry.State = RenamedThenAdded;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(entry);
        }
Example #32
0
        private bool MergeEntries <T>(EntryList <T> source, EntryList <T> target, EntryType type, Func <T, T, bool> action) where T : EntryBase
        {
            var changed = false;

            foreach (var b in source)
            {
                var a = target.FirstOrDefault(e => e.Entry.Id == b.Entry.Id);
                if (a == null)
                {
                    AddNewEntry <T>(type, b.AllBytes, b.Entry.Id);
                    changed = true;
                    continue;
                }
                if (action != null)
                {
                    changed = action.Invoke(a, b) || changed;
                }
            }
            return(changed);
        }
Example #33
0
        public async Task <ActionResult <EntryType> > PutEntryTypeDescription(Guid entryTypeID, [FromBody] EditEntryTypeDescriptionModel model)
        {
            try
            {
                EntryType logicEntryType = new EntryType()
                {
                    entryTypeID          = entryTypeID,
                    entryTypeDescription = model.entryTypeDescription
                };
                await repository.UpdateEntryTypeDescription(logicEntryType);

                await repository.SaveAsync();

                return(Ok(await repository.GetEntryTypeByIDAsync(entryTypeID)));
            }
            catch (Exception e)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, e.InnerException));
            }
        }
Example #34
0
        public EditContactViewModel(IRepositoryManager repositoryManager, Person person, CloseView closeAction)
        {
            entryType       = EntryType.Existing;
            _repository     = repositoryManager;
            PersonToEdit    = person;
            PersonFirstName = person.FirstName;
            PersonLastName  = person.LastName;
            PersonId        = person.Id;
            if (person.Addresses?.Count > 0)
            {
                Addresses = person.Addresses.ToObservableCollection();
            }
            else
            {
                Addresses = new ObservableCollection <Address>();
            }

            BindButtons();
            closeView = closeAction;
        }
Example #35
0
    Color GetColorFromType(EntryType type)
    {
        switch (type)
        {
        case EntryType.Combat:
            return(Color.red);

        case EntryType.Harvesting:
            return(Color.yellow);

        case EntryType.Dialogue:
            return(Color.cyan);

        case EntryType.Default:
            return(Color.white);

        default:
            return(Color.magenta);
        }
    }
Example #36
0
        public SessionMenuEntry(RestartButton menu, EntryType type, GameScreen screen)
        {
            Screen = screen;
            _type  = type;
            _menu  = menu;
            _scale = 0.9f;
            Alpha  = 1.0f;


            var viewport_height = _menu.ScreenManager.GraphicsDevice.Viewport.Height;
            var viewport_width  = _menu.ScreenManager.GraphicsDevice.Viewport.Width;

            gameIcon1 = new Sprite(_menu.ScreenManager.Content.Load <Texture2D>("gameObjs\\buttonRestart"));
            var percentage = ((float)viewport_width) / (100f / _sizeScaleInPercent);

            _buttonScale = percentage / gameIcon1.Size.X;

            _width  = gameIcon1.Size.X * _buttonScale;
            _height = gameIcon1.Size.Y * _buttonScale;
        }
Example #37
0
    public void SubmitEntry(EntryType entryType, string input, User user)
    {
        if (activeList == null)
        {
            Debug.LogError("No list selected!");
            return;
        }

        if (entryType == EntryType.Question)
        {
            activeList.AddQuestion(new Question(input, user));
        }

        if (entryType == EntryType.Answer)
        {
            activeQuestion.AddAnswer(new Answer(input));
        }

        activeList.Save();
    }
Example #38
0
        public void getlEtt()
        {
            //lDept = new List<Department>();

            lEtt.Clear();
            DataTable dt = new DataTable();

            dt    = selectAll();
            dtEtt = dt;
            foreach (DataRow row in dt.Rows)
            {
                EntryType ett1 = new EntryType();
                ett1.entry_type_id     = row[ett.entry_type_id].ToString();
                ett1.entry_type_code   = row[ett.entry_type_code].ToString();
                ett1.entry_type_name_e = row[ett.entry_type_name_e].ToString();
                ett1.entry_type_name_t = row[ett.entry_type_name_t].ToString();

                lEtt.Add(ett1);
            }
        }
Example #39
0
        private void processChangedOrCreatedEntry(EntryType type, string path)
        {
            var existingEntry = _root.GetEntry(path);

            if (existingEntry == null)
            {
                createEntry(type, path);
                return;
            }

            var actualType = type == EntryType.Uncertain
                                ? existingEntry.Type
                                : type;

            if (actualType != existingEntry.Type || actualType == EntryType.File)
            {
                deleteEntry(existingEntry);
                createEntry(type, path);
            }
        }
Example #40
0
        private static string EntryDetails(UrlHelper urlHelper, EntryType entryType, int id, string urlSlug)
        {
            switch (entryType)
            {
            case EntryType.DiscussionTopic:
                return(urlHelper.Action("Index", "Discussion", new { clientPath = string.Format("topics/{0}", id) }));

            case EntryType.ReleaseEvent:
                return(urlHelper.Action("Details", "Event", new { id, slug = urlSlug }));

            case EntryType.ReleaseEventSeries:
                return(urlHelper.Action("SeriesDetails", "Event", new { id, slug = urlSlug }));

            case EntryType.Tag:
                return(urlHelper.Action("DetailsById", "Tag", new { id, slug = urlSlug }));

            default:
                return(urlHelper.Action("Details", entryType.ToString(), new { id }));
            }
        }
        // * Methods *
        // Static Factory Method - Create Buyer Entry
        public static MarketEntry CreateBuyerEntry(string userId, EntryType entryType,
                                                   int auctionId, int productId,
                                                   byte productQualityId, double entryQuantity,
                                                   decimal entryPrice, DateTime deliveryDate,
                                                   string deliveryLocation)
        {
            var marketEntry = new MarketEntry(userId, entryType, auctionId, entryQuantity,
                                              entryPrice, deliveryDate);

            var buyerFinalProduct = new FinalProduct()
            {
                ProductId = productId,
                QualityId = productQualityId
            };

            marketEntry.FinalProduct     = buyerFinalProduct;
            marketEntry.DeliveryLocation = deliveryLocation;

            return(marketEntry);
        }
Example #42
0
        protected void CheckConcurrentEdit(EntryType entryType, int id)
        {
            Login.Manager.VerifyLogin();

            var conflictingEditor = ConcurrentEntryEditManager.CheckConcurrentEdits(new EntryRef(entryType, id), Login.User);

            if (conflictingEditor.UserId != ConcurrentEntryEditManager.Nothing.UserId)
            {
                var ago = DateTime.Now - conflictingEditor.Time;

                if (ago.TotalMinutes < 1)
                {
                    TempData.SetStatusMessage(string.Format(ViewRes.EntryEditStrings.ConcurrentEditWarningNow, conflictingEditor.UserName));
                }
                else
                {
                    TempData.SetStatusMessage(string.Format(ViewRes.EntryEditStrings.ConcurrentEditWarning, conflictingEditor.UserName, (int)ago.TotalMinutes));
                }
            }
        }
Example #43
0
        /// <summary>
        /// Conversion from Entry to string seq seq
        /// Contrary function of LoadContentToFile()
        /// </summary>
        /// <returns></returns>
        private IEnumerable <IEnumerable <string> > SaveFileToContent()
        {
            var titles = Titles;

            if (_titleRules != null)
            {
                _titleRules(ref titles);
            }

            var content = new List <List <string> > {
                titles
            };

            foreach (var aEntry in Content)
            {
                var newEntry = aEntry;
                if (_entryRules != null)
                {
                    _entryRules(ref newEntry);
                }
                var newContentLine = new List <string>();
                foreach (var propName in Titles.Select(
                             title => (from prop in EntryType.GetProperties()
                                       from attr in prop.GetCustomAttributes(typeof(TitleName), false)
                                       where ((TitleName)attr).Name == title
                                       select prop.Name).FirstOrDefault()))
                {
                    if (propName != null)
                    {
                        var contentField = EntryType.GetProperty(propName).GetValue(newEntry, null);
                        newContentLine.Add(contentField.ToString());
                    }
                    else
                    {
                        newContentLine.Add("");
                    }
                }
                content.Add(newContentLine);
            }
            return(content);
        }
Example #44
0
        async void ReadMembersFormDataBase(EntryType type)
        {
            var table = string.Empty;

            switch (type)
            {
            case EntryType.Channel:
                table = "channels";
                break;

            case EntryType.EPG:
                break;

            case EntryType.Server:
                table = "servers";
                break;

            case EntryType.Provider:
                table = "providers";
                break;

            default:
                break;
            }

            var items = db.SQLQuery <ulong>(string.Format("SELECT * FROM {0}", table)).Result;

            for (var i = ulong.MinValue; i < (ulong)items.Count; i++)
            {
                var item = Activator.CreateInstance(typeof(T));

                if (HasProperty(item.GetType(), "Name"))
                {
                    var name_prop = item.GetType().GetProperty("Name");
                    name_prop.SetValue(item, items[i]["name"]);

                    Add(string.Format("{0}", name_prop.GetValue(item)),
                        (T)Convert.ChangeType(item, typeof(T)));
                }
            }
        }
Example #45
0
        private async Task <TagTopUsagesAndCount <TEntry> > GetTopUsagesAndCountAsync <TUsage, TEntry, TSort, TSubType>(
            IDatabaseContext <Tag> ctx, int tagId,
            EntryType entryType,
            Func <IQueryable <TEntry>, EntryTypeAndTagCollection <TSubType>, IQueryable <TEntry> > whereExpression,
            int maxCount = 12)
            where TEntry : class, IEntryBase, IEntryWithTags <TUsage>
            where TUsage : TagUsage
            where TSubType : struct, Enum
        {
            var typeAndTag = EntryTypeAndTagCollection <TSubType> .Create(entryType, tagId, ctx, allowAllTags : true);

            var q = ctx.Query <TEntry>()
                    .WhereNotDeleted();

            q = whereExpression(q, typeAndTag);

            IReadOnlyCollection <TEntry> topUsages;
            int usageCount;

            try
            {
                topUsages = await q
                            .OrderByTagUsage <TEntry, TUsage>(tagId)
                            .Take(maxCount)
                            .VdbToListAsync();

                usageCount = await q.VdbCountAsync();
            }
            catch (Exception x) when(x is SqlException or GenericADOException)
            {
                s_log.Warn(x, "Unable to get tag usages");
                topUsages  = new TEntry[0];
                usageCount = 0;
            }

            return(new TagTopUsagesAndCount <TEntry>
            {
                TopUsages = topUsages,
                TotalCount = usageCount
            });
        }
Example #46
0
        public override void Load(BinaryReader reader, long length)
        {
            Entries.Clear();
            long dataOffset = reader.BaseStream.Position;

            uint count = Endian.ConvertUInt32(reader.ReadUInt32());

            // This alignment will always happen as each entry is 8 bytes each and the entry count is 4 bytes long.
            // Therefore there should always be 4 bytes of padding between the entry and string data.
            uint startChunkLen = (count * 8) + 4;

            if (startChunkLen % align != 0)
            {
                startChunkLen += align - startChunkLen % align;
            }

            long stringOffset = dataOffset + startChunkLen;

            for (int i = 0; i < count; i++)
            {
                // The native code writes to these palceholder bytes to calculate the offset of the string at runtime.
                // These are always expected to be be zero.
                uint placeholderBytes = reader.ReadUInt32();
                Debug.Assert(placeholderBytes == 0, "Unexpected placeholder data in howtoplay bin file");

                EntryType type    = (EntryType)reader.ReadByte();
                byte      imageId = reader.ReadByte();
                ushort    len     = Endian.ConvertUInt16(reader.ReadUInt16());

                long tempOffset = reader.BaseStream.Position;

                reader.BaseStream.Position = stringOffset;
                string str = Encoding.BigEndianUnicode.GetString(reader.ReadBytes(len * 2));
                reader.BaseStream.Position = tempOffset;

                Entry entry = new Entry(str, type, imageId);
                Entries.Add(entry);

                stringOffset += (len * 2) + 2;// Skip the null terminator bytes
            }
        }
Example #47
0
        /// <summary>
        /// Parses an FTP line and returns an entry, if vald
        ///
        /// Only tested on FileZilla FTP Server
        /// </summary>
        /// <param name="line">Line to be parsed</param>
        /// <param name="entry">Entry to be returned if valid</param>
        /// <returns>true if successful, otherwise false</returns>
        public static bool ParseFTPLine(string line, ref FTPEntry entry)
        {
            entry = null;
            EntryType type = EntryType.Unknown;

            if (line.StartsWith("-"))
            {
                type = EntryType.File;
            }
            else if (line.StartsWith("d"))
            {
                type = EntryType.Folder;
            }

            if (type == EntryType.Unknown)
            {
                return(false);
            }

            string[] parts     = line.Split(' ');
            string   name      = parts[parts.Length - 1];
            int      currIndex = 7;

            while (String.IsNullOrEmpty(parts[currIndex]))
            {
                currIndex++;
            }

            long size = Convert.ToInt64(parts[currIndex]);

            if (type == EntryType.File)
            {
                entry = new FTPEntry(name, size);
            }
            else
            {
                entry = new FTPEntry(name);
            }

            return(true);
        }
Example #48
0
        /// <summary>
        /// Creates a stylized log entry and stores it into the entry collection.
        /// </summary>
        /// <param name="message">The entry text to be made.</param>
        /// <param name="type">The style of the entry being made.</param>
        internal static void AddEntry(string message, EntryType type)
        {
            // Check what type of entry we're adding and create it.
            string entry = null;

            switch (type)
            {
            case EntryType.General:
                entry += Timestamp() + "[-] " + message;
                break;

            case EntryType.Notice:
                entry += Timestamp() + "[*] " + message;
                break;

            case EntryType.Success:
                entry += Timestamp() + "[+] " + message;
                break;

            case EntryType.Warning:
                entry += Timestamp() + "[!] " + message;
                break;

            case EntryType.Error:
                entry += Timestamp() + "[x] " + message;
                break;
            }

            // Add our entry if it's not null, otherwise, add our received message.
            if (entry != null)
            {
                Log.Add(entry);
            }
            else
            {
                if (message != null)
                {
                    Log.Add(entry);
                }
            }
        }
Example #49
0
        /// <summary>
        /// Case insenstive indexer which gets or sets the value of the named property.
        /// Values which are set which are not properties will be added to the internal dictionary and so will be accessible anyway.
        /// Note that the EntryType and CitationKey are readonly, and will throw an exception when trying to set from here.
        /// </summary>
        /// <param name="propertyName"></param>
        /// <returns>The value of the field or if the field
        /// does not exist, then null.</returns>
        public string this[string propertyName]
        {
            get
            {
                if (propertyName.Equals(ENTRY_TYPE, SC.OrdinalIgnoreCase))
                {
                    return(EntryType.ToString());
                }
                else if (propertyName.Equals(CITATION_KEY, SC.OrdinalIgnoreCase))
                {
                    return(CitationKey);
                }
                else if (_propertyGetters.TryGetValue(propertyName, out var getter))
                {
                    return(getter(this));
                }

                return(_keyValuePairs.TryGetValue(propertyName, out var value) ? value : null);
            }
            set
            {
                if (propertyName.Equals(ENTRY_TYPE, SC.OrdinalIgnoreCase) || propertyName.Equals(CITATION_KEY, SC.OrdinalIgnoreCase))
                {
                    throw new MemberAccessException($"Cannot set read-only property: '{propertyName}'");
                }

                if (_keyValuePairs.ContainsKey(propertyName))
                {
                    _keyValuePairs[propertyName] = value;
                }
                else
                {
                    _keyValuePairs.Add(propertyName, value);
                }

                if (_propertySetters.TryGetValue(propertyName, out var setter))
                {
                    setter(this, value);
                }
            }
        }
Example #50
0
        /// <summary>
        /// Implementace zápisu zprávy
        /// </summary>
        /// <param name="message">Text zprávy</param>
        /// <param name="level">Důležitost zprávy</param>
        /// <param name="type">Typ zprávy</param>
        protected override void OnWriteLine(string message, VerbosityLevel level, EntryType type)
        {
            EventLogEntryType entryType;

            switch (type)
            {
            case EntryType.Error:
                entryType = EventLogEntryType.Error;
                break;

            case EntryType.Warning:
                entryType = EventLogEntryType.Warning;
                break;

            default:
                entryType = EventLogEntryType.Information;
                break;
            }

            EventLog.WriteEntry(this.Source, TrimMessage((string.IsNullOrEmpty(this.EntryHeader) ? "" : this.EntryHeader + Environment.NewLine) + message, this.Source.Length), entryType);
        }
Example #51
0
        public CreateEntryRequest(string name, string videoAddress, EntryType type)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (videoAddress == null)
            {
                throw new ArgumentNullException("videoAddress");
            }

            try { new MailAddress(videoAddress); }
            catch (Exception)
            {
                throw new ArgumentException("Invalid video address", "videoAddress");
            }

            this.Name         = name;
            this.VideoAddress = VideoAddress;
            this.Type         = type;
        }
Example #52
0
        private Dictionary <string, object> FindMetaData(int titleid, EntryType type)
        {
            // This methods finds the metadata that is associated with a title id
            String typestring = "";

            switch (type)
            {
            case EntryType.Anime:
                typestring = "anime";
                break;

            case EntryType.Manga:
                typestring = "manga";
                break;
            }
            Dictionary <string, object> searchpattern = new Dictionary <string, object>();

            searchpattern["id"]   = titleid.ToString();
            searchpattern["type"] = typestring;
            return(attributes.FirstOrDefault(x => searchpattern.All(x.Contains)));
        }
    void SetAngle(Transform indicator, EntryType entry, int index)
    {
        float eulerY = 0;

        if (entry == EntryType.Horizontal)
        {
            eulerY = (index == 0 || index == 3) ? 0 : 180;
        }

        if (entry == EntryType.Vertical)
        {
            eulerY = (index == 0 || index == 1) ? 90 : 270;
        }

        if (entry == EntryType.None)
        {
            eulerY = 90 * index;
        }

        indicator.localRotation = Quaternion.Euler(new Vector3(indicator.eulerAngles.x, eulerY, indicator.eulerAngles.z));
    }
Example #54
0
        private string[] searchType(string path, EntryType type)
        {
            PlexFAT.Directory dir = getDirectory(path);
            var arr = dir.Contents.Where(n => dir.TypeOf(n) == type).ToArray();
            var lst = new List <string>();

            if (path.EndsWith("/"))
            {
                path = path.Remove(path.LastIndexOf("/"), 1);
            }
            if (type == EntryType.DIRECTORY)
            {
                lst.Add(DriveNumber + path + "/.");
            }
            foreach (var entry in arr)
            {
                lst.Add(DriveNumber + path + "/" + entry);
            }

            return(lst.ToArray());
        }
Example #55
0
        public FeedItem(EntryType entryType,
                        string title,
                        string subtitle,
                        Image cover,
                        DateTimeOffset releaseDate,
                        string aid,
                        string author,
                        string origin,
                        string intro)
        {
            this.EntryType   = entryType;
            this.ReleaseDate = releaseDate;
            this.Title       = title;
            this.Subtitle    = subtitle;
            this.Cover       = cover;
            switch (entryType)
            {
            case EntryType.Article:
                var a = Collections.References.Articles[aid];
                if (a == null)
                {
                    a = new Article(aid);
                    Collections.References.Articles.Add(a);
                }
                a.Title        = title;
                a.Subtitle     = subtitle;
                a.Cover        = cover;
                a.ReleaseDate  = releaseDate;
                a.Author       = author;
                a.Origin       = origin;
                a.Introduction = intro;
                this.Item      = a;
                break;

            case EntryType.Guide:
                var g = new Guide(releaseDate);
                this.Item = g;
                break;
            }
        }
Example #56
0
        public String insert(EntryType p)
        {
            String re  = "";
            String sql = "";

            p.active = "1";
            //p.ssdata_id = "";
            int chk = 0;

            p.date_modi   = p.date_modi == null ? "" : p.date_modi;
            p.date_cancel = p.date_cancel == null ? "" : p.date_cancel;
            p.user_create = p.user_create == null ? "" : p.user_create;
            p.user_modi   = p.user_modi == null ? "" : p.user_modi;
            p.user_cancel = p.user_cancel == null ? "" : p.user_cancel;
            //p.prefix_id = int.TryParse(p.prefix_id, out chk) ? chk.ToString() : "0";
            //p.dept_id = int.TryParse(p.dept_id, out chk) ? chk.ToString() : "0";

            sql = "Insert Into " + ett.table + "(" + ett.entry_type_code + "," + ett.entry_type_name_e + "," + ett.entry_type_name_t + "," +
                  ett.date_create + "," + ett.date_modi + "," + ett.date_cancel + "," +
                  ett.user_create + "," + ett.user_modi + "," + ett.user_cancel + "," +
                  ett.active + "," + ett.remark + ", " + ett.sort1 + ", " +
                  ett.status_app + " " +
                  ") " +
                  "Values ('" + p.entry_type_code + "','" + p.entry_type_name_e.Replace("'", "''") + "','" + p.entry_type_name_t.Replace("'", "''") + "'," +
                  "'" + p.date_create + "','" + p.date_modi + "','" + p.date_cancel + "'," +
                  "'" + p.user_create + "','" + p.user_modi + "','" + p.user_cancel + "'," +
                  "'" + p.active + "','" + p.remark.Replace("'", "''") + "','" + p.sort1 + "', " +
                  "'" + p.status_app + "' " +
                  ")";
            try
            {
                re = conn.ExecuteNonQuery(conn.conn, sql);
            }
            catch (Exception ex)
            {
                sql = ex.Message + " " + ex.InnerException;
            }

            return(re);
        }
        internal static string GetReadableTestTypeName(EntryType entryType)
        {
            string result = string.Empty;

            switch (entryType)
            {
            case EntryType.BeforeBreakfast:
                result = Constants.BeforeBreakfast;
                break;

            case EntryType.AfterBreakfast:
                result = Constants.AfterBreakfast;
                break;

            case EntryType.BeforeLunch:
                result = Constants.BeforeLunch;
                break;

            case EntryType.AfterLunch:
                result = Constants.AfterLunch;
                break;

            case EntryType.BeforeDinner:
                result = Constants.BeforeDinner;
                break;

            case EntryType.AfterDinner:
                result = Constants.AfterDinner;
                break;

            case EntryType.BeforeBed:
                result = Constants.BeforeBed;
                break;

            default:
                break;
            }

            return(result);
        }
Example #58
0
        private void RecordMappingIds(int titleid, EntryType type)
        {
            List <Dictionary <string, object> > attributes = ((JArray)JObjectToDictionary((JObject)JObjectToDictionary((JObject)FindMetaData(titleid, type)["relationships"])["mappings"])["data"]).ToObject <List <Dictionary <string, object> > >();

            foreach (Dictionary <string, object> mapping in attributes)
            {
                int mappingid = int.Parse((string)mapping["id"]);
                Dictionary <string, object> titleidmap    = FindMapping(mappingid);
                Dictionary <string, object> mapattributes = ((JObject)titleidmap["attributes"]).ToObject <Dictionary <string, object> >();
                if (mapattributes.ContainsKey("externalSite"))
                {
                    if ((string)mapattributes["externalSite"] == "myanimelist/" + (type == EntryType.Anime ? "anime" : "manga"))
                    {
                        int mtitleid = int.Parse((string)mapattributes["externalId"]);
                        if (tconverter.RetreiveSavedMALIDFromServiceID(Service.Kitsu, titleid, type) < 0)
                        {
                            tconverter.SaveIDtoDatabase(Service.Kitsu, mtitleid, titleid, type);
                        }
                    }
                }
            }
        }
Example #59
0
        public KeyValuePair <string[], decimal[]> GetSpendingSumForLastYear(int?[] selectedAccounts, IEnumerable <EntryType> entryTypesWithCategories)
        {
            IEnumerable <EntryType> entryTypesWithCategoriesNoIncome = entryTypesWithCategories.Where(x => x.Name != "Income");
            var arraySize = entryTypesWithCategoriesNoIncome.Count();

            string[]  dataSumLabels = new string[arraySize];
            decimal[] dataSumData   = new decimal[arraySize];
            DateTime  date          = DateTime.Now.Date;

            for (int i = 0; i < arraySize; ++i)
            {
                EntryType entryTypeWithCategories = entryTypesWithCategoriesNoIncome.ElementAt(i);
                dataSumData[i] = _context.Records.Where(x => entryTypeWithCategories.Categories.Any(y => y.Id == x.CategoryId) &&
                                                        selectedAccounts.Contains(x.AccountId) &&
                                                        DateTime.ParseExact(x.CreatedTimestamp, "dd-MM-yy HH:mm:ss", CultureInfo.InvariantCulture).Date <= date &&
                                                        DateTime.ParseExact(x.CreatedTimestamp, "dd-MM-yy HH:mm:ss", CultureInfo.InvariantCulture).Date > date.AddDays(-365))
                                 .Sum(x => x.MoneyAmount);
                dataSumLabels[i] = entryTypeWithCategories.Name;
            }

            return(new KeyValuePair <string[], decimal[]>(dataSumLabels, dataSumData));
        }
Example #60
0
        /// <summary>
        /// Creates or updates resources based on the natural key values of the supplied resource. The POST operation can be used to create or update resources. In database terms, this is often referred to as an &quot;upsert&quot; operation (insert + update).  Clients should NOT include the resource &quot;id&quot; in the JSON body because it will result in an error (you must use a PUT operation to update a resource by &quot;id&quot;). The web service will identify whether the resource already exists based on the natural key values provided, and update or create the resource appropriately.
        /// </summary>
        /// <param name="body">The JSON representation of the &quot;entryType&quot; resource to be created or updated.</param>
        /// <returns>A RestSharp <see cref="IRestResponse"/> instance containing the API response details.</returns>
        public IRestResponse PostEntryTypes(EntryType body)
        {
            var request = new RestRequest("/entryTypes", Method.POST);

            request.RequestFormat = DataFormat.Json;

            // verify required params are set
            if (body == null)
            {
                throw new ArgumentException("API method call is missing required parameters");
            }
            request.AddBody(body);
            var response = client.Execute(request);

            var location = response.Headers.FirstOrDefault(x => x.Name == "Location");

            if (location != null && !string.IsNullOrWhiteSpace(location.Value.ToString()))
            {
                body.id = location.Value.ToString().Split('/').Last();
            }
            return(response);
        }