string.IsNullOrEmpty(string)

Here are the examples of the csharp api string.IsNullOrEmpty(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

93262 Examples 7

19 Source : Configuration.ValueConfig.cs
with GNU Affero General Public License v3.0
from 0ceal0t

private bool DrawCombo(string id, T[] comboOptions, T currentValue, out T value) {
            value = currentValue;
            if (ImGui.BeginCombo(id, $"{currentValue}", ImGuiComboFlags.HeightLargest)) {
                if (ShowSearch) {
                    ImGui.SetNexreplacedemWidth(ImGui.GetWindowContentRegionWidth() - 50);
                    ImGui.InputText("Search##Combo", ref SearchInput, 256);
                }

                if (ShowSearch) ImGui.BeginChild("Child##Combo", new Vector2(ImGui.GetWindowContentRegionWidth(), 200), true);

                var idx = 0;
                foreach (T option in comboOptions) {
                    if (ShowSearch && !string.IsNullOrEmpty(SearchInput)) {
                        var optionString = option.ToString();
                        if (!optionString.ToLower().Contains(SearchInput.ToLower())) continue;
                    }

                    if (ImGui.Selectable($"{option}##Combo{idx}", option.Equals(currentValue))) {
                        value = option;

                        if (ShowSearch) ImGui.EndChild();
                        ImGui.EndCombo();
                        return true;
                    }
                    idx++;
                }

                if (ShowSearch) ImGui.EndChild();
                ImGui.EndCombo();
            }
            return false;
        }

19 Source : GaugeGCDConfig.cs
with GNU Affero General Public License v3.0
from 0ceal0t

protected override void DrawConfig(string id, ref bool newPos, ref bool newVisual, ref bool reset) {
            foreach (var subGCD in SubGCDs) {
                var suffix = string.IsNullOrEmpty(subGCD.SubName) ? "" : $" ({subGCD.SubName})";

                if (JobBars.Config.GaugeColor.Draw($"Color{suffix}{id}", subGCD.Name, subGCD.Color, out var newColor)) {
                    subGCD.Color = newColor;
                    newVisual = true;
                }

                if (JobBars.Config.GaugeInvert.Draw($"Invert{suffix}{id}", subGCD.Name, subGCD.Invert, out var newInvert)) {
                    subGCD.Invert = newInvert;
                }

                if (JobBars.Config.GaugeCompletionSound.Draw($"Completion Sound{suffix}{id}", subGCD.Name, ValidSoundType, subGCD.CompletionSound, out var newCompletionSound)) {
                    subGCD.CompletionSound = newCompletionSound;
                }

                if (JobBars.Config.GaugeProgressSound.Draw($"Play Sound On Progress{suffix}{id}", subGCD.Name, subGCD.ProgressSound, out var newProgressSound)) {
                    subGCD.ProgressSound = newProgressSound;
                }

                if (JobBars.Config.GaugeReverseFill.Draw($"Reverse Tick Fill Order{suffix}{id}", subGCD.Name, subGCD.ReverseFill, out var newReverseFill)) {
                    subGCD.ReverseFill = newReverseFill;
                    newVisual = true;
                }
            }
        }

19 Source : GaugeTimerConfig.cs
with GNU Affero General Public License v3.0
from 0ceal0t

protected override void DrawConfig(string id, ref bool newPos, ref bool newVisual, ref bool reset) {
            foreach (var subTimer in SubTimers) {
                var suffix = string.IsNullOrEmpty(subTimer.SubName) ? "" : $" ({subTimer.SubName})";

                if (JobBars.Config.GaugeColor.Draw($"Color{suffix}{id}", subTimer.Name, subTimer.Color, out var newColor)) {
                    subTimer.Color = newColor;
                    newVisual = true;
                }

                if (JobBars.Config.GaugeTimerOffset.Draw($"Time Offset{suffix}{id}", subTimer.Name, subTimer.Offset, out var newOffset)) {
                    subTimer.Offset = newOffset;
                }

                if (JobBars.Config.GaugeInvert.Draw($"Invert{suffix}{id}", subTimer.Name, subTimer.Invert, out var newInvert)) {
                    subTimer.Invert = newInvert;
                }

                if (JobBars.Config.GaugeProgressSound.Draw($"Play Sound When Low{suffix}{id}", subTimer.Name, subTimer.LowWarningSound, out var newLowWarningSound)) {
                    subTimer.LowWarningSound = newLowWarningSound;
                }
            }
        }

19 Source : UiHelper.Data.cs
with GNU Affero General Public License v3.0
from 0ceal0t

private static void SetupSheets() {
            JobToString = new();
            ItemToString = new();

            ActionSheet = JobBars.DataManager.GetExcelSheet<Lumina.Excel.GeneratedSheets.Action>().Where(
                x => !string.IsNullOrEmpty(x.Name) && (x.IsPlayerAction || x.ClreplacedJob.Value != null) && !x.IsPvP // weird conditions to catch things like enchanted RDM spells
            );
            foreach (var item in ActionSheet) {
                var name = item.Name.ToString();
                var attackType = item.ActionCategory.Value.Name.ToString();
                var actionId = item.ActionCategory.Value.RowId;
                if (item.Icon != 405 && item.Icon != 0) ActionToIcon[item.RowId] = item.Icon;

                if (actionId == 2 || actionId == 3) { // spell or weaponskill
                    if (item.CooldownGroup != 58 && item.AdditionalCooldownGroup != 58) continue; // not actually a gcd
                    GCDs.Add(item.RowId);
                }
            }

            List<StatusNameId> statusList = new();
            StatusSheet = JobBars.DataManager.GetExcelSheet<Lumina.Excel.GeneratedSheets.Status>().Where(x => !string.IsNullOrEmpty(x.Name));
            foreach (var item in StatusSheet) {
                statusList.Add(new StatusNameId {
                    Name = item.Name,
                    Status = new Item {
                        Id = item.RowId,
                        Type = ItemType.Buff
                    }
                });
            }
            StatusNames = statusList.ToArray();

            JobSheet = JobBars.DataManager.GetExcelSheet<ClreplacedJob>().Where(x => x.Name != null);
        }

19 Source : HealthMonitor.cs
with MIT License
from 0ffffffffh

private string RebuildArgList(string argList, string extras)
        {
            if (string.IsNullOrEmpty(extras))
                return argList;

            StringBuilder sb = new StringBuilder();
            string s;
            Dictionary<string, string> eArgs = Helper.ParseOptions(argList);
            Dictionary<string, string> extraDict = Helper.ParseOptions(extras);

            foreach (var key in extraDict.Keys)
            {
                if (eArgs.ContainsKey(key))
                {
                    eArgs[key] = extraDict[key];
                }
                else
                {
                    eArgs.Add(key, extraDict[key]);
                }
            }


            extraDict.Clear();
            extraDict = null;

            foreach (var key in eArgs.Keys)
            {
                sb.AppendFormat("{0} {1} ", key, eArgs[key]);
            }

            s = sb.ToString().TrimEnd();

            eArgs.Clear();
            eArgs = null;

            sb.Clear();
            sb = null;

            return s;
        }

19 Source : Helper.cs
with MIT License
from 0ffffffffh

public static Dictionary<string, string> ParseOptions(string s)
        {
            Dictionary<string, string> argDict = new Dictionary<string, string>();

            string tmp = "";
            bool putTmp = false;
            string opt = null;

            if (string.IsNullOrEmpty(s))
                return argDict;

            string[] breaks = s.Split(' ');

            foreach (string item in breaks)
            {
                if (item.StartsWith("\""))
                {
                    tmp = item;
                    putTmp = true;
                }
                else if (item.EndsWith("\""))
                {
                    putTmp = false;

                    if (opt != null)
                    {
                        argDict.Add(opt, tmp + item);
                        opt = null;
                    }
                    else
                        argDict.Add(tmp + item, "");

                    tmp = "";
                }
                else
                {
                    if (putTmp)
                        tmp += item;
                    else
                    {
                        var value = item.Trim();

                        if (value.Length > 0)
                        {
                            if (value.StartsWith("-"))
                            {
                                if (opt != null)
                                {
                                    argDict.Add(opt, "");
                                }

                                opt = value;

                            }
                            else
                            {
                                if (opt != null)
                                {
                                    argDict.Add(opt, value);
                                    opt = null;
                                }
                                else
                                    argDict.Add(value, "");
                            }
                        }
                    }
                }

            }

            if (opt != null)
                argDict.Add(opt, "");

            breaks = null;

            return argDict;
        }

19 Source : EdisFace.cs
with MIT License
from 0ffffffffh

private Dictionary<string,string> BuildForm(HttpListenerContext ctx)
        {
            string[] items;

            string post;

            using (StreamReader sr = new StreamReader(ctx.Request.InputStream))
            {
                post = sr.ReadToEnd();
            }

            if (string.IsNullOrEmpty(post))
                return null;

            items = post.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);

            var dict = new Dictionary<string, string>();

            foreach (var item in items)
            {
                string[] kv = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);

                if (kv.Length == 2)
                {
                    kv[1] = System.Web.HttpUtility.UrlDecode(kv[1],Encoding.GetEncoding("iso-8859-9"));


                    dict.Add(kv[0], kv[1]);
                }

            }

            return dict;
        }

19 Source : IndexAndSearchHandler.cs
with MIT License
from 0ffffffffh

private bool IsValidPagerHash(string s)
        {
            if (string.IsNullOrEmpty(s))
                return false;

            if (s.Length != 32)
                return false;

            for (int i=0;i<32;i++)
            {
                var c = char.ToLower(s[i]);

                if (!(c >= '0' && c <= '9') || !(c >= 'a' && c <= 'f'))
                    return false;

            }

            return true;
        }

19 Source : EdisFace.cs
with MIT License
from 0ffffffffh

private void RequestHandler(IAsyncResult result)
        {
            Dictionary<string, string> form;

            string objectName,path;
            HttpListenerContext ctx;

            if (!this.httpListener.IsListening)
                return;

            try
            {
                ctx = this.httpListener.EndGetContext(result);
            }
            catch (Exception e)
            {
                Log.Error("request completion error: " + e.Message);
                RegisterRequestWaiter(null);
                return;
            }

            form = BuildForm(ctx);

            objectName = ctx.Request.Url.LocalPath;

            var ext = Path.GetExtension(objectName);
            objectName = Path.GetFileNameWithoutExtension(objectName);

            objectName = objectName.
                Replace(".", "").
                Replace("/","").
                Replace("\\","");

            if (string.IsNullOrEmpty(objectName))
                objectName = "\\";
            else
                objectName = "\\" + objectName + ext;

            path = Config.Get().HtmlContentRoot + objectName;
            
            RegisterRequestWaiter(null);

            if (objectName == "\\")
            {
                if (ctx.Request.HttpMethod.ToLower() == "post")
                {
                    HandlePost(ctx, form);
                }
                else
                    ReplyIndex(ctx, string.Empty);
            }
            else
            {
                ReplyWithFile(ctx, path);
            }
            
            ctx.Response.Close();
        }

19 Source : MemcachedIo.cs
with MIT License
from 0ffffffffh

public bool Remove(string key)
        {
            if (string.IsNullOrEmpty(key))
                return false;

            return this.mc.Remove(key);
        }

19 Source : MemcachedIo.cs
with MIT License
from 0ffffffffh

public bool Set(string key, object value)
        {
            if (string.IsNullOrEmpty(key))
                return false;

            return this.mc.Store(StoreMode.Set, key, value);
        }

19 Source : MemcachedIo.cs
with MIT License
from 0ffffffffh

public bool Set(string key, object value, TimeSpan validFor)
        {
            if (string.IsNullOrEmpty(key))
                return false;

            return this.mc.Store(StoreMode.Set, key, value, validFor);
        }

19 Source : MemcachedIo.cs
with MIT License
from 0ffffffffh

public T Get<T>(string key)
        {
            if (string.IsNullOrEmpty(key))
                return default(T);

            return this.mc.Get<T>(key);
        }

19 Source : MemcachedIo.cs
with MIT License
from 0ffffffffh

public bool TryGet<T>(string key, out T value)
        {
            bool got;
            object obj;

            value = default(T);

            if (string.IsNullOrEmpty(key))
                return false;

            got = this.mc.TryGet(key, out obj);

            if (!got)
                return false;
            
            value = (T)obj;

            return true;
        }

19 Source : SozlukDataStore.cs
with MIT License
from 0ffffffffh

private static string BuildFetchSQLQuery(
            ref string baseQueryHash,
            string content, 
            string suser, 
            DateTime begin, DateTime end,
            int rowBegin,int rowEnd)
        {
            bool linkAnd = false;
            string query;

            StringBuilder sb = new StringBuilder();
            StringBuilder cond = new StringBuilder();

            if (!CacheManager.TryGetCachedResult<string>(baseQueryHash, out query))
            {

                if (!string.IsNullOrEmpty(suser))
                    sb.AppendFormat(SEARCH_SUSER_ID_GET_SQL, suser.Trim());

                if (!string.IsNullOrEmpty(content))
                {
                    cond.AppendFormat(SEARCH_COND_CONTENT, content.Trim());
                    linkAnd = true;
                }

                if (!string.IsNullOrEmpty(suser))
                {
                    if (linkAnd)
                        cond.Append(" AND ");
                    else
                        linkAnd = true;

                    cond.Append(SEARCH_COND_SUSER);
                }

                if (begin != DateTime.MinValue && end != DateTime.MinValue)
                {
                    if (linkAnd)
                        cond.Append(" AND ");

                    cond.AppendFormat(SEARCH_COND_DATE, begin.ToString(), end.ToString());

                }

                sb.Append(SEARCH_SQL_BASE);

                if (cond.Length > 0)
                {
                    cond.Insert(0, "WHERE ");
                    sb.Replace("%%CONDITIONS%%", cond.ToString());
                }
                else
                {
                    sb.Replace("%%CONDITIONS%%", string.Empty);
                }

                if (!string.IsNullOrEmpty(content))
                    sb.Replace("%%COUNT_CONDITION%%", string.Format(SEARCH_COND_COUNT_CONTENT, content));
                else
                    sb.Replace("%%COUNT_CONDITION%%", SEARCH_COND_COUNT_ALL);


                if (!string.IsNullOrEmpty(suser))
                    sb.Append(" AND EntryCount > 0");

                sb.Append(";");

                baseQueryHash = Helper.Md5(sb.ToString());

                CacheManager.CacheObject(baseQueryHash, sb.ToString());
            }
            else
            {
                sb.Append(query);
            }

            sb.Replace("%%ROW_LIMIT_CONDITION%%",
                string.Format("RowNum BETWEEN {0} AND {1}", rowBegin, rowEnd));
            
            query = sb.ToString();

            cond.Clear();
            sb.Clear();

            cond = null;
            sb = null;

            return query;
        }

19 Source : SozlukDataStore.cs
with MIT License
from 0ffffffffh

public static SearchAndIndexQueryResult FetchBasliksUsingSearch(bool fresh, string content, string suser, DateTime begin, DateTime end, int pageNumber, string pagerHash, bool leaveDatesAsIs)
        {
            SearchAndIndexQueryResult resultSet;
            SqlServerIo sql;
            TimeSpan invTimeout;
            int rowBegin, rowEnd;
            string query;
            KeysetId keysetId;
            string baslik, descr, deceptedDate;
            int entryCount;
            bool resultCached;

            rowBegin = (pageNumber * BasliksPerPage) + 1;
            rowEnd = rowBegin + BasliksPerPage - 1;

            //Workarounds, workarounds, workarounds !
            if (begin != DateTime.MinValue && end != DateTime.MinValue)
            {
                if (leaveDatesAsIs)
                {
                    deceptedDate = begin.AddTicks((end - begin).Ticks / 2).ToString();
                }
                else
                {
                    //push it out of from the search date range to reverse daterange check logic
                    deceptedDate = end.AddDays(2).ToString();
                }
            }
            else
                deceptedDate = string.Empty;

            query = BuildFetchSQLQuery(ref pagerHash, content, suser, begin, end, rowBegin, rowEnd);


            if (fresh)
            {
                keysetId = KeysetId.Todays(true);
                invTimeout = TodaysTimeout;
            }
            else
            {
                keysetId = KeysetId.Search(pagerHash,true);
                invTimeout = SearchResultTimeout;
            }

            resultCached = CacheManager.TryGetCachedQueryResult<SearchAndIndexQueryResult>(query, out resultSet);

            if (!resultCached)
            {
                sql = SqlServerIo.Create();

                if (!sql.Execute(false, query))
                {
                    SqlServerIo.Release(sql);
                    return new SearchAndIndexQueryResult();
                }

                resultSet = new SearchAndIndexQueryResult
                {
                    PagerHash = pagerHash
                };

                while (sql.Read())
                {
                    baslik = sql.GetValueOfColumn<string>("Baslik");
                    entryCount = sql.GetValueOfColumn<int>("EntryCount");

                    if (resultSet.TotalRecordCount == 0)
                        resultSet.TotalRecordCount = sql.GetValueOfColumn<int>("TotalRecordCount");

                    if (entryCount>0)
                        descr = content;
                    else
                        descr = Strev(content);

                    if (string.IsNullOrEmpty(suser))
                        suser = string.Empty;

                    resultSet.Entries.Add(
                        new Entry(
                            baslik, 
                            suser, 
                            deceptedDate, 
                            descr,entryCount)
                            );

                    resultSet.PhysicalRecordCount++;
                }

                resultSet.LogicalRecordCount = resultSet.Entries.Count;

                SqlServerIo.Release(sql);

                CacheManager.CacheObject(keysetId,true, query, resultSet,invTimeout);
            }

            return resultSet;
        }

19 Source : IndexAndSearchHandler.cs
with MIT License
from 0ffffffffh

private void HandleSearch()
        {
            bool noDate;
            int pageNum = GetValue<int>("pagenum");
            string pagerHash = GetValue<string>("ph");
            string term = GetValue<string>("term");
            string suser = GetValue<string>("suser");
            DateTime beginDate = GetValue<DateTime>("date");
            DateTime endDate = GetValue<DateTime>("todate");

            noDate = beginDate == DateTime.MinValue;

            if (noDate)
                endDate = DateTime.MinValue; //no date
            else if (endDate == DateTime.MinValue)
            {
                //begin set but end not. so replacedume the end to the today like sozluk-cgi does
                endDate = DateTime.Now; 

                if (beginDate > endDate)
                {
                    //We are damn sure that there will be no record :P
                    PushResponseItem("LogicalEntryCount", 0);
                    return;
                }
            }

            if (!string.IsNullOrEmpty(suser) && !Suser.IsSuserNameAllowed(suser))
            {
                PushResponseItem("LogicalEntryCount", 0);
                return;
            }

            if (!string.IsNullOrEmpty(pagerHash) && IsValidPagerHash(pagerHash))
            {
                PushResponseItem("LogicalEntryCount", 0);
                return;
            }

            if (!string.IsNullOrEmpty(term))
                term = NormalizeTerm(term);

            if (pageNum > 0)
                pageNum--;

            SearchAndIndexQueryResult result;

            result = SozlukDataStore.FetchBasliksUsingSearch(
                false, term, suser, beginDate, endDate, 
                pageNum,pagerHash,noDate);

            if (result.HasEntry)
            {
                PushResponseItem("TotalRecordCount", result.TotalRecordCount);
                PushResponseItem("LogicalEntryCount", result.LogicalRecordCount);
                PushResponseItem("PhysicalEntryCount", result.PhysicalRecordCount);
                PushResponseItem("TotalPageCount", SozlukDataStore.CalcPageCount(result.TotalRecordCount,RecordPerPageType.Basliks));
                PushResponseItem("CurrentPageNum", pageNum + 1);


                if (!string.IsNullOrEmpty(result.PagerHash))
                    PushResponseItem("PagerHash", result.PagerHash);


                foreach (var entry in result.Entries)
                    PushResponseContent(entry.GetTransportString());

                result.Entries.Clear();
                result.Entries = null;
            }
            else
            {
                PushResponseItem("LogicalEntryCount", 0);
            }
        }

19 Source : IndexAndSearchHandler.cs
with MIT License
from 0ffffffffh

private void HandleSearch()
        {
            bool noDate;
            int pageNum = GetValue<int>("pagenum");
            string pagerHash = GetValue<string>("ph");
            string term = GetValue<string>("term");
            string suser = GetValue<string>("suser");
            DateTime beginDate = GetValue<DateTime>("date");
            DateTime endDate = GetValue<DateTime>("todate");

            noDate = beginDate == DateTime.MinValue;

            if (noDate)
                endDate = DateTime.MinValue; //no date
            else if (endDate == DateTime.MinValue)
            {
                //begin set but end not. so replacedume the end to the today like sozluk-cgi does
                endDate = DateTime.Now; 

                if (beginDate > endDate)
                {
                    //We are damn sure that there will be no record :P
                    PushResponseItem("LogicalEntryCount", 0);
                    return;
                }
            }

            if (!string.IsNullOrEmpty(suser) && !Suser.IsSuserNameAllowed(suser))
            {
                PushResponseItem("LogicalEntryCount", 0);
                return;
            }

            if (!string.IsNullOrEmpty(pagerHash) && IsValidPagerHash(pagerHash))
            {
                PushResponseItem("LogicalEntryCount", 0);
                return;
            }

            if (!string.IsNullOrEmpty(term))
                term = NormalizeTerm(term);

            if (pageNum > 0)
                pageNum--;

            SearchAndIndexQueryResult result;

            result = SozlukDataStore.FetchBasliksUsingSearch(
                false, term, suser, beginDate, endDate, 
                pageNum,pagerHash,noDate);

            if (result.HasEntry)
            {
                PushResponseItem("TotalRecordCount", result.TotalRecordCount);
                PushResponseItem("LogicalEntryCount", result.LogicalRecordCount);
                PushResponseItem("PhysicalEntryCount", result.PhysicalRecordCount);
                PushResponseItem("TotalPageCount", SozlukDataStore.CalcPageCount(result.TotalRecordCount,RecordPerPageType.Basliks));
                PushResponseItem("CurrentPageNum", pageNum + 1);


                if (!string.IsNullOrEmpty(result.PagerHash))
                    PushResponseItem("PagerHash", result.PagerHash);


                foreach (var entry in result.Entries)
                    PushResponseContent(entry.GetTransportString());

                result.Entries.Clear();
                result.Entries = null;
            }
            else
            {
                PushResponseItem("LogicalEntryCount", 0);
            }
        }

19 Source : Entry.cs
with MIT License
from 0ffffffffh

private string MakeTag(string tagName, object value, string attribName = null, object attribValue = null)
        {
            if (!string.IsNullOrEmpty(attribName))
                return string.Format("<{0} {1}=\"{2}\">{3}</{0}>", tagName, attribName, attribValue.ToString(), value);

            return string.Format("<{0}>{1}</{0}>", tagName, value);
        }

19 Source : Suser.cs
with MIT License
from 0ffffffffh

public static bool IsSuserNameAllowed(string suser)
        {
            if (string.IsNullOrEmpty(suser))
                return false;
            
            foreach (var chr in suser)
            {
                if (!IsAllowedChr(chr))
                    return false;
            }

            return true;
        }

19 Source : CelesteNetDebugMapComponent.cs
with MIT License
from 0x0ade

public void Handle(CelesteNetConnection con, DataPlayerInfo player) {
            if (player.ID == Client.PlayerInfo.ID || LastArea == null)
                return;

            lock (Ghosts)
                if (Ghosts.TryGetValue(player.ID, out DebugMapGhost ghost) &&
                    string.IsNullOrEmpty(player.DisplayName))
                    Ghosts.Remove(player.ID);
        }

19 Source : CelesteNetMainComponent.cs
with MIT License
from 0x0ade

public void Handle(CelesteNetConnection con, DataPlayerFrame frame) {
            LastFrames[frame.Player.ID] = frame;

            Level level = Player?.Scene as Level;
            Session session = Session;

            bool outside =
                !Client.Data.TryGetBoundRef(frame.Player, out DataPlayerState state) ||
                level == null ||
                session == null ||
                state.SID != session.Area.SID ||
                state.Mode != session.Area.Mode ||
                state.Level == LevelDebugMap;

            if (UnsupportedSpriteModes.Contains(frame.SpriteMode))
                frame.SpriteMode = PlayerSpriteMode.Madeline;

            if (!Ghosts.TryGetValue(frame.Player.ID, out Ghost ghost) ||
                ghost == null ||
                (ghost.Active && ghost.Scene != level) ||
                ghost.Sprite.Mode != frame.SpriteMode ||
                outside) {
                ghost?.RunOnUpdate(ghost => ghost.NameTag.Name = "");
                ghost = null;
                Ghosts.TryRemove(frame.Player.ID, out _);
            }

            if (level == null || outside)
                return;

            if (ghost == null) {
                Ghosts[frame.Player.ID] = ghost = new(Context, frame.Player, frame.SpriteMode);
                ghost.Active = false;
                ghost.NameTag.Name = frame.Player.DisplayName;
                if (ghost.Sprite.Mode != frame.SpriteMode)
                    UnsupportedSpriteModes.Add(frame.SpriteMode);
                RunOnMainThread(() => {
                    level.Add(ghost);
                    level.OnEndOfFrame += () => ghost.Active = true;
                });
            }

            ghost.RunOnUpdate(ghost => {
                if (string.IsNullOrEmpty(ghost.NameTag.Name))
                    return;
                ghost.NameTag.Name = frame.Player.DisplayName;
                UpdateIdleTag(ghost, ref ghost.IdleTag, state.Idle);
                ghost.UpdateSprite(frame.Position, frame.Speed, frame.Scale, frame.Facing, frame.Depth, frame.Color, frame.SpriteRate, frame.SpriteJustify, frame.CurrentAnimationID, frame.CurrentAnimationFrame);
                ghost.UpdateHair(frame.Facing, frame.HairColor, frame.HairSimulateMotion, frame.HairCount, frame.HairColors, frame.HairTextures);
                ghost.UpdateDash(frame.DashWasB, frame.DashDir); // TODO: Get rid of this, sync particles separately!
                ghost.UpdateDead(frame.Dead && state.Level == session.Level);
                ghost.UpdateFollowers((Settings.Enreplacedies & CelesteNetClientSettings.SyncMode.Receive) == 0 ? Dummy<DataPlayerFrame.Enreplacedy>.EmptyArray : frame.Followers);
                ghost.UpdateHolding((Settings.Enreplacedies & CelesteNetClientSettings.SyncMode.Receive) == 0 ? null : frame.Holding);
                ghost.Interactive = state.Interactive;
            });
        }

19 Source : CelesteNetModShareComponent.cs
with MIT License
from 0x0ade

public void Handle(CelesteNetConnection con, DataMapModInfoRequest request) {
            string sid = request.MapSID;
            if (string.IsNullOrEmpty(sid))
                sid = (Engine.Scene as Level)?.Session?.Area.SID;

            if (string.IsNullOrEmpty(sid))
                goto Error;

            AreaData area = AreaData.Get(sid);
            if (area == null)
                goto Error;

            if (!Everest.Content.TryGet<replacedetTypeMap>($"Maps/{area.SID}", out Modreplacedet replacedet))
                goto Error;

            EverestModuleMetadata mod = replacedet?.Source?.Mod;
            if (mod == null)
                goto Error;

            Client?.Send(new DataMapModInfo {
                RequestID = request.ID,

                MapSID = sid,
                MapName = Dialog.Clean(area.Name),
                ModID = mod.Name,
                ModName = string.IsNullOrEmpty(mod.Name) ? "" : ($"modname_{mod.Name.DialogKeyify()}"?.DialogCleanOrNull() ?? Dialog.Clean(area.Name)),
                ModVersion = mod.Version
            });

            return;

            Error:
            Client?.Send(new DataMapModInfo {
                RequestID = request.ID
            });
            return;
        }

19 Source : CelesteNetPlayerListComponent.cs
with MIT License
from 0x0ade

public void RebuildList() {
            if (MDraw.DefaultFont == null || Client == null || Channels == null)
                return;

            DataPlayerInfo[] all = Client.Data.GetRefs<DataPlayerInfo>();

            List<Blob> list = new() {
                new Blob {
                    Text = $"{all.Length} player{(all.Length == 1 ? "" : "s")}",
                    Color = ColorCountHeader
                }
            };

            StringBuilder builder = new();


            switch (Mode) {
                case ListMode.Clreplacedic:
                    foreach (DataPlayerInfo player in all.OrderBy(p => GetOrderKey(p))) {
                        if (string.IsNullOrWhiteSpace(player.DisplayName))
                            continue;

                        builder.Append(player.DisplayName);

                        DataChannelList.Channel channel = Channels.List.FirstOrDefault(c => c.Players.Contains(player.ID));
                        if (channel != null && !string.IsNullOrEmpty(channel.Name)) {
                            builder
                                .Append(" #")
                                .Append(channel.Name);
                        }

                        if (Client.Data.TryGetBoundRef(player, out DataPlayerState state))
                            AppendState(builder, state);

                        builder.AppendLine();
                    }

                    list.Add(new() {
                        Text = builder.ToString().Trim(),
                        ScaleFactor = 1f
                    });
                    break;

                case ListMode.Channels:
                    HashSet<DataPlayerInfo> listed = new();

                    DataChannelList.Channel own = Channels.List.FirstOrDefault(c => c.Players.Contains(Client.PlayerInfo.ID));

                    if (own != null) {
                        list.Add(new() {
                            Text = own.Name,
                            Color = ColorChannelHeaderOwn
                        });

                        builder.Clear();
                        foreach (DataPlayerInfo player in own.Players.Select(p => GetPlayerInfo(p)).OrderBy(p => GetOrderKey(p))) 
                            listed.Add(ListPlayerUnderChannel(builder, player));
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 0.5f
                        });
                    }

                    foreach (DataChannelList.Channel channel in Channels.List) {
                        if (channel == own)
                            continue;

                        list.Add(new() {
                            Text = channel.Name,
                            Color = ColorChannelHeader
                        });

                        builder.Clear();
                        foreach (DataPlayerInfo player in channel.Players.Select(p => GetPlayerInfo(p)).OrderBy(p => GetOrderKey(p)))
                            listed.Add(ListPlayerUnderChannel(builder, player));
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 1f
                        });
                    }

                    bool wrotePrivate = false;

                    builder.Clear();
                    foreach (DataPlayerInfo player in all.OrderBy(p => GetOrderKey(p))) {
                        if (listed.Contains(player) || string.IsNullOrWhiteSpace(player.DisplayName))
                            continue;

                        if (!wrotePrivate) {
                            wrotePrivate = true;
                            list.Add(new() {
                                Text = "!<private>",
                                Color = ColorChannelHeaderPrivate
                            });
                        }

                        builder.AppendLine(player.DisplayName);
                    }

                    if (wrotePrivate) {
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 1f
                        });
                    }
                    break;
            }

            List = list;
        }

19 Source : CelesteNetPlayerListComponent.cs
with MIT License
from 0x0ade

private DataPlayerInfo GetPlayerInfo(uint id) {
            if (Client.Data.TryGetRef(id, out DataPlayerInfo player) && !string.IsNullOrEmpty(player?.DisplayName))
                return player;
            return null;
        }

19 Source : CelesteNetMainComponent.cs
with MIT License
from 0x0ade

public void Handle(CelesteNetConnection con, DataPlayerInfo player) {
            if (player.ID == Client.PlayerInfo.ID) {
                if (PlayerNameTag != null)
                    PlayerNameTag.Name = player.DisplayName;
                return;
            }

            if (!Ghosts.TryGetValue(player.ID, out Ghost ghost) ||
                ghost == null)
                return;

            if (string.IsNullOrEmpty(player.DisplayName)) {
                ghost.RunOnUpdate(ghost => ghost.NameTag.Name = "");
                Ghosts.TryRemove(player.ID, out _);
                LastFrames.TryRemove(player.ID, out _);
                Client.Data.FreeOrder<DataPlayerFrame>(player.ID);
                return;
            }
        }

19 Source : CelesteNetModShareComponent.cs
with MIT License
from 0x0ade

public void Handle(CelesteNetConnection con, DataMapModInfoRequest request) {
            string sid = request.MapSID;
            if (string.IsNullOrEmpty(sid))
                sid = (Engine.Scene as Level)?.Session?.Area.SID;

            if (string.IsNullOrEmpty(sid))
                goto Error;

            AreaData area = AreaData.Get(sid);
            if (area == null)
                goto Error;

            if (!Everest.Content.TryGet<replacedetTypeMap>($"Maps/{area.SID}", out Modreplacedet replacedet))
                goto Error;

            EverestModuleMetadata mod = replacedet?.Source?.Mod;
            if (mod == null)
                goto Error;

            Client?.Send(new DataMapModInfo {
                RequestID = request.ID,

                MapSID = sid,
                MapName = Dialog.Clean(area.Name),
                ModID = mod.Name,
                ModName = string.IsNullOrEmpty(mod.Name) ? "" : ($"modname_{mod.Name.DialogKeyify()}"?.DialogCleanOrNull() ?? Dialog.Clean(area.Name)),
                ModVersion = mod.Version
            });

            return;

            Error:
            Client?.Send(new DataMapModInfo {
                RequestID = request.ID
            });
            return;
        }

19 Source : CelesteNetPlayerListComponent.cs
with MIT License
from 0x0ade

private string GetOrderKey(DataPlayerInfo player) {
            if (player == null)
                return "9";

            if (Client.Data.TryGetBoundRef(player, out DataPlayerState state) && !string.IsNullOrEmpty(state?.SID))
                return $"0 {(state.SID != null ? "0" + state.SID : "9")} {player.FullName}";

            return $"8 {player.FullName}";
        }

19 Source : CelesteNetStatusComponent.cs
with MIT License
from 0x0ade

public void Set(string text, float timeText = timeTextMax, bool spin = true) {
            if (string.IsNullOrEmpty(text)) {
                show = false;
                return;
            }

            this.text = text;
            this.timeText = timeText;
            this.spin = spin;
            show = true;
        }

19 Source : Ghost.cs
with MIT License
from 0x0ade

public void UpdateSprite(Vector2 position, Vector2 speed, Vector2 scale, Facings facing, int depth, Color color, float rate, Vector2? justify, string animationID, int animationFrame) {
            if (Holdable.Holder == null) {
                Position = position;
            }
            Speed = speed;

            Sprite.Scale = scale;
            Sprite.Scale.X *= (float) facing;

            LastDepth = depth;
            Depth = depth + DepthOffset;

            LastSpriteColor = color;
            Sprite.Color = color * Alpha;

            Sprite.Rate = rate;
            Sprite.Justify = justify;

            if (!string.IsNullOrEmpty(animationID)) {
                try {
                    if (Sprite.CurrentAnimationID != animationID)
                        Sprite.Play(animationID);
                    Sprite.SetAnimationFrame(animationFrame);
                } catch {
                    // Play likes to fail randomly as the ID doesn't exist in an underlying dict.
                    // Let's ignore this for now.
                }
            }
        }

19 Source : GhostEmoteWheel.cs
with MIT License
from 0x0ade

public override void Render() {
            base.Render();

            string[] emotes = CelesteNetClientModule.Settings.Emotes;

            // Update can halt in the pause menu.

            if (Shown) {
                Angle = CelesteNetClientModule.Instance.JoystickEmoteWheel.Value.Angle();
                float angle = (float) ((Angle + Math.PI * 2f) % (Math.PI * 2f));
                float start = (-0.5f / emotes.Length) * 2f * (float) Math.PI;
                if (2f * (float) Math.PI + start < angle) {
                    // Angle should be start < angle < 0, but is (TAU + start) < angle < TAU
                    angle -= 2f * (float) Math.PI;
                }
                for (int i = 0; i < emotes.Length; i++) {
                    float min = ((i - 0.5f) / emotes.Length) * 2f * (float) Math.PI;
                    float max = ((i + 0.5f) / emotes.Length) * 2f * (float) Math.PI;
                    if (min <= angle && angle <= max) {
                        Selected = i;
                        break;
                    }
                }
            }

            time += Engine.RawDeltaTime;

            if (!Shown) {
                Selected = -1;
            }
            selectedTime += Engine.RawDeltaTime;
            if (PrevSelected != Selected) {
                selectedTime = 0f;
                PrevSelected = Selected;
            }

            float popupAlpha;
            float popupScale;

            popupTime += Engine.RawDeltaTime;
            if (Shown && !popupShown) {
                popupTime = 0f;
            } else if ((Shown && popupTime > 1f) ||
                (!Shown && popupTime < 1f)) {
                popupTime = 1f;
            }
            popupShown = Shown;

            if (popupTime < 0.1f) {
                float t = popupTime / 0.1f;
                // Pop in.
                popupAlpha = Ease.CubeOut(t);
                popupScale = Ease.ElasticOut(t);

            } else if (popupTime < 1f) {
                // Stay.
                popupAlpha = 1f;
                popupScale = 1f;

            } else {
                float t = (popupTime - 1f) / 0.2f;
                // Fade out.
                popupAlpha = 1f - Ease.CubeIn(t);
                popupScale = 1f - 0.2f * Ease.CubeIn(t);
            }

            float alpha = Alpha * popupAlpha;

            if (alpha <= 0f)
                return;

            if (Tracking == null)
                return;

            Level level = SceneAs<Level>();
            if (level == null)
                return;

            popupScale *= level.GetScreenScale();

            Vector2 pos = Tracking.Position;
            pos.Y -= 8f;

            pos = level.WorldToScreen(pos);

            float radius = BG.Width * 0.5f * 0.75f * popupScale;

            pos = pos.Clamp(
                0f + radius, 0f + radius,
                1920f - radius, 1080f - radius
            );

            // Draw.Circle(pos, radius, Color.Black * 0.8f * alpha * alpha, radius * 0.6f * (1f + 0.2f * (float) Math.Sin(time)), 8);
            BG.DrawCentered(
                pos,
                Color.White * alpha * alpha * alpha,
                Vector2.One * popupScale
            );

            Indicator.DrawCentered(
                pos,
                Color.White * alpha * alpha * alpha,
                Vector2.One * popupScale,
                Angle
            );

            float selectedScale = 1.2f - 0.2f * Calc.Clamp(Ease.CubeOut(selectedTime / 0.1f), 0f, 1f) + (float) Math.Sin(time * 1.8f) * 0.05f;

            for (int i = 0; i < emotes.Length; i++) {
                Line.DrawCentered(
                    pos,
                    Color.White * alpha * alpha * alpha,
                    Vector2.One * popupScale,
                    ((i + 0.5f) / emotes.Length) * 2f * (float) Math.PI
                );

                string emote = emotes[i];
                if (string.IsNullOrEmpty(emote))
                    continue;

                float a = (i / (float) emotes.Length) * 2f * (float) Math.PI;
                Vector2 emotePos = pos + new Vector2(
                    (float) Math.Cos(a),
                    (float) Math.Sin(a)
                ) * radius;

                if (GhostEmote.IsIcon(emote)) {
                    MTexture icon = GhostEmote.GetIcon(emote, Selected == i ? selectedTime : 0f);
                    if (icon == null)
                        continue;

                    Vector2 iconSize = new(icon.Width, icon.Height);
                    float iconScale = (GhostEmote.Size / Math.Max(iconSize.X, iconSize.Y)) * 0.24f * popupScale;

                    icon.DrawCentered(
                        emotePos,
                        Color.White * (Selected == i ? (Calc.BetweenInterval(selectedTime, 0.1f) ? 0.9f : 1f) : 0.7f) * alpha,
                        Vector2.One * (Selected == i ? selectedScale : 1f) * iconScale
                    );

                } else {
                    Vector2 textSize = CelesteNetClientFont.Measure(emote);
                    float textScale = (GhostEmote.Size / Math.Max(textSize.X, textSize.Y)) * 0.24f * popupScale;

                    CelesteNetClientFont.DrawOutline(
                        emote,
                        emotePos,
                        new(0.5f, 0.5f),
                        Vector2.One * (Selected == i ? selectedScale : 1f) * textScale,
                        (Selected == i ? (Calc.BetweenInterval(selectedTime, 0.1f) ? TextSelectColorA : TextSelectColorB) : Color.LightSlateGray) * alpha,
                        2f,
                        Color.Black * alpha * alpha * alpha
                    );
                }

19 Source : CelesteNetPlayerSession.cs
with MIT License
from 0x0ade

public bool ConSendFilter(CelesteNetConnection con, DataType data) {
            if (Server.Data.TryGetBoundRef(PlayerInfo, out DataNetFilterList? list) && list != null) {
                string source = data.GetSource(Server.Data);
                return string.IsNullOrEmpty(source) || list.Contains(source);
            }

            return true;
        }

19 Source : CelesteNetServerModule.cs
with MIT License
from 0x0ade

public virtual void Save(string path = "") {
            path = Path.GetFullPath(path.Nullify() ?? FilePath);

            Logger.Log(LogLevel.INF, "settings", $"Saving {GetType().Name} to {path}");

            string? dir = Path.GetDirectoryName(path);
            if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            using (Stream stream = File.OpenWrite(path + ".tmp"))
            using (StreamWriter writer = new(stream))
                Save(writer);

            if (File.Exists(path))
                File.Delete(path);
            File.Move(path + ".tmp", path);
        }

19 Source : FileSystemUserData.cs
with MIT License
from 0x0ade

public void SaveRaw<T>(string path, T data) where T : notnull {
            lock (GlobalLock) {
                string? dir = Path.GetDirectoryName(path);
                if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                using (Stream stream = File.OpenWrite(path + ".tmp"))
                using (StreamWriter writer = new(stream))
                    YamlHelper.Serializer.Serialize(writer, data, typeof(T));

                if (File.Exists(path))
                    File.Delete(path);
                File.Move(path + ".tmp", path);
            }
        }

19 Source : FileSystemUserData.cs
with MIT License
from 0x0ade

public override string GetUID(string key) {
            if (key.IsNullOrEmpty())
                return "";
            lock (GlobalLock) {
                if (LoadRaw<Global>(GlobalPath).UIDs.TryGetValue(key, out string? uid))
                    return uid;
                return "";
            }
        }

19 Source : FileSystemUserData.cs
with MIT License
from 0x0ade

public override Stream WriteFile(string uid, string name) {
            string path = GetUserFilePath(uid, name);
            string? dir = Path.GetDirectoryName(path);
            if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            if (File.Exists(path))
                File.Delete(path);
            return File.OpenWrite(path);
        }

19 Source : FileSystemUserData.cs
with MIT License
from 0x0ade

public override string Create(string uid) {
            lock (GlobalLock) {
                Global global = LoadRaw<Global>(GlobalPath);
                string key = GetKey(uid);
                if (!key.IsNullOrEmpty())
                    return key;

                string keyFull;
                do {
                    keyFull = Guid.NewGuid().ToString().Replace("-", "");
                    key = keyFull.Substring(0, 16);
                } while (global.UIDs.ContainsKey(key));
                global.UIDs[key] = uid;

                Save(uid, new PrivateUserInfo {
                    Key = key,
                    KeyFull = keyFull
                });

                SaveRaw(GlobalPath, global);

                return key;
            }
        }

19 Source : FileSystemUserData.cs
with MIT License
from 0x0ade

public override void CopyTo(UserData other) {
            using UserDataBatchContext batch = other.OpenBatch();
            lock (GlobalLock) {
                Global global = LoadRaw<Global>(GlobalPath);

                Dictionary<string, Type?> types = new();
                replacedembly[] asms = AppDomain.CurrentDomain.Getreplacedemblies();

                foreach (string uid in GetAll()) {
                    PrivateUserInfo info = Load<PrivateUserInfo>(uid);
                    other.Insert(uid, info.Key, info.KeyFull, !info.KeyFull.IsNullOrEmpty());

                    foreach (string path in Directory.GetFiles(Path.Combine(UserRoot, uid))) {
                        string name = Path.GetFileNameWithoutExtension(path);
                        if (name == typeof(PrivateUserInfo).FullName)
                            continue;

                        if (!types.TryGetValue(name, out Type? type)) {
                            foreach (replacedembly asm in asms)
                                if ((type = asm.GetType(name)) != null)
                                    break;
                            types[name] = type;
                        }

                        using Stream stream = File.OpenRead(path);
                        other.InsertData(uid, name, type, stream);
                    }

                    string dir = Path.Combine(UserRoot, uid, "data");
                    if (Directory.Exists(dir)) {
                        foreach (string path in Directory.GetFiles(dir)) {
                            string name = Path.GetFileName(path);
                            using Stream stream = File.OpenRead(path);
                            other.InsertFile(uid, name, stream);
                        }
                    }
                }
            }
        }

19 Source : FileSystemUserData.cs
with MIT License
from 0x0ade

private void InsertFileRaw(string path, Stream stream) {
            lock (GlobalLock) {
                string? dir = Path.GetDirectoryName(path);
                if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                if (File.Exists(path))
                    File.Delete(path);
                Stream target = File.OpenWrite(path);
                stream.CopyTo(target);
            }
        }

19 Source : ChatCMDChannelChat.cs
with MIT License
from 0x0ade

public override void ParseAndRun(ChatCMDEnv env) {
            CelesteNetPlayerSession? session = env.Session;
            if (session == null)
                return;

            string text = env.Text.Trim();

            if (string.IsNullOrEmpty(text)) {
                if (env.Server.UserData.GetKey(session.UID).IsNullOrEmpty())
                    throw new Exception("You must be registered to enable / disable auto channel chat mode!");

                ChatModule.UserChatSettings settings = env.Server.UserData.Load<ChatModule.UserChatSettings>(session.UID);
                settings.AutoChannelChat = !settings.AutoChannelChat;
                env.Server.UserData.Save(session.UID, settings);
                env.Send($"{(settings.AutoChannelChat ? "Enabled" : "Disabled")} auto channel chat.\nFilter out global chat via the mod options.");
                return;
            }

            DataPlayerInfo? player = env.Player;
            Channel channel = session.Channel;

            using ListSnapshot<CelesteNetPlayerSession> others = channel.Players.Where(p => p != session).ToSnapshot(channel.Lock);
            DataChat? msg = Chat.PrepareAndLog(null, new DataChat {
                Player = player,
#pragma warning disable CS8619 // LINQ is dumb.
                Targets = others.Select(p => p.PlayerInfo).Where(p => p != null).ToArray(),
#pragma warning restore CS8619
                Tag = $"channel {channel.Name}",
                Text = text,
                Color = Chat.Settings.ColorWhisper
            });

            if (msg == null)
                return;

            if (player != null) {
                env.Msg.Tag = $"channel {channel.Name}";
                env.Msg.Text = text;
                env.Msg.Color = Chat.Settings.ColorWhisper;
                Chat.ForceSend(env.Msg);
            }

            // FIXME: ForceSend doesn't already do this..?
            if ((msg.Targets?.Length ?? 0) == 0)
                return;

            DataInternalBlob blob = new(env.Server.Data, msg);
            foreach (CelesteNetPlayerSession other in others)
                other.Con.Send(blob);
        }

19 Source : ChatCMDGlobalChat.cs
with MIT License
from 0x0ade

public override void ParseAndRun(ChatCMDEnv env) {
            CelesteNetPlayerSession? session = env.Session;
            if (session == null)
                return;

            string text = env.Text.Trim();

            if (string.IsNullOrEmpty(text)) {
                Chat.Commands.Get<ChatCMDChannelChat>().ParseAndRun(env);
                return;
            }

            DataPlayerInfo? player = env.Player;
            if (player == null)
                return;

            DataChat? msg = Chat.PrepareAndLog(null, new DataChat {
                Player = player,
                Text = text
            });

            if (msg == null)
                return;

            env.Msg.Text = text;
            env.Msg.Tag = "";
            env.Msg.Color = Color.White;
            env.Msg.Target = null;
            Chat.ForceSend(env.Msg);
        }

19 Source : ChatModule.cs
with MIT License
from 0x0ade

private void OnSessionEnd(CelesteNetPlayerSession session, DataPlayerInfo? lastPlayerInfo) {
            string? displayName = lastPlayerInfo?.DisplayName;
            if (!displayName.IsNullOrEmpty()) {
                string? reason = new DynamicData(session).Get<string>("leaveReason");
                if (Settings.GreetPlayers || !string.IsNullOrEmpty(reason))
                    Broadcast((reason ?? Settings.MessageLeave).InjectSingleValue("player", displayName));
            }
            session.Remove<SpamContext>(this)?.Dispose();
        }

19 Source : WSCMDUnban.cs
with MIT License
from 0x0ade

public override object? Run(string uid) {
            if ((uid = uid?.Trim() ?? "").IsNullOrEmpty())
                return null;

            Frontend.Server.UserData.Delete<BanInfo>(uid);
            Frontend.BroadcastCMD(true, "update", "/userinfos");

            return null;
        }

19 Source : SqliteUserData.cs
with MIT License
from 0x0ade

public override string Create(string uid) {
            lock (GlobalLock) {
                string key = GetKey(uid);
                if (!key.IsNullOrEmpty())
                    return key;

                string keyFull;
                do {
                    keyFull = Guid.NewGuid().ToString().Replace("-", "");
                    key = keyFull.Substring(0, 16);
                } while (!GetUID(key).IsNullOrEmpty());

                using MiniCommand mini = new(this) {
                    SqliteOpenMode.ReadWrite,
                    @"
                        REPLACE INTO meta (uid, key, keyfull, registered)
                        VALUES ($uid, $key, $keyfull, 1);
                    ",
                    { "$uid", uid },
                    { "$key", key },
                    { "$keyfull", keyFull },
                };
                mini.Run();

                return key;
            }
        }

19 Source : Protocol16Serializer.cs
with MIT License
from 0blu

private static void SerializeOperationResponse(Protocol16Stream output, OperationResponse data, bool writeTypeCode)
        {
            output.WriteTypeCodeIfTrue(Protocol16Type.OperationResponse, writeTypeCode);
            output.WriteByte(data.OperationCode);
            SerializeShort(output, data.ReturnCode, false);
            if (string.IsNullOrEmpty(data.DebugMessage))
            {
                output.WriteTypeCodeIfTrue(Protocol16Type.Null, true);
            }
            else
            {
                // WTF ExitGames, why did you set the writeCode to false?!
                SerializeString(output, data.DebugMessage, true);
            }
            SerializeParameterTable(output, data.Parameters);
        }

19 Source : UIColor.cs
with GNU Affero General Public License v3.0
from 0ceal0t

public static ElementColor GetColor(string colorName, ElementColor defaultColor) {
            if (string.IsNullOrEmpty(colorName)) return defaultColor;
            return AllColors.TryGetValue(colorName, out var newColor) ? newColor : defaultColor;
        }

19 Source : SozlukDataStore.cs
with MIT License
from 0ffffffffh

public static bool AddEntry(Entry entry)
        {
            bool result;

            if (string.IsNullOrEmpty(entry.Content))
                return false;

            SqlServerIo sql = SqlServerIo.Create();

            if (!sql.Ready)
                return false;

            //naa
            entry.FixForMultipleLineFeeds();

            result = sql.Execute(false, NEW_ENTRY_SQL, entry.Baslik,entry.Suser,entry.Date.ToString(),entry.Content);

            if (result)
            {
                
                if (!sql.Read())
                    result = false;
                else
                {
                    entry.SetId(sql.GetValueOfColumn<int>("BaslikId"));

                    
                    CacheManager.InvalidateCacheSet(KeysetId.Baslik(entry.BaslikID));

                    var indexKeyid = KeysetId.Index(entry.Baslik[0]);
                    CacheManager.InvalidateCacheSet(indexKeyid);
                    
                    if (sql.GetValueOfColumn<int>("IsNewBaslikInsert") == 1)
                    {
                        //invalidate also todays section keyset a.k.a Taze
                        CacheManager.InvalidateCacheSet(KeysetId.Todays());
                    }
                }
                
            }


            SqlServerIo.Release(sql);

            return result;
        }

19 Source : SozlukDataStore.cs
with MIT License
from 0ffffffffh

public static SearchAndIndexQueryResult FetchBasliks(string index, int pageNumber, string pagerHash)
        {
            DateTime begin, end;
            
            //fresh contents
            if (string.IsNullOrEmpty(index))
            {
                GetTodaysDateRange(out begin, out end);

                return FetchBasliksUsingSearch(true,string.Empty, string.Empty, begin, end, pageNumber,pagerHash,true);
            }

            index = index.ToLower();

            if (index == "all")
                return FetchBasliksIndexed(pageNumber,'.',pagerHash);

            if (index == "*")
                return FetchBasliksIndexed(pageNumber, '*',pagerHash);

            if (index[0] >= 'a' && index[0] <= 'z')
                return FetchBasliksIndexed(pageNumber, index[0],pagerHash);

            return new SearchAndIndexQueryResult();
        }

19 Source : IndexAndSearchHandler.cs
with MIT License
from 0ffffffffh

private void HandleIndexing()
        {
            int pageNum;
            string pagerHash;
            string indexVal;

            SearchAndIndexQueryResult result;

            pageNum = GetValue<int>("pagenum");
            pagerHash = GetValue<string>("ph");
            indexVal = GetValue<string> ("index");

            if (!string.IsNullOrEmpty(pagerHash) && IsValidPagerHash(pagerHash))
            {
                PushResponseItem("LogicalEntryCount", 0);
                return;
            }

            if (pageNum > 0)
                pageNum--;
            else
                pageNum = 0;

            result = SozlukDataStore.FetchBasliks(indexVal, pageNum,pagerHash);

            if (result.HasEntry)
            {
                PushResponseItem("TotalRecordCount", result.TotalRecordCount);
                PushResponseItem("LogicalEntryCount", result.LogicalRecordCount);
                PushResponseItem("PhysicalEntryCount", result.PhysicalRecordCount);
                PushResponseItem("TotalPageCount", SozlukDataStore.CalcPageCount(result.TotalRecordCount,RecordPerPageType.Basliks));
                PushResponseItem("CurrentPageNum", pageNum + 1);

                if (!string.IsNullOrEmpty(result.PagerHash))
                    PushResponseItem("PagerHash", result.PagerHash);

                foreach (var entry in result.Entries)
                    PushResponseContent(entry.GetTransportString());


                result.Entries.Clear();
                result.Entries = null;
            }
            else
            {
                PushResponseItem("LogicalEntryCount", 0);
            }

        }

19 Source : IndexAndSearchHandler.cs
with MIT License
from 0ffffffffh

private void HandleIndexing()
        {
            int pageNum;
            string pagerHash;
            string indexVal;

            SearchAndIndexQueryResult result;

            pageNum = GetValue<int>("pagenum");
            pagerHash = GetValue<string>("ph");
            indexVal = GetValue<string> ("index");

            if (!string.IsNullOrEmpty(pagerHash) && IsValidPagerHash(pagerHash))
            {
                PushResponseItem("LogicalEntryCount", 0);
                return;
            }

            if (pageNum > 0)
                pageNum--;
            else
                pageNum = 0;

            result = SozlukDataStore.FetchBasliks(indexVal, pageNum,pagerHash);

            if (result.HasEntry)
            {
                PushResponseItem("TotalRecordCount", result.TotalRecordCount);
                PushResponseItem("LogicalEntryCount", result.LogicalRecordCount);
                PushResponseItem("PhysicalEntryCount", result.PhysicalRecordCount);
                PushResponseItem("TotalPageCount", SozlukDataStore.CalcPageCount(result.TotalRecordCount,RecordPerPageType.Basliks));
                PushResponseItem("CurrentPageNum", pageNum + 1);

                if (!string.IsNullOrEmpty(result.PagerHash))
                    PushResponseItem("PagerHash", result.PagerHash);

                foreach (var entry in result.Entries)
                    PushResponseContent(entry.GetTransportString());


                result.Entries.Clear();
                result.Entries = null;
            }
            else
            {
                PushResponseItem("LogicalEntryCount", 0);
            }

        }

See More Examples