/// <summary>
        /// 添加待办事项
        /// </summary>
        /// <returns></returns>
        private async Task AddOrRestoreAndSyncNewToDo(int?category = null)
        {
            ShowNoItems = Visibility.Collapsed;

            EditedToDo.ID = Guid.NewGuid().ToString();
            if (category == null)
            {
                EditedToDo.Category = CateVM.Categories[AddingCate].CateColorID;
            }

            //0 for insert,1 for add
            if (!AppSettings.Instance.IsAddToBottom)
            {
                AllToDos.Insert(0, EditedToDo);
            }
            else
            {
                AllToDos.Add(EditedToDo);
            }

            //序列化保存
            await SerializerHelper.SerializerToJson <ObservableCollection <ToDo> >(AllToDos, SerializerFileNames.ToDoFileName);

            //更新磁贴
            Messenger.Default.Send(new GenericMessage <ObservableCollection <ToDo> >(AllToDos), MessengerTokens.UpdateTile);

            //离线模式,还没有登录过
            if (App.IsInOfflineMode)
            {
                IsLoading = Visibility.Collapsed;
            }
            //登录过的,但是没有网络
            else if (App.IsNoNetwork && !App.IsInOfflineMode)
            {
                StagedToDos.Add(EditedToDo);
                await SerializerHelper.SerializerToJson <ObservableCollection <ToDo> >(StagedToDos, SerializerFileNames.StageFileName);
            }
            //登录过的,有网络
            else if (App.CanSendRequest)
            {
                try
                {
                    //在线模式
                    //发送请求
                    var result = await CloudService.AddSchedule(EditedToDo.Content, "0", EditedToDo.Category.ToString());

                    if (!string.IsNullOrEmpty(result))
                    {
                        ////发送当前的顺序
                        await CloudService.SetAllOrder(ToDo.GetCurrentOrderString(AllToDos));
                    }
                    else
                    {
                        StagedToDos.Add(EditedToDo);
                    }
                }
                catch (Exception)
                {
                    StagedToDos.Add(EditedToDo);
                }
            }
            EditedToDo = new ToDo();
            IsLoading  = Visibility.Collapsed;
            UpdateListByChangingSelectedCate();
            UpdateUndoneCount();
        }
Example #2
0
        /// <summary>
        /// NeuChar 请求
        /// </summary>
        public virtual IResponseMessageBase OnNeuCharRequest(RequestMessageNeuChar requestMessage)
        {
            try
            {
                var    path   = ServerUtility.ContentRootMapPath("~/App_Data/NeuChar");
                var    file   = Path.Combine(path, "NeuCharRoot.config");
                string result = null;

                switch (requestMessage.NeuCharMessageType)
                {
                case NeuCharActionType.GetConfig:
                {
                    if (File.Exists(file))
                    {
                        using (var fs = FileHelper.GetFileStream(file))
                        {
                            using (var sr = new StreamReader(fs, Encoding.UTF8))
                            {
                                var json = sr.ReadToEnd();
                                result = json;
                            }
                        }
                    }
                    else
                    {
                        result = "{}";        //TODO:初始化一个对象
                    }
                }
                break;

                case NeuCharActionType.SaveConfig:
                {
                    var configRootJson = requestMessage.ConfigRoot;
                    SenparcTrace.SendCustomLog("收到NeuCharRequest", configRootJson);
                    var configRoot = SerializerHelper.GetObject <ConfigRoot>(configRootJson);       //这里只做序列化校验

                    //TODO:进行验证


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

                    var fileBak = Path.Combine(path, "NeuCharRoot.bak.config");
                    //TODO:后期也可以考虑把不同模块分离到不同的文件中

                    File.Delete(fileBak);

                    using (var fs = new FileStream(fileBak, FileMode.CreateNew))
                    {
                        using (var sw = new StreamWriter(fs))
                        {
                            sw.Write(configRootJson);
                            sw.Flush();
                        }
                    }

                    //替换备份文件
                    File.Delete(file);
                    File.Move(fileBak, file);

                    //刷新数据
                    var neuralSystem = NeuralSystem.Instance;
                    neuralSystem.ReloadNode();
                }
                break;

                default:
                    break;
                }


                var successMsg = new
                {
                    success = true,
                    result  = result
                };
                TextResponseMessage = successMsg.ToJson();
            }
            catch (Exception ex)
            {
                var errMsg = new
                {
                    success = false,
                    result  = ex.Message
                };
                TextResponseMessage = errMsg.ToJson();
            }

            return(null);
        }
Example #3
0
        private void loadButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDlg = new OpenFileDialog();

            openFileDlg.Filter = "*.xml|*.xml";
            if (openFileDlg.ShowDialog().Value)
            {
                try
                {
                    string path           = System.IO.Path.GetDirectoryName(openFileDlg.FileName);
                    string backgroundPath = System.IO.Path.Combine(path, "Background");
                    string goodsPath      = System.IO.Path.Combine(path, "Goods");
                    string musicPath      = System.IO.Path.Combine(path, "Music");

                    ReadCountStageCollection stages = SerializerHelper <ReadCountStageCollection> .XmlDeserialize(openFileDlg.FileName);

                    foreach (ReadCountStage stage in stages.StageCollection)
                    {
                        this.stageCollection.Add(stage);

                        bool found = false;
                        stage.BackgroundImage = System.IO.Path.Combine(backgroundPath, stage.BackgroundImage);
                        foreach (ImageItem bk in this.backgroundImageCollection)
                        {
                            if (bk.File == stage.BackgroundImage)
                            {
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            ImageItem bkItem = new ImageItem();
                            bkItem.File  = stage.BackgroundImage;
                            bkItem.Title = System.IO.Path.GetFileNameWithoutExtension(bkItem.File);
                            this.backgroundImageCollection.Add(bkItem);
                        }

                        foreach (ReadCountItem item in stage.Items)
                        {
                            item.GoodsImage = System.IO.Path.Combine(goodsPath, item.GoodsImage);

                            found = false;
                            foreach (ImageItem temp in this.goodsImageCollection)
                            {
                                if (temp.File == item.GoodsImage)
                                {
                                    found = true;
                                    break;
                                }
                            }

                            if (found)
                            {
                                continue;
                            }

                            ImageItem imageItem = new ImageItem();
                            imageItem.File  = item.GoodsImage;
                            imageItem.Title = System.IO.Path.GetFileNameWithoutExtension(imageItem.File);
                            this.goodsImageCollection.Add(imageItem);
                        }
                    }

                    for (int i = 0; i < stages.BackgroundMusicList.Count; i++)
                    {
                        stages.BackgroundMusicList[i] = System.IO.Path.Combine(musicPath, stages.BackgroundMusicList[i]);
                        ImageItem musicItem = new ImageItem();
                        musicItem.File  = stages.BackgroundMusicList[i];
                        musicItem.Title = System.IO.Path.GetFileName(stages.BackgroundMusicList[i]);
                        this.musicCollection.Add(musicItem);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
 public CollectionExpression(CollectionNamespace collectionNamespace, IBsonSerializer itemSerializer)
 {
     _collectionNamespace = Ensure.IsNotNull(collectionNamespace, nameof(collectionNamespace));
     _serializer          = SerializerHelper.CreateEnumerableSerializer(Ensure.IsNotNull(itemSerializer, nameof(itemSerializer)));
 }
Example #5
0
 public void SetStatus(string result)
 {
     this.status = SerializerHelper.DeserializeFromString <SongRequestCurrentlyPlayingModel>(result);
 }
Example #6
0
        private static async Task Version5Upgrade(int version, string filePath)
        {
            if (version < 5)
            {
                LegacyDesktopChannelSettings legacySettings = await SerializerHelper.DeserializeFromFile <LegacyDesktopChannelSettings>(filePath);

                DesktopChannelSettings settings = await SerializerHelper.DeserializeFromFile <DesktopChannelSettings>(filePath);

                await ChannelSession.Services.Settings.Initialize(settings);

                foreach (string quote in legacySettings.quotesInternal)
                {
                    settings.UserQuotes.Add(new UserQuoteViewModel(quote));
                }

                List <CommandBase> commands = new List <CommandBase>();
                commands.AddRange(settings.ChatCommands);
                commands.AddRange(settings.InteractiveCommands);
                commands.AddRange(settings.EventCommands);
                commands.AddRange(settings.TimerCommands);

                UserCurrencyViewModel currency = settings.Currencies.Values.FirstOrDefault(c => !c.IsRank);
                if (currency == null)
                {
                    currency = settings.Currencies.Values.FirstOrDefault();
                }

                foreach (CommandBase command in commands)
                {
                    foreach (ActionBase action in command.Actions)
                    {
                        if (action is InteractiveAction)
                        {
                            InteractiveAction nAction = (InteractiveAction)action;
#pragma warning disable CS0612 // Type or member is obsolete
                            if (nAction.AddUserToGroup)
                            {
                                nAction.InteractiveType = InteractiveActionTypeEnum.MoveUserToGroup;
                            }
                            else
                            {
                                nAction.InteractiveType = InteractiveActionTypeEnum.MoveGroupToScene;
                            }
                            nAction.SceneID = nAction.MoveGroupToScene;
#pragma warning restore CS0612 // Type or member is obsolete
                        }

                        if (currency != null)
                        {
                            if (action is ChatAction)
                            {
                                ChatAction nAction = (ChatAction)action;
                                nAction.ChatText = nAction.ChatText.Replace("$usercurrencyname", currency.Name);
                            }
                            else if (action is CurrencyAction)
                            {
                                CurrencyAction nAction = (CurrencyAction)action;
                                nAction.ChatText = nAction.ChatText.Replace("$usercurrencyname", currency.Name);
                            }
                            else if (action is OBSStudioAction)
                            {
                                OBSStudioAction nAction = (OBSStudioAction)action;
                                if (!string.IsNullOrEmpty(nAction.SourceText))
                                {
                                    nAction.SourceText = nAction.SourceText.Replace("$usercurrencyname", currency.Name);
                                }
                            }
                            else if (action is OverlayAction)
                            {
                                OverlayAction nAction = (OverlayAction)action;
                                if (!string.IsNullOrEmpty(nAction.Text))
                                {
                                    nAction.Text = nAction.Text.Replace("$usercurrencyname", currency.Name);
                                }
                            }
                            else if (action is TextToSpeechAction)
                            {
                                TextToSpeechAction nAction = (TextToSpeechAction)action;
                                nAction.SpeechText = nAction.SpeechText.Replace("$usercurrencyname", currency.Name);
                            }
                            else if (action is XSplitAction)
                            {
                                XSplitAction nAction = (XSplitAction)action;
                                if (!string.IsNullOrEmpty(nAction.SourceText))
                                {
                                    nAction.SourceText = nAction.SourceText.Replace("$usercurrencyname", currency.Name);
                                }
                            }
                        }
                    }
                }

                foreach (GameCommandBase game in settings.GameCommands)
                {
                    if (game is IndividualProbabilityGameCommand)
                    {
                        IndividualProbabilityGameCommand individualGame = (IndividualProbabilityGameCommand)game;
                        DesktopSettingsUpgrader.SetAllGameChatActionsToWhispers(individualGame.UserJoinedCommand);
                        DesktopSettingsUpgrader.SetAllGameChatActionsToWhispers(individualGame.LoseLeftoverCommand);
                        foreach (GameOutcome outcome in individualGame.Outcomes)
                        {
                            DesktopSettingsUpgrader.SetAllGameChatActionsToWhispers(outcome.ResultCommand);
                        }
                    }
                    else if (game is OnlyOneWinnerGameCommand)
                    {
                        OnlyOneWinnerGameCommand oneWinnerGame = (OnlyOneWinnerGameCommand)game;
                        DesktopSettingsUpgrader.SetAllGameChatActionsToWhispers(oneWinnerGame.UserJoinedCommand);
                    }
                }

                await ChannelSession.Services.Settings.Save(settings);
            }
        }
 protected SerializerStreamDataContract(IEnumerable <Type> knownTypes)
     : base(knownTypes ?? SerializerHelper.GetSerializableTypes())
 {
 }
Example #8
0
 /// <summary>
 /// Convert a <see cref="ValueArray{String}"/> to the JSON format
 /// </summary>
 /// <param name="valueArray">The <see cref="ValueArray{String}"/></param>
 /// <returns>The JSON string</returns>
 public static string ToHstoreString(this ValueArray <string> valueArray) =>
 SerializerHelper.ToHstoreString(valueArray);
 public Task <Report> RenderByNameAsync(string templateName, object data, CancellationToken ct = default(CancellationToken))
 {
     return(RenderAsync(SerializerHelper.SerializeRenderRequestForName(templateName, data, _dataContractResolver), ct));
 }
 /// <summary>
 /// 序列化的类型是否完整支持
 /// </summary>
 /// <param name="checkType"></param>
 /// <param name="classFullName"></param>
 /// <returns></returns>
 bool isSysSuport(Type checkType, string classFullName = null)
 {
     //ITuple
     if (typeof(ITuple).IsAssignableFrom(checkType))
     {
         return(true);
     }
     if (classFullName == null)
     {
         classFullName = Utils.GetFullName(checkType);
     }
     //基本类型
     if (SerializerHelper.IsSuportSerializerHelper(classFullName))
     {
         return(true);
     }
     //枚举
     if (SerializerHelper.IsEnumSuportSerializerHelper(checkType))
     {
         return(true);
     }
     //可空类型
     if (Utils.IsNullable(checkType))
     {
         return(true);
     }
     if (checkType.IsArray)
     {
         return(true);
     }
     if (checkType.IsGenericType)
     {
         var arguments = checkType.GetGenericArguments();
         if (arguments.Length == 1)
         {
             if (typeof(ISet <>).MakeGenericType(arguments).IsAssignableFrom(checkType))
             {
                 return(true);
             }
             else if (typeof(IList <>).MakeGenericType(arguments).IsAssignableFrom(checkType))
             {
                 return(true);
             }
             else if (typeof(IEnumerable <>).MakeGenericType(arguments).IsAssignableFrom(checkType))
             {
                 return(true);
             }
         }
         //字典
         else if (arguments.Length == 2)
         {
             if (typeof(KeyValuePair <,>).MakeGenericType(arguments).IsAssignableFrom(checkType))
             {
                 return(true);
             }
             else if (typeof(SortedList <,>).MakeGenericType(arguments).IsAssignableFrom(checkType))
             {
                 return(true);
             }
             else if (typeof(IDictionary <,>).MakeGenericType(arguments).IsAssignableFrom(checkType))
             {
                 return(true);
             }
         }
     }
     return(false);
 }
 public Task <Report> RenderAsync(object request, CancellationToken ct = default(CancellationToken))
 {
     return(RenderAsync(SerializerHelper.SerializeRenderRequest(request, _dataContractResolver), ct));
 }
 public Task <Report> RenderAsync(string templateShortid, string jsonData, CancellationToken ct = default(CancellationToken))
 {
     return(RenderAsync(SerializerHelper.SerializeRenderRequest(templateShortid, jsonData, _dataContractResolver), ct));
 }
Example #13
0
        public ActionResult <SalesRoot> GetSalesFromXML(string base64Xml)
        {
            var xmlString = Encoding.UTF8.GetString(Convert.FromBase64String(base64Xml));

            return(SerializerHelper.StringToObject <SalesRoot>(xmlString));
        }
Example #14
0
 public void SaveConfig(string file)
 {
     SerializerHelper.SaveAsXml(this, file);
 }
Example #15
0
        };                                                                                                                  //EncryptionPolicy = new TableEncryptionPolicy()

        public AzureTableStorageCacheClient(string connectionString, ISerializer <string> serializer, ILogger <AzureTableStorageCacheClient> logger, string tableName = _defaultTableName, string defaultPartitionKey = _defaultDefaultPartitionKey, bool throwOnError = false)
            : this(connectionString, SerializerHelper.WrapSerializer(serializer), tableName, defaultPartitionKey, logger, throwOnError)
        {
            _isBinarySerializer = false;
        }
Example #16
0
 /// <summary>
 /// Convert a string to a <see cref="ValueArray{T}"/>
 /// </summary>
 /// <typeparam name="T">The generic type of the <see cref="ValueArray{T}"/></typeparam>
 /// <param name="valueArrayString">The string to convert</param>
 /// <returns>The <see cref="ValueArray{T}"/></returns>
 public static ValueArray <T> FromHstoreToValueArray <T>(this string valueArrayString) =>
 SerializerHelper.FromHstoreToValueArray <T>(valueArrayString);
Example #17
0
 public AzureTableStorageCacheClient(CloudStorageAccount account, ISerializer <byte[]> serializer, ILogger <AzureTableStorageCacheClient> logger, string tableName = _defaultTableName, string defaultPartitionKey = _defaultDefaultPartitionKey, bool throwOnError = false)
     : this(account, SerializerHelper.WrapSerializer(serializer), tableName, defaultPartitionKey, logger, throwOnError)
 {
     _isBinarySerializer = true;
 }
Example #18
0
        /// <summary>
        /// 处理图文消息
        /// </summary>
        /// <param name="originContent">id|id|id</param>
        /// <param name="data">素材资源库</param>
        /// <returns></returns>
        public static List <Article> FillNewsMessage(string originContent, MaterialData data)
        {
            if (originContent.IsNullOrWhiteSpace())
            {
                return(null);
            }

            //var firstMaterialId = originContent.Split('|')?[0];


            List <Article> articleList = new List <Article>();

            var material = data.FirstOrDefault(z => z.Id == originContent);

            if (material == null)
            {
                return(null);
            }

            var articleData = SerializerHelper.GetObject <ArticleData>(material.Content);//获取主文章(第一篇图文)内容

            if (articleData != null && articleData.ArticleIds != null)
            {
                for (int i = 0; i < articleData.ArticleIds.Count; i++)
                {
                    ArticleData articleItem = null;
                    string      materialId  = null;
                    if (i == 0)
                    {
                        articleItem = articleData;//第一项就是自己
                        materialId  = material.Id;
                    }
                    else
                    {
                        var materialItem = data.FirstOrDefault(z => z.Id == articleData.ArticleIds[i]);//后续选项从素材中查找
                        if (materialItem != null)
                        {
                            articleItem = SerializerHelper.GetObject <ArticleData>(materialItem.Content);
                            if (articleItem == null)
                            {
                                continue;
                            }
                            materialId = materialItem.Id;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    var article = new Article()
                    {
                        Title       = articleItem?.Title,
                        PicUrl      = articleItem?.ThumbCoverUrl,
                        Description = articleItem?.Digest,
                        //   Url = $"http://neuchar.senparc.com/Material/Details?uniqueId={articleItem.ArticleIds[0]}"
                    };

                    if (articleItem.ContentSourceUrl.IsNullOrWhiteSpace())
                    {
                        article.Url = $"http://neuchar.senparc.com/WX/Material/Details?uniqueId={materialId}";
                    }
                    else
                    {
                        article.Url = articleItem.ContentSourceUrl;
                    }

                    articleList.Add(article);
                }
            }

            return(articleList.Count > 0 ? articleList : null);//TODO:可以返回一条默认有好消息

            //var list = SerializerHelper.GetObject<List<Article>>(originContent);

            //foreach (var item in list)
            //{
            //    item.Title = FillTextMessage(item.Title);
            //    item.Description = FillTextMessage(item.Description);
            //}

            //return list;
        }
Example #19
0
        protected void PopulateColumnsForTable(DataSourceTable DataSourceTable)
        {
            var tableModel = _tableModels.Single(x => x.TableName == DataSourceTable.TableName);

            DataSourceTable.Columns = SerializerHelper.Serialize(tableModel.Columns);
        }
Example #20
0
        private static async Task Version4Upgrade(int version, string filePath)
        {
            if (version < 4)
            {
                string data = File.ReadAllText(filePath);
                data = data.Replace("MixItUp.Base.Actions.RankAction", "MixItUp.Base.Actions.CurrencyAction");
                data = data.Replace("\"Type\": 13\n", "\"Type\": 1\n");
                File.WriteAllText(filePath, data);

                LegacyDesktopChannelSettings legacySettings = await SerializerHelper.DeserializeFromFile <LegacyDesktopChannelSettings>(filePath);

                legacySettings.InitializeDB = false;

                List <LegacyUserDataViewModel> legacyUsers = new List <LegacyUserDataViewModel>();
                if (legacySettings.IsStreamer)
                {
                    string dbPath = ((DesktopSettingsService)ChannelSession.Services.Settings).GetDatabaseFilePath(legacySettings);
                    SQLiteDatabaseWrapper databaseWrapper = new SQLiteDatabaseWrapper(dbPath);
                    await databaseWrapper.RunReadCommand("SELECT * FROM Users", (SQLiteDataReader dataReader) =>
                    {
                        LegacyUserDataViewModel userData = new LegacyUserDataViewModel(dataReader);
                        legacyUsers.Add(userData);
                    });

                    File.Copy(DesktopSettingsService.SettingsTemplateDatabaseFileName, dbPath, overwrite: true);
                }

                await ChannelSession.Services.Settings.Initialize(legacySettings);

                DesktopChannelSettings settings = await SerializerHelper.DeserializeFromFile <DesktopChannelSettings>(filePath);

                settings.InitializeDB = false;
                await ChannelSession.Services.Settings.Initialize(settings);

                UserCurrencyViewModel currency = null;
                UserCurrencyViewModel rank     = null;
                if (settings.IsStreamer)
                {
                    if (!string.IsNullOrEmpty(legacySettings.CurrencyAcquisition.Name))
                    {
                        currency = legacySettings.CurrencyAcquisition;
                        currency.SpecialIdentifier = SpecialIdentifierStringBuilder.ConvertToSpecialIdentifier(currency.Name);
                        settings.Currencies.Add(legacySettings.CurrencyAcquisition.ID, legacySettings.CurrencyAcquisition);
                    }

                    if (!string.IsNullOrEmpty(legacySettings.RankAcquisition.Name))
                    {
                        rank = legacySettings.RankAcquisition;
                        rank.SpecialIdentifier  = SpecialIdentifierStringBuilder.ConvertToSpecialIdentifier(rank.Name);
                        rank.Ranks              = legacySettings.Ranks;
                        rank.RankChangedCommand = legacySettings.RankChangedCommand;
                        settings.Currencies.Add(legacySettings.RankAcquisition.ID, legacySettings.RankAcquisition);
                    }

                    foreach (LegacyUserDataViewModel user in legacyUsers)
                    {
                        settings.UserData[user.ID] = user;
                        if (rank != null)
                        {
                            settings.UserData[user.ID].SetCurrencyAmount(rank, user.RankPoints);
                        }
                        if (currency != null)
                        {
                            settings.UserData[user.ID].SetCurrencyAmount(currency, user.CurrencyAmount);
                        }
                    }

                    if (currency != null)
                    {
                        if (legacySettings.GiveawayCurrencyCost > 0)
                        {
                            settings.GiveawayCurrencyRequirement = new UserCurrencyRequirementViewModel(currency, legacySettings.GiveawayCurrencyCost);
                        }
                        if (legacySettings.GameQueueCurrencyCost > 0)
                        {
                            settings.GameQueueCurrencyRequirement = new UserCurrencyRequirementViewModel(currency, legacySettings.GameQueueCurrencyCost);
                        }
                    }

                    if (rank != null)
                    {
                        if (legacySettings.GiveawayUserRank != null && rank.Ranks.Any(r => r.Name.Equals(legacySettings.GiveawayUserRank)))
                        {
                            settings.GiveawayRankRequirement = new UserCurrencyRequirementViewModel(rank, rank.Ranks.FirstOrDefault(r => r.Name.Equals(legacySettings.GiveawayUserRank)));
                        }
                        if (legacySettings.GameQueueMinimumRank != null)
                        {
                            settings.GameQueueRankRequirement = new UserCurrencyRequirementViewModel(rank, legacySettings.GameQueueMinimumRank);
                        }
                    }
                }

                List <CommandBase> commands = new List <CommandBase>();
                commands.AddRange(settings.ChatCommands);
                commands.AddRange(settings.InteractiveCommands);
                commands.AddRange(settings.EventCommands);
                commands.AddRange(settings.TimerCommands);

                foreach (CommandBase command in commands)
                {
                    foreach (ActionBase action in command.Actions)
                    {
                        if (action is ChatAction)
                        {
                            ChatAction nAction = (ChatAction)action;
                            nAction.ChatText = DesktopSettingsUpgrader.ReplaceSpecialIdentifiersVersion4(nAction.ChatText, currency, rank);
                        }
                        else if (action is CurrencyAction)
                        {
                            CurrencyAction nAction = (CurrencyAction)action;
                            nAction.ChatText = DesktopSettingsUpgrader.ReplaceSpecialIdentifiersVersion4(nAction.ChatText, currency, rank);
                        }
                        else if (action is OBSStudioAction)
                        {
                            OBSStudioAction nAction = (OBSStudioAction)action;
                            nAction.SourceText = DesktopSettingsUpgrader.ReplaceSpecialIdentifiersVersion4(nAction.SourceText, currency, rank);
                        }
                        else if (action is OverlayAction)
                        {
                            OverlayAction nAction = (OverlayAction)action;
                            nAction.ImagePath = DesktopSettingsUpgrader.ReplaceSpecialIdentifiersVersion4(nAction.ImagePath, currency, rank);
                            nAction.Text      = DesktopSettingsUpgrader.ReplaceSpecialIdentifiersVersion4(nAction.Text, currency, rank);
                        }
                        else if (action is TextToSpeechAction)
                        {
                            TextToSpeechAction nAction = (TextToSpeechAction)action;
                            nAction.SpeechText = DesktopSettingsUpgrader.ReplaceSpecialIdentifiersVersion4(nAction.SpeechText, currency, rank);
                        }
                        else if (action is XSplitAction)
                        {
                            XSplitAction nAction = (XSplitAction)action;
                            nAction.SourceText = DesktopSettingsUpgrader.ReplaceSpecialIdentifiersVersion4(nAction.SourceText, currency, rank);
                        }
                    }
                }

                if (settings.IsStreamer)
                {
                    foreach (ChatCommand command in settings.ChatCommands)
                    {
#pragma warning disable CS0612 // Type or member is obsolete
                        if (command.CurrencyCost > 0)
                        {
                            command.CurrencyRequirement = new UserCurrencyRequirementViewModel(currency, command.CurrencyCost);
                        }
#pragma warning restore CS0612 // Type or member is obsolete
                    }
                }

                await ChannelSession.Services.Settings.Save(settings);
            }
        }
Example #21
0
        private void SerializeDockPanel(string path)
        {
            var state = mainDockPanel.GetDockPanelState();

            SerializerHelper.Serialize(state, path);
        }
Example #22
0
        private static async Task Version2Upgrade(int version, string filePath)
        {
            if (version < 2)
            {
                string data = File.ReadAllText(filePath);
                data = data.Replace("interactiveControlsInternal", "interactiveCommandsInternal");
                data = data.Replace("CapsBlockCount", "ModerationCapsBlockCount");
                data = data.Replace("PunctuationBlockCount", "ModerationPunctuationBlockCount");
                data = data.Replace("EmoteBlockCount", "ModerationEmoteBlockCount");
                data = data.Replace("BlockLinks", "ModerationBlockLinks");
                data = data.Replace("Timeout1MinuteOffenseCount", "ModerationTimeout1MinuteOffenseCount");
                data = data.Replace("Timeout5MinuteOffenseCount", "ModerationTimeout5MinuteOffenseCount");
                File.WriteAllText(filePath, data);

                DesktopChannelSettings settings = await SerializerHelper.DeserializeFromFile <DesktopChannelSettings>(filePath);

                await ChannelSession.Services.Settings.Initialize(settings);

                List <CommandBase> commands = new List <CommandBase>();
                commands.AddRange(settings.ChatCommands);
                commands.AddRange(settings.InteractiveCommands);
                commands.AddRange(settings.EventCommands);
                commands.AddRange(settings.TimerCommands);

                foreach (CommandBase command in commands)
                {
                    foreach (ActionBase action in command.Actions)
                    {
                        if (action is ChatAction)
                        {
                            ChatAction nAction = (ChatAction)action;
                            nAction.ChatText = DesktopSettingsUpgrader.ReplaceSpecialIdentifiersVersion2(nAction.ChatText);
                        }
                        else if (action is CurrencyAction)
                        {
                            CurrencyAction nAction = (CurrencyAction)action;
                            nAction.ChatText = DesktopSettingsUpgrader.ReplaceSpecialIdentifiersVersion2(nAction.ChatText);
                        }
                        else if (action is OBSStudioAction)
                        {
                            OBSStudioAction nAction = (OBSStudioAction)action;
                            nAction.SourceText = DesktopSettingsUpgrader.ReplaceSpecialIdentifiersVersion2(nAction.SourceText);
                        }
                        else if (action is OverlayAction)
                        {
                            OverlayAction nAction = (OverlayAction)action;
                            nAction.ImagePath = DesktopSettingsUpgrader.ReplaceSpecialIdentifiersVersion2(nAction.ImagePath);
                            nAction.Text      = DesktopSettingsUpgrader.ReplaceSpecialIdentifiersVersion2(nAction.Text);
                        }
                        else if (action is TextToSpeechAction)
                        {
                            TextToSpeechAction nAction = (TextToSpeechAction)action;
                            nAction.SpeechText = DesktopSettingsUpgrader.ReplaceSpecialIdentifiersVersion2(nAction.SpeechText);
                        }
                        else if (action is XSplitAction)
                        {
                            XSplitAction nAction = (XSplitAction)action;
                            nAction.SourceText = DesktopSettingsUpgrader.ReplaceSpecialIdentifiersVersion2(nAction.SourceText);
                        }
                    }
                }

                await ChannelSession.Services.Settings.Save(settings);
            }
        }
        public void MergeKey2(string tablename, string indexname, BigEntityTableMeta meta)
        {
            ProcessTraceUtil.StartTrace();

            IndexMergeInfo mergeinfo = null;

            lock (meta)
            {
                mergeinfo = meta.IndexMergeInfos.Find(p => indexname.Equals(p.IndexName));
                if (mergeinfo == null)
                {
                    mergeinfo           = new IndexMergeInfo();
                    mergeinfo.IndexName = indexname;
                    meta.IndexMergeInfos.Add(mergeinfo);
                }

                if (mergeinfo.IsMergin)
                {
                    return;
                }
                meta.NewAddCount   = 0;
                mergeinfo.IsMergin = true;
            }
            DateTime timestart    = DateTime.Now;
            string   newindexfile = string.Empty;

            byte[] bigbuffer   = new byte[1024 * 1024];
            byte[] smallbuffer = new byte[2048];
            try
            {
                ProcessTraceUtil.TraceMem("开始整理key:" + indexname, "m");

                long   lasmargepos      = 0;
                long   newIndexMergePos = mergeinfo.IndexMergePos;
                string indexfile        = indexname.Equals(meta.KeyName) ? GetKeyFile(tablename) : GetIndexFile(tablename, indexname);
                var    tablelocker      = GetKeyLocker(tablename, string.Empty);

                //新的磁盘索引
                List <BigEntityTableIndexItem> newdiskindexlist = new List <BigEntityTableIndexItem>();
                var loadFactor = (int)Math.Max(4, new FileInfo(indexfile).Length / MAX_KEYBUFFER);

                using (var reader = ObjTextReader.CreateReader(indexfile))
                {
                    long readoldstartpostion = reader.ReadedPostion();

                    try
                    {
                        tablelocker.EnterWriteLock();
                        keyindexmemtemplist[tablename] = keyindexmemlist[tablename];
                        keyindexmemlist[tablename]     = new SortArrayList <BigEntityTableIndexItem>();
                    }
                    finally
                    {
                        tablelocker.ExitWriteLock();
                    }
                    var listtemp = keyindexmemtemplist[tablename].GetList().ToList();
                    listtemp = listtemp.Select(p => new BigEntityTableIndexItem
                    {
                        Del        = p.Del,
                        Key        = p.Key,
                        KeyOffset  = p.KeyOffset,
                        len        = p.len,
                        Offset     = p.Offset,
                        Index      = p.Index,
                        RangeIndex = p.RangeIndex
                    }).ToList();
                    int readcount = listtemp.Count;

                    ProcessTraceUtil.TraceMem("从内存中读取新增数据,共" + readcount + "条", "m");

                    if (readcount == 0)
                    {
                        return;
                    }

                    lasmargepos = listtemp.Max(p => p.KeyOffset);
                    reader.SetPostion(lasmargepos);
                    reader.ReadObject <BigEntityTableIndexItem>();
                    lasmargepos = reader.ReadedPostion();

                    //优化确定哪些部分是不需要一个个读入的
                    long copybefore = 0, copylast = 0;
                    long lastrankindex = 0;
                    var  indexarray    = keyindexdisklist[tablename];
                    using (var sortarray = new Collections.SorteArray <BigEntityTableIndexItem>(indexarray))
                    {
                        int mid = -1;
                        int pos = sortarray.Find(listtemp.First(), ref mid);
                        ProcessTraceUtil.Trace("查找新数据在老数中插入的开始位置:mid=" + mid + ",pos=" + pos);
                        if (pos == -1 && mid != -1)
                        {
                            //小于最小的
                            copybefore    = indexarray[mid].KeyOffset;
                            lastrankindex = indexarray[mid].RangeIndex;
                            ProcessTraceUtil.Trace("老数据可以直接copy的部分:0->" + copybefore);
                        }
                        else if (pos != -1)
                        {
                            copybefore    = indexarray[pos].KeyOffset;
                            lastrankindex = indexarray[pos].RangeIndex;
                            ProcessTraceUtil.Trace("老数据可以直接copy的部分:0->" + copybefore);
                        }

                        //优化确定后面读到哪

                        mid = -1;
                        pos = sortarray.Find(listtemp.Last(), ref mid);
                        ProcessTraceUtil.Trace("查找新数据在老数据中插入的结束位置:mid=" + mid + ",pos=" + pos);
                        if (pos == -1 && mid != -1 && mid < indexarray.Length - 1)
                        {
                            //小于最小的
                            copylast = indexarray[mid + 1].KeyOffset;
                            ProcessTraceUtil.Trace("老数据可以直接copy的部分:" + copylast + "->" + mergeinfo.IndexMergePos);
                        }
                        else if (pos != -1)
                        {
                            copylast = indexarray[pos].KeyOffset;
                            ProcessTraceUtil.Trace("老数据可以直接copy的部分:" + copylast + "->" + mergeinfo.IndexMergePos);
                        }
                    }

                    newindexfile = (indexname.Equals(meta.KeyName) ? GetKeyFile(tablename) : GetIndexFile(tablename, indexname)) + ".temp";
                    if (File.Exists(newindexfile))
                    {
                        File.Delete(newindexfile);
                    }
                    //快速copy
                    if (copybefore > 0)
                    {
                        ProcessTraceUtil.TraceMem("直接copy前面不在排序范围的数据:0->" + copybefore, "m");
                        IOUtil.CopyFile(indexfile, newindexfile, FileMode.Create, 0, copybefore - 1);
                        readoldstartpostion = copybefore;
                        ProcessTraceUtil.TraceMem("copy数据完成", "m");

                        newdiskindexlist.AddRange(keyindexdisklist[tablename].Where(p => p.KeyOffset < copybefore));
                    }

                    bool isall = false;
                    ProcessTraceUtil.TraceMem("开始读取在排序范围内的数据", "m");
                    while (true)
                    {
                        ProcessTraceUtil.Trace("读取老数据,开始位置:" + readoldstartpostion);
                        reader.SetPostion(readoldstartpostion);
                        var  listordered = new List <BigEntityTableIndexItem>();
                        var  loadcount   = 0;
                        long keyoffset   = 0;
                        foreach (var item in reader.ReadObjectsWating <BigEntityTableIndexItem>(1, p => keyoffset = p, bigbuffer))
                        {
                            item.KeyOffset = keyoffset;
                            item.SetIndex(meta.KeyIndexInfo);

                            if (item.KeyOffset >= mergeinfo.IndexMergePos)
                            {
                                break;
                            }
                            if (copylast > 0 && item.KeyOffset >= copylast)
                            {
                                break;
                            }
                            listordered.Add(item);
                            if (++loadcount >= MERGE_TRIGGER_NEW_COUNT)
                            {
                                break;
                            }
                        }

                        readoldstartpostion = reader.ReadedPostion();
                        bool isonlyoldlist = false;

                        if (listordered.Count == 0)
                        {
                            ProcessTraceUtil.TraceMem("老数据没有了,全部是新数据:" + listtemp.Count, "m");

                            listordered = MergeAndSort2(listordered, listtemp).ToList();
                            foreach (var item in listordered)
                            {
                                item.RangeIndex = lastrankindex++;
                            }
                            isall = true;
                        }
                        else if (listtemp.Count == 0 && listordered.Count > 10000)
                        {
                            ProcessTraceUtil.TraceMem("新数据没有了,全部是老数据:" + listordered.Count, "m");
                            //copy
                            IOUtil.CopyFile(indexfile, newindexfile, FileMode.Open, listordered.First().KeyOffset, listordered.Last().KeyOffset - 1, false);
                            var  listorderedlast = listordered.Last();
                            long copyoffset      = 0;
                            using (var nw = ObjTextWriter.CreateWriter(newindexfile, ObjTextReaderWriterEncodeType.entitybuf2))
                            {
                                var item = new BigEntityTableIndexItem {
                                    Del = listorderedlast.Del, Key = listorderedlast.Key, len = listorderedlast.len, Offset = listorderedlast.Offset, Index = listorderedlast.Index
                                };
                                item.KeyOffset = nw.GetWritePosition();

                                copyoffset = nw.GetWritePosition() - listorderedlast.KeyOffset;

                                nw.AppendObject(item);
                                newIndexMergePos = nw.GetWritePosition();
                            }
                            isonlyoldlist = true;
                            //更新索引
                            foreach (var item in listordered)
                            {
                                item.RangeIndex = lastrankindex++;
                                item.KeyOffset += copyoffset;
                            }

                            ProcessTraceUtil.TraceMem("直接copy数据完成", "m");
                        }
                        else
                        {
                            ProcessTraceUtil.TraceMem("老数据条数为:" + listordered.Count + ",新数据条数为:" + listtemp.Count, "m");

                            var listordermax = listordered.Last();

                            int idx = 0;
                            foreach (var item in listtemp)
                            {
                                if (item.CompareTo(listordermax) > 0)
                                {
                                    break;
                                }
                                else
                                {
                                    idx++;
                                }
                            }
                            List <BigEntityTableIndexItem> smalllist = listtemp.Take(idx).ToList();
                            listtemp    = listtemp.Skip(idx).ToList();
                            listordered = MergeAndSort2(listordered, smalllist).ToList();
                            foreach (var item in listordered)
                            {
                                item.RangeIndex = lastrankindex++;

                                //ProcessTraceUtil.Trace("rangeindex:" + item.Key[0] + "->" + (item.RangeIndex));
                            }
                            ProcessTraceUtil.TraceMem("排序完成:" + listordered.Count + "条", "m");
                        }

                        if (listordered.Count > 0)
                        {
                            if (!isonlyoldlist)
                            {
                                ProcessTraceUtil.TraceMem("把排好的数据写入到新索引文件:" + listordered.Count + "条", "m");
                                using (var nw = ObjTextWriter.CreateWriter(newindexfile, ObjTextReaderWriterEncodeType.entitybuf2))
                                {
                                    foreach (var item in listordered)
                                    {
                                        item.KeyOffset = nw.GetWritePosition();
                                        nw.AppendObject(item);
                                    }
                                    newIndexMergePos = nw.GetWritePosition();
                                }
                                ProcessTraceUtil.TraceMem("写入到新索引文件完成", "m");
                            }

                            if (listordered.Count <= 2 || loadFactor == 1)
                            {
                                newdiskindexlist.AddRange(listordered);
                            }
                            else
                            {
                                newdiskindexlist.Add(listordered.First());
                                int idx = 0;
                                foreach (var item in listordered)
                                {
                                    if ((++idx) % loadFactor == 0)
                                    {
                                        newdiskindexlist.Add(item);
                                    }
                                }
                                //newdiskindexlist.AddRange(listordered.Where(p => (++idx) % loadFactor == 0));
                                if (idx % loadFactor != 0)
                                {
                                    newdiskindexlist.Add(listordered.Last());
                                }
                            }
                        }

                        ProcessTraceUtil.TraceMem("写入到新索引文件后整理索引完成", "m");

                        if (isall)
                        {
                            if (copylast > 0 && copylast < mergeinfo.IndexMergePos)
                            {
                                ProcessTraceUtil.TraceMem("copy已排序的大于新增最大数部分" + copylast + "->" + mergeinfo.IndexMergePos, "m");
                                var offset = 0L;
                                using (var nw = ObjTextWriter.CreateWriter(newindexfile, ObjTextReaderWriterEncodeType.entitybuf2))
                                {
                                    offset = nw.GetWritePosition() - copylast;
                                }
                                //copy
                                long newindexpos = IOUtil.CopyFile(indexfile, newindexfile, FileMode.Open, copylast, mergeinfo.IndexMergePos - 1, false);

                                foreach (var p in keyindexdisklist[tablename])
                                {
                                    if (p.KeyOffset >= copylast && p.KeyOffset < mergeinfo.IndexMergePos)
                                    {
                                        newdiskindexlist.Add(new BigEntityTableIndexItem
                                        {
                                            Del        = p.Del,
                                            Key        = p.Key,
                                            KeyOffset  = p.KeyOffset + offset,
                                            len        = p.len,
                                            Offset     = p.Offset,
                                            Index      = p.Index,
                                            RangeIndex = p.RangeIndex + readcount
                                        });
                                    }
                                }

                                ProcessTraceUtil.TraceMem("copy数据完成->" + offset, "m");
                            }
                            break;
                        }
                        else
                        {
                            if (listtemp.Count > 0)
                            {
                                long newcopybefore = 0;
                                using (var sortarray = new Collections.SorteArray <BigEntityTableIndexItem>(indexarray))
                                {
                                    int mid = -1;
                                    int pos = sortarray.Find(listtemp.First(), ref mid);
                                    ProcessTraceUtil.Trace("查找已经排序的小于新增最小数据部分:mid=" + mid + ",pos=" + pos);
                                    if (pos == -1 && mid != -1)
                                    {
                                        //小于最小的
                                        newcopybefore = indexarray[mid].KeyOffset;
                                        lastrankindex = indexarray[mid].RangeIndex + readcount - listtemp.Count;
                                    }
                                    else if (pos != -1)
                                    {
                                        newcopybefore = indexarray[pos].KeyOffset;
                                        lastrankindex = indexarray[pos].RangeIndex + readcount - listtemp.Count;
                                    }
                                }
                                if (newcopybefore > readoldstartpostion)
                                {
                                    ProcessTraceUtil.Trace("中间copy");
                                    var offset = 0L;
                                    using (var nw = ObjTextWriter.CreateWriter(newindexfile, ObjTextReaderWriterEncodeType.entitybuf2))
                                    {
                                        offset = nw.GetWritePosition() - readoldstartpostion;
                                    }
                                    IOUtil.CopyFile(indexfile, newindexfile, FileMode.Open, readoldstartpostion, newcopybefore - 1, false);

                                    foreach (var p in keyindexdisklist[tablename])
                                    {
                                        if (p.KeyOffset >= readoldstartpostion && p.KeyOffset < newcopybefore)
                                        {
                                            newdiskindexlist.Add(new BigEntityTableIndexItem
                                            {
                                                Del        = p.Del,
                                                Key        = p.Key,
                                                KeyOffset  = p.KeyOffset + offset,
                                                len        = p.len,
                                                Offset     = p.Offset,
                                                Index      = p.Index,
                                                RangeIndex = p.RangeIndex + readcount - listtemp.Count
                                            });
                                        }
                                    }

                                    readoldstartpostion = newcopybefore;
                                    ProcessTraceUtil.Trace("中间copy完成");
                                }
                                else if (newcopybefore < readoldstartpostion)
                                {
                                    ProcessTraceUtil.Trace("补中间");
                                    reader.SetPostion(newcopybefore);
                                    //补充数目
                                    foreach (var item in reader.ReadObjectsWating <BigEntityTableIndexItem>(1, p => keyoffset = p, smallbuffer))
                                    {
                                        item.KeyOffset = keyoffset;
                                        item.SetIndex(meta.KeyIndexInfo);
                                        //ProcessTraceUtil.Trace(item.Key[0].ToString());
                                        if (item.KeyOffset >= mergeinfo.IndexMergePos)
                                        {
                                            break;
                                        }
                                        if (copylast > 0 && item.KeyOffset >= copylast)
                                        {
                                            break;
                                        }
                                        if (item.KeyOffset == readoldstartpostion)
                                        {
                                            break;
                                        }
                                        if (item.Del)
                                        {
                                            continue;
                                        }
                                        //ProcessTraceUtil.Trace("补中间+1");
                                        lastrankindex++;
                                    }
                                }
                            }
                            else
                            {
                                ProcessTraceUtil.Trace("中间copy2");
                                var offset = 0L;
                                using (var nw = ObjTextWriter.CreateWriter(newindexfile, ObjTextReaderWriterEncodeType.entitybuf2))
                                {
                                    offset = nw.GetWritePosition() - readoldstartpostion;
                                }
                                IOUtil.CopyFile(indexfile, newindexfile, FileMode.Open, readoldstartpostion, copylast - 1, false);

                                foreach (var p in keyindexdisklist[tablename])
                                {
                                    if (p.KeyOffset >= readoldstartpostion && p.KeyOffset < copylast)
                                    {
                                        newdiskindexlist.Add(new BigEntityTableIndexItem
                                        {
                                            Del        = p.Del,
                                            Key        = p.Key,
                                            KeyOffset  = p.KeyOffset + offset,
                                            len        = p.len,
                                            Offset     = p.Offset,
                                            Index      = p.Index,
                                            RangeIndex = p.RangeIndex + readcount
                                        });
                                    }
                                }

                                readoldstartpostion = copylast;
                                ProcessTraceUtil.Trace("中间copy2完成");
                            }
                        }
                    }
                }

                //后面copy
                string tablefile = GetTableFile(tablename);

                var idxreader = ObjTextReader.CreateReader(indexfile);
                var newwriter = ObjTextWriter.CreateWriter(newindexfile, ObjTextReaderWriterEncodeType.entitybuf2);
                try
                {
                    long nextcopypos = 0;
                    ProcessTraceUtil.TraceMem("读取后面的数据->" + lasmargepos, "m");
                    idxreader.SetPostion(lasmargepos);
                    bool hasitem   = false;
                    bool isfirst   = true;
                    long keyoffset = 0;
                    foreach (var item in idxreader.ReadObjectsWating <BigEntityTableIndexItem>(1, p => keyoffset = p, smallbuffer))
                    {
                        hasitem = true;
                        item.SetIndex(meta.KeyIndexInfo);
                        item.KeyOffset = keyoffset;
                        if (item.KeyOffset > newwriter.GetWritePosition())
                        {
                            var spacelen = item.KeyOffset - newwriter.GetWritePosition();
                            ProcessTraceUtil.Trace("没有对齐,尝试对齐,spacelen->" + spacelen);
                            if (spacelen % 3 == 0)
                            {
                                newwriter.FillSpace(spacelen / 3);
                            }
                            else
                            {
                                ProcessTraceUtil.Trace("对齐失败");
                                var ex = new Exception("无法对齐");
                                ex.Data.Add("老索引文件当前位置", item.KeyOffset);
                                ex.Data.Add("新索引文件写入位置", newwriter.GetWritePosition());
                                throw ex;
                            }
                        }

                        if (item.KeyOffset == newwriter.GetWritePosition())
                        {
                            nextcopypos = newwriter.GetWritePosition();
                            if (isfirst)
                            {
                                newIndexMergePos = nextcopypos;
                            }
                            ProcessTraceUtil.Trace("新老索引文件已经对齐:" + item.KeyOffset);
                            break;
                        }

                        isfirst        = false;
                        item.KeyOffset = newwriter.GetWritePosition();
                        newwriter.AppendObject(item);
                    }

                    if (nextcopypos > 0)
                    {
                        newwriter.Dispose();
                        ProcessTraceUtil.Trace("copy后面的数据->" + nextcopypos);
                        nextcopypos = IOUtil.CopyFile(indexfile, newindexfile, FileMode.Open, nextcopypos, -512);
                    }
                    else if (!hasitem)
                    {
                        var idxpos = idxreader.ReadedPostion();
                        if (idxpos == newwriter.GetWritePosition())
                        {
                            nextcopypos = idxpos;
                            newwriter.Dispose();
                        }
                        else
                        {
                            ProcessTraceUtil.Trace(idxpos + " vs " + newwriter.GetWritePosition());
                        }
                    }
                    ProcessTraceUtil.TraceMem("读取后面的数据完成", "m");
                    if (nextcopypos == 0)
                    {
                        throw new Exception("更新索引出错");
                    }

                    try
                    {
                        BigEntityTableIndexItem[] oldindexarray     = null;
                        BigEntityTableIndexItem[] newdiskindexarray = newdiskindexlist.ToArray();

                        tablelocker.EnterWriteLock();
                        ProcessTraceUtil.TraceMem("读取后面的数据->" + lasmargepos, "m");
                        if (nextcopypos <= 0)
                        {
                            using (newwriter)
                            {
                                using (idxreader)
                                {
                                    foreach (var item in idxreader.ReadObjectsWating <BigEntityTableIndexItem>(1, bytes: bigbuffer))
                                    {
                                        item.SetIndex(meta.KeyIndexInfo);
                                        item.KeyOffset = newwriter.GetWritePosition();
                                        newwriter.AppendObject(item);
                                    }
                                }
                            }
                        }
                        else
                        {
                            nextcopypos = IOUtil.CopyFile(indexfile, newindexfile, FileMode.Open, nextcopypos, long.MaxValue);
                            ProcessTraceUtil.TraceMem("继续copy后面的数据->" + nextcopypos, "m");
                            idxreader.Dispose();
                        }
                        ProcessTraceUtil.TraceMem("读取后面的数据完成", "m");

                        //更新索引
                        mergeinfo.LoadFactor = loadFactor;
                        keyindexdisklist.TryRemove(tablename, out oldindexarray);
                        keyindexdisklist.TryAdd(tablename, newdiskindexarray);
                        keyindexmemtemplist[tablename] = new SortArrayList <BigEntityTableIndexItem>();

                        int trycount = 0;
                        while (true)
                        {
                            try
                            {
                                File.Delete(indexfile);
                                ProcessTraceUtil.Trace("删除旧文件完成");
                                break;
                            }
                            catch (System.IO.IOException ex)
                            {
                                Thread.Sleep(1);
                                trycount++;
                                if (trycount > 1000)
                                {
                                    throw ex;
                                }
                            }
                        }

                        File.Move(newindexfile, indexfile);

                        ProcessTraceUtil.TraceMem("删除旧文件,重命名新文件完成", "m");

                        idxreader = null;
                    }
                    finally
                    {
                        tablelocker.ExitWriteLock();
                    }


                    string metafile = GetMetaFile(tablename);
                    mergeinfo.IndexMergePos = lasmargepos;
                    SerializerHelper.SerializerToXML(meta, metafile, true);

                    ProcessTraceUtil.Trace("更新元文件,更新索引完成");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("整理索引后面部分出错" + ex.ToString());

                    //LogManager.LogHelper.Instance.Error("整理索引后面部分出错", ex);
                }
                finally
                {
                    if (idxreader != null)
                    {
                        idxreader.Dispose();
                    }

                    if (newwriter != null && !newwriter.Isdispose)
                    {
                        newwriter.Dispose();
                    }

                    if (File.Exists(newindexfile))
                    {
                        File.Delete(newindexfile);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());

                //LogManager.LogHelper.Instance.Error("整理索引出错", ex);
            }
            finally
            {
                //GC.Collect();
                //ProcessTraceUtil.TraceMem("回收内存","m");
                mergeinfo.IsMergin = false;
                var info = ProcessTraceUtil.PrintTrace();
                Console.WriteLine(info);
                //LogManager.LogHelper.Instance.Debug("整理索引过程:" + info);
            }
        }
Example #24
0
 public void LoadSettings(ServerController controller)
 {
     controller.Model.Settings = SerializerHelper.Load <ServerSettings>(controller.Model.ServerConfigFile);
 }
Example #25
0
        public void Init()
        {
            if (Directory.Exists(path + "/" + application))
            {
                string[] files = Directory.GetFiles(path + "/" + application);
                if (files.Length > 0)
                {
                    foreach (string file in files)
                    {
                        File.Delete(file);
                    }
                }
            }

            if (!Directory.Exists("Content"))
            {
                Directory.CreateDirectory("Content");
            }

            this._graphics = new GraphicsConfiguration();
            this._graphics.BitsPerPixel            = 32;
            this._graphics.IsMouseVisible          = true;
            this._graphics.IsVerticalSync          = false;
            this._graphics.Resolution              = new Resolution(800, 600);
            this._graphics.Styles                  = Styles.Default;
            this._graphics.IsLightEngineActive     = false;
            this._graphics.IsParticuleEngineActive = false;

            this._audio              = new AudioConfiguration();
            this._audio.FadeMusic    = false;
            this._audio.FxVolume     = 0f;
            this._audio.MasterVolume = 0f;
            this._audio.MaxSounds    = 0;
            this._audio.MusicVolume  = 0f;
            this._audio.Mute         = true;

            this._game         = new GameConfiguration();
            this._game.Culture = CultureInfo.CurrentCulture.Name;
            this._game.Skin    = string.Empty;

            this._hotKeys = new HotKeyConfiguration();

            this._language      = new Language();
            this._language.Key  = CultureInfo.CurrentCulture.Name;
            this._language.Name = CultureInfo.CurrentCulture.NativeName;

            FunctionTranslation func = new FunctionTranslation();

            func.Key = "DEFAULT";

            Translation trans = new Translation();

            trans.Key   = "HELLO_WORLD";
            trans.Value = "Bonjour le monde !";

            func.Translations.Add(trans);
            this._language.Functions.Add(func);

            SerializerHelper.Save("Content/graphics.xml", this._graphics);
            SerializerHelper.Save("Content/audio.xml", this._audio);
            SerializerHelper.Save("Content/game.xml", this._game);
            SerializerHelper.Save("Content/keys.xml", this._hotKeys);
            SerializerHelper.Save("Content/" + this._language.Key + ".xml", this._language);
        }
Example #26
0
        public void SerializeCompareTest()
        {
            //var sessionBag = SessionContainer.UpdateSession(null, "OpenId", "SessionKey");

            Func <SessionBag> getNewEntity = () =>
            {
                var sessionBag = new SessionBag()
                {
                    Key        = Guid.NewGuid().ToString(),
                    Name       = "Jeffrey",
                    SessionKey = "SessionKey",
                    CacheTime  = DateTime.Now,
                    ExpireTime = DateTime.Now,
                    OpenId     = "OpenId"
                };
                return(sessionBag);
            };

            var testCycle = 50;
            //使用 Newtonsoft.Json 进行 1 万次序列化并计算时间
            DateTime dt1 = DateTime.Now;

            for (int i = 0; i < testCycle; i++)
            {
                //获取一个 SessionBag 对象
                var sessionBag = getNewEntity();
                //序列化
                var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(sessionBag);
                var obj        = Newtonsoft.Json.JsonConvert.DeserializeObject <SessionBag>(jsonString);

                if (i == 0)
                {
                    Console.WriteLine("Newtonsoft.JSON:");
                    Console.WriteLine(jsonString);    //输出字符串
                    Console.WriteLine(obj.CacheTime); //输出反序列化后的参数
                    Console.WriteLine("==============");
                    dt1 = DateTime.Now;               //过滤启动时间,Newtonsoft启动时间需要200多ms
                }
            }
            DateTime dt2 = DateTime.Now;

            DateTime dt3 = DateTime.Now;

            //使用 Newtonsoft.Json 进行 1 万次序列化并计算时间
            for (int i = 0; i < testCycle; i++)
            {
                //获取一个 SessionBag 对象
                var sessionBag = getNewEntity();
                //序列化
                var jsonString = SerializerHelper.GetJsonString(sessionBag);
                var obj        = SerializerHelper.GetObject <SessionBag>(jsonString);

                if (i == 0)
                {
                    Console.WriteLine(".NET Serializer:");
                    Console.WriteLine(jsonString);    //输出字符串
                    Console.WriteLine(obj.CacheTime); //输出反序列化后的参数
                    Console.WriteLine("==============");
                    dt3 = DateTime.Now;               //过滤启动时间
                }
            }
            DateTime dt4 = DateTime.Now;

            DateTime dt5 = DateTime.Now;

            //使用 .NET 内置 JSON 序列化
            for (int i = 0; i < testCycle; i++)
            {
                //获取一个 SessionBag 对象
                var          sessionBag      = getNewEntity();
                var          binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                MemoryStream memoryStream    = new MemoryStream();
                {
                    //序列化
                    binaryFormatter.Serialize(memoryStream, sessionBag);
                    byte[] objectDataAsStream = memoryStream.ToArray();

                    //反序列化
                    var obj = StackExchangeRedisExtensions.Deserialize <SessionBag>(objectDataAsStream);

                    if (i == 0)
                    {
                        Console.WriteLine(".NET Serializer:");
                        Console.WriteLine(Encoding.UTF8.GetString(objectDataAsStream)); //输出字符串
                        Console.WriteLine(obj.CacheTime);                               //输出反序列化后的参数
                        Console.WriteLine("==============");
                        dt5 = DateTime.Now;                                             //过滤启动时间
                    }
                }
            }
            DateTime dt6 = DateTime.Now;

            Console.WriteLine("Newtonsoft JSON 序列化 {0} 次,耗时:{1}ms", testCycle, (dt2 - dt1).TotalMilliseconds);
            Console.WriteLine(".NET 内置 JSON 序列化 {0} 次,耗时:{1}ms", testCycle, (dt4 - dt3).TotalMilliseconds);
            Console.WriteLine("二进制 序列化 {0} 次,耗时:{1}ms", testCycle, (dt6 - dt5).TotalMilliseconds);

            //结果:Newtonsoft.JSON 效率更高,三个结果时间基本上1:2:3
        }
Example #27
0
        public void GetJsonStringTest_Null()
        {
            var obj =
                new
            {
                X =
                    new RootClass()
                {
                    A             = "Jeffrey",
                    B             = 31,
                    C             = null,
                    ElementClassA = new ElementClass()
                    {
                        A = "Jeffrey", B = null
                    },
                    ElementClassB = null
                },
                Y = new
                {
                    O = "0",
                    Z = (string)null
                }
            };

            var obj2 = new RootClass()
            {
                A             = "Jeffrey",
                B             = 31,
                C             = null,
                ElementClassA = new ElementClass()
                {
                    A = "Jeffrey", B = null
                },
                ElementClassB = null
            };

            var obj3 = new RootClass()
            {
                A             = "Jeffrey",
                B             = 31,
                C             = null,
                ElementClassA = new ElementClass()
                {
                    A = "Jeffrey", B = null
                },
                ElementClassB = null,
                ElementClass2 = new ElementClass2()
                {
                    A = "A"
                }
            };

            DateTime         dt1 = DateTime.Now;
            SerializerHelper js  = new SerializerHelper();

            var json = js.GetJsonString(obj, new JsonSetting(true, new List <string>(new[] { "Z", "C" })));

            Console.WriteLine(json);

            var json2 = js.GetJsonString(obj2, new JsonSetting(true, new List <string>(new[] { "B" })));

            Console.WriteLine(json2);

            var json3 = js.GetJsonString(obj3, new JsonSetting(true, null, new List <Type>(new[] { typeof(ElementClass2) })));

            Console.WriteLine(json3);

            Console.WriteLine((DateTime.Now - dt1).TotalMilliseconds);
        }
        /// <summary>
        /// 修改待办事项
        /// </summary>
        /// <returns></returns>
        private async Task ModifyAndSyncToDo()
        {
            IsLoading = Visibility.Visible;

            //修改当前列表
            var itemToModify = AllToDos.ToList().Find(sche =>
            {
                if (sche.ID == EditedToDo.ID)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            });

            itemToModify.Content    = EditedToDo.Content;
            itemToModify.Category   = CateVM.Categories[AddingCate].CateColorID;
            itemToModify.CreateTime = DateTime.Now.ToString();

            UpdateDisplayList(CateVM.Categories[SelectedCate].CateColorID);

            //离线模式
            if (App.IsInOfflineMode)
            {
                await SerializerHelper.SerializerToJson <ObservableCollection <ToDo> >(AllToDos, SerializerFileNames.ToDoFileName);

                EditedToDo = new ToDo();

                Messenger.Default.Send(new GenericMessage <ObservableCollection <ToDo> >(AllToDos), MessengerTokens.UpdateTile);

                return;
            }
            //非离线模式
            else if (App.CanSendRequest)
            {
                try
                {
                    var resultUpdate = await CloudService.UpdateContent(itemToModify.ID, itemToModify.Content, itemToModify.CreateTime, itemToModify.Category);

                    if (resultUpdate)
                    {
                        AllToDos.ToList().Find(sche =>
                        {
                            if (sche.ID == EditedToDo.ID)
                            {
                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        }).Content = EditedToDo.Content;

                        EditedToDo = new ToDo();

                        Messenger.Default.Send(new GenericMessage <ObservableCollection <ToDo> >(AllToDos), MessengerTokens.UpdateTile);
                    }
                }
                catch (COMException)
                {
                    await ToastService.SendToastAsync(ResourcesHelper.GetResString("RequestError"));
                }
            }
            IsLoading = Visibility.Collapsed;
        }
Example #29
0
        public void updateAssets(List <object> assetsToUpdate)
        {
            //Recuperer tous les repertoires
            string documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Native-Software";

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

            if (!Directory.Exists(documentsDirectory + "\\Asset Manager"))
            {
                Directory.CreateDirectory(documentsDirectory + "\\Asset Manager");
            }

            String[] tabString = Directory.GetDirectories(documentsDirectory + "\\Asset Manager\\");

            for (int i = 0; i < tabString.Length; i++)
            {
                string pathDirToload = tabString[i];

                //Recuperer les assets du repertoire selectioné
                DirectoryInfo dirProjectSelected = new DirectoryInfo(pathDirToload);
                string        pathFileSerialized = pathDirToload + "\\" + dirProjectSelected.Name.Replace(" ", "_") + ".kres";
                if (File.Exists(pathFileSerialized))
                {
                    AssetsToSerialize assetsSerialized = null;

                    FileStream fs = File.OpenRead(pathFileSerialized);
                    if (fs.Length > 0)
                    {
                        MemoryStream ms = new MemoryStream();
                        ms.SetLength(fs.Length);

                        fs.Read(ms.GetBuffer(), 0, (int)ms.Length);

                        assetsSerialized = (AssetsToSerialize)SerializerHelper.DeSerializeBinary(ms);
                        ms.Close();
                    }

                    fs.Close();

                    if (assetsSerialized != null)
                    {
                        List <object> assetsUpdated = new List <object>();
                        //Verifier si le projet contient les assets
                        for (int j = 0; j < assetsToUpdate.Count; j++)
                        {
                            object assetOBJ  = assetsToUpdate[j];
                            bool   isUpdated = false;
                            if (assetOBJ is DisplayObject)
                            {
                                DisplayObject assetDisplayObject = assetOBJ as DisplayObject;

                                if (assetDisplayObject.Type.Equals("IMAGE"))
                                {
                                    //Chercher dans le projet d'assets si il contient une image du même nom
                                    for (int k = 0; k < assetsSerialized.ListObjects.Count; k++)
                                    {
                                        DisplayObject serializedDisplayObject = assetsSerialized.ListObjects[k];
                                        if (serializedDisplayObject.Type.Equals("IMAGE"))
                                        {
                                            if (serializedDisplayObject.Name.Equals(assetDisplayObject.OriginalAssetName))
                                            {
                                                //Update the asset
                                                assetDisplayObject.Image = new Bitmap(serializedDisplayObject.Image);
                                                isUpdated = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                                else if (assetDisplayObject.Type.Equals("SPRITE"))
                                {
                                    //Chercher dans le projet d'assets si il contient une image du même nom
                                    for (int k = 0; k < assetsSerialized.ListObjects.Count; k++)
                                    {
                                        DisplayObject serializedDisplayObject = assetsSerialized.ListObjects[k];
                                        if (serializedDisplayObject.Type.Equals("SPRITE"))
                                        {
                                            if (serializedDisplayObject.Name.Equals(assetDisplayObject.OriginalAssetName))
                                            {
                                                //Update the asset
                                                assetDisplayObject.SpriteSet = serializedDisplayObject.SpriteSet;
                                                string currentSeq = assetDisplayObject.CurrentSequence;
                                                assetDisplayObject.CurrentSequence = currentSeq;
                                                int frame = assetDisplayObject.CurrentFrame;
                                                assetDisplayObject.CurrentFrame = frame;

                                                assetDisplayObject.InitialRect = assetDisplayObject.SurfaceRect;

                                                isUpdated = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }

                            if (isUpdated == true)
                            {
                                assetsUpdated.Add(assetOBJ);
                            }
                        }

                        for (int j = 0; j < assetsUpdated.Count; j++)
                        {
                            assetsToUpdate.Remove(assetsUpdated[j]);
                        }
                    }

                    assetsSerialized = null;
                }

                if (assetsToUpdate.Count == 0)
                {
                    return;
                }
            }
        }
        /// <summary>
        /// 目前支持向指定微信用户的openid发放指定金额红包
        /// 注意total_amount、min_value、max_value值相同
        /// total_num=1固定
        /// 单个红包金额介于[1.00元,200.00元]之间
        /// </summary>
        /// <returns></returns>
        public ActionResult SendRedPack()
        {
            string nonceStr;//随机字符串
            string paySign;//签名
            var sendNormalRedPackResult = RedPackApi.SendNormalRedPack(
                TenPayV3Info.AppId, TenPayV3Info.MchId, TenPayV3Info.Key,
                @"F:\apiclient_cert.p12",     //证书物理地址
                "接受收红包的用户的openId",   //接受收红包的用户的openId
                "红包发送者名称",             //红包发送者名称
                Request.UserHostAddress,      //IP
                100,                          //付款金额,单位分
                "红包祝福语",                 //红包祝福语
                "活动名称",                   //活动名称
                "备注信息",                   //备注信息
                out nonceStr,
                out paySign,
                null,                         //场景id(非必填)
                null,                         //活动信息(非必填)
                null                          //资金授权商户号,服务商替特约商户发放时使用(非必填)
                );

            SerializerHelper serializerHelper = new SerializerHelper();
            return Content(serializerHelper.GetJsonString(sendNormalRedPackResult));
        }
Example #31
0
        /// <summary>
        /// NeuChar 请求
        /// </summary>
        public virtual IResponseMessageBase OnNeuCharRequest(RequestMessageNeuChar requestMessage)
        {
            try
            {
                var path = ServerUtility.ContentRootMapPath("~/App_Data/NeuChar");
                //SenparcTrace.SendCustomLog("OnNeuCharRequest path", path);

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

                var    file    = Path.Combine(path, "NeuCharRoot.config");
                bool   success = true;
                string result  = null;

                var configFileExisted = File.Exists(file);
                if (!configFileExisted)
                {
                    using (var fs = new FileStream(file, FileMode.CreateNew))
                    {
                        using (var sw = new StreamWriter(fs))
                        {
                            sw.WriteLine(NeuralSystem.DEFAULT_CONFIG_FILE_CONENT);
                        }
                        fs.Flush();
                    }
                }

                switch (requestMessage.NeuCharMessageType)
                {
                case NeuCharActionType.GetConfig:
                {
                    if (configFileExisted)        //本次对话会创建,但不在读取,利可读取可能会发生“无法访问已关闭文件”的错误
                    {
                        using (var fs = FileHelper.GetFileStream(file))
                        {
                            using (var sr = new StreamReader(fs, Encoding.UTF8))
                            {
                                var json = sr.ReadToEnd();
                                result = json;
                            }
                        }
                    }
                    else
                    {
                        result = NeuralSystem.DEFAULT_CONFIG_FILE_CONENT;        //TODO:初始化一个对象
                    }
                }
                break;

                case NeuCharActionType.SaveConfig:
                {
                    var configRootJson = requestMessage.ConfigRoot;
                    SenparcTrace.SendCustomLog("收到NeuCharRequest", "字符串长度:" + configRootJson.Length.ToString());
                    var configRoot = SerializerHelper.GetObject <ConfigRoot>(configRootJson);       //这里只做序列化校验

                    //TODO:进行验证


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

                    var fileTemp = Path.Combine(path, $"NeuCharRoot.temp.{SystemTime.Now.ToString("yyyyMMdd-HHmmss")}.config");
                    //TODO:后期也可以考虑把不同模块分离到不同的文件中

                    using (var fs = new FileStream(fileTemp, FileMode.Create))
                    {
                        using (var sw = new StreamWriter(fs))
                        {
                            sw.Write(configRootJson);
                            sw.Flush();
                        }
                    }

                    //历史文件备份,并替换临时文件
                    File.Move(file, file.Replace(".config", $".bak.{SystemTime.Now.ToString("yyyyMMdd-HHmmss")}.config"));
                    File.Move(fileTemp, file);

                    //刷新数据
                    var neuralSystem = NeuralSystem.Instance;
                    neuralSystem.ReloadNode();
                }
                break;

                case NeuCharActionType.CheckNeuChar:
                {
                    //TODO:进行有效性检验
                    var configRoot = requestMessage.ConfigRoot?.GetObject <APMDomainConfig>();

                    if (configRoot == null || configRoot.Domain.IsNullOrWhiteSpace())
                    {
                        success = false;
                        result  = "未指定 Domain!";
                        break;
                    }

                    var co2netDataOperation = new DataOperation(configRoot.Domain);

                    //获取所有数据
                    var dataItems = co2netDataOperation.ReadAndCleanDataItems(configRoot.RemoveData, true);
                    result = dataItems.ToJson();
                }
                break;

                case NeuCharActionType.PushNeuCharAppConfig:
                {
                    var configFileDir = Path.Combine(path, "AppConfig");
                    if (!Directory.Exists(configFileDir))
                    {
                        Directory.CreateDirectory(configFileDir);        //这里也可以不创建,除非是为了推送
                    }

                    //还原一次,为了统一格式,并未后续处理提供能力(例如调整缩进格式)
                    var requestData = requestMessage.RequestData.GetObject <PushConfigRequestData>();
                    var mainVersion = requestData.Version.Split('.')[0];        //主版本号
                    //配置文件路径:~/App_Data/NeuChar/AppConfig/123-v1.config
                    var configFilePath = Path.Combine(configFileDir, $"{requestData.AppId}-v{mainVersion}.config");

                    using (var fs = new FileStream(configFilePath, FileMode.Create))
                    {
                        using (var sw = new StreamWriter(fs, Encoding.UTF8))
                        {
                            var json = requestData.Config.ToJson(true); //带缩进格式的 JSON 字符串
                            sw.Write(json);                             //写入 Json 文件
                            sw.Flush();
                        }
                    }
                    result = "OK";
                }
                break;

                case NeuCharActionType.PullNeuCharAppConfig:
                {
                    var requestData = requestMessage.RequestData.GetObject <PullConfigRequestData>();
                    var mainVersion = requestData.Version.Split('.')[0];        //主版本号

                    var configFileDir = Path.Combine(path, "AppConfig");
                    //配置文件路径:~/App_Data/NeuChar/AppConfig/123-v1.config
                    var configFilePath = Path.Combine(configFileDir, $"{requestData.AppId}-v{mainVersion}.config");
                    if (!File.Exists(configFilePath))
                    {
                        //文件不存在
                        result  = $"配置文件不存在,请先推送或设置配置文件,地址:{configFilePath}";
                        success = false;
                    }
                    else
                    {
                        //读取内容
                        using (var fs = FileHelper.GetFileStream(configFilePath))
                        {
                            using (var sr = new StreamReader(fs, Encoding.UTF8))
                            {
                                var json = sr.ReadToEnd();        //带缩进格式的 JSON 字符串(文件中的原样)
                                result = json;
                            }
                        }
                    }
                }
                break;

                default:
                    break;
                }

                var successMsg = new
                {
                    success = success,
                    result  = result
                };
                TextResponseMessage = successMsg.ToJson();
            }
            catch (Exception ex)
            {
                var errMsg = new
                {
                    success = false,
                    result  = ex.Message
                };
                TextResponseMessage = errMsg.ToJson();
            }

            return(null);
        }