Beispiel #1
0
        /// <summary>
        /// 向前台发送媒体带参消息
        /// </summary>
        /// <typeparam name="T">消息参数的类型</typeparam>
        /// <param name="type">媒体消息的类型</param>
        /// <param name="message">消息参数</param>
        public static void SendMediaMessageToForeground <T>(MediaMessageTypes type, T message)
        {
            var payload = new ValueSet();

            payload.Add(MessageService.MessageType, type.ToString());
            payload.Add(MessageService.MessageBody, serializeService.Serialize(message));
            BackgroundMediaPlayer.SendMessageToForeground(payload);
        }
Beispiel #2
0
        public void SerializationCanSerializeAnonymousTypes()
        {
            // Arrange
            var obj = new { GhostTownsCount = 5 };

            // Act
            var actual = _service.Serialize(obj);

            // Assert
            Assert.Contains("ghost_towns_count", actual);
        }
Beispiel #3
0
        public void OnGet([FromRoute] string title)
        {
            ExistingPostKey = null;
            if (string.IsNullOrWhiteSpace(title))
            {
                PostInEdit       = new Post().EnsureValidKey();
                SubmitButtonText = "Publish";
                return;
            }

            var response = _blogService.GetPostByUrlFriendlyTitle(title);

            PostInEdit = response?.Post;

            if (PostInEdit == null)
            {
                SubmitButtonText = "Publish";
                PostInEdit       = new Post().EnsureValidKey();
            }
            else
            {
                ExistingPostKey = PostInEdit.Key;
                ExistingPostUrlFriendlyTitle = PostInEdit.UrlFriendlyTitle;
                SubmitButtonText             = "Update";
                AllTagsInText = _serializationService
                                .Serialize(response.AllTags is null ? new string[] { } : response.AllTags);
                PostImagesInText = _serializationService.Serialize(PostInEdit.Images ?? new List <PostImage>());
            }
        }
Beispiel #4
0
        public async Task <bool> ExportOpmlFeedsAsync(Stream stream)
        {
            var opml = new Opml {
                Head = new OpmlHead {
                    Title = "Feeds from myFeed App"
                }
            };
            var categories = await _categoryManager.GetAllAsync();

            var outlines = categories.Select(x => new OpmlOutline
            {
                ChildOutlines = x.Channels
                                .Select(i => new { Entity = i, Uri = new Uri(i.Uri) })
                                .Select(y => new OpmlOutline
                {
                    HtmlUrl = $"{y.Uri.Scheme}://{y.Uri.Host}",
                    XmlUrl  = y.Uri.ToString(),
                    Title   = y.Uri.Host,
                    Text    = y.Uri.Host,
                    Version = "rss",
                    Type    = "rss"
                })
                                .ToList(),
                Title = x.Title,
                Text  = x.Title
            });

            opml.Body = new List <OpmlOutline>(outlines);
            if (stream == null)
            {
                return(false);
            }
            _serializationService.Serialize(opml, stream);
            return(true);
        }
        public IHttpResult <TResult> SendPostRequest <TResult, TInput>(string requestUrl, TInput obj)
        {
            try
            {
                var serializedObject = _serializationService.Serialize(obj);
                var data             = Encoding.UTF8.GetBytes(serializedObject);
                var webRequest       = CreateHttpRequest(requestUrl, HttpMethodType.Post);
                using (var requestStream = webRequest.GetRequestStream())
                {
                    requestStream.Write(data, 0, data.Length);
                }
                var webResponse = webRequest.GetResponse();
                using (var responseStream = webResponse.GetResponseStream())
                {
                    string responseStr = string.Empty;
                    if (responseStream != null)
                    {
                        responseStr = new StreamReader(responseStream).ReadToEnd();
                    }
                    var responseObj = _serializationService.Deserialize <TResult>(responseStr);

                    return(new HttpResult <TResult>(responseObj, null));
                }
            }
            catch (WebException exception)
            {
                var error = string.Format("Message:{0}, Url:{1}", exception.Message, requestUrl);
                return(new HttpResult <TResult>(error));
            }
        }
Beispiel #6
0
        public void TestCollection()
        {
            Base a = new Base();
            Base b = new Base();
            Base c = new Base();
            Base d = new Base();
            CollectionDerived e = new CollectionDerived()
            {
                Child = a, Parents = new List <Base>()
                {
                    a, b, c, d
                }
            };

            TypeConfiguration.TrustedTypes = TypeMatch.Assembly(typeof(SerializerTests).Assembly);
            ISerializationService serializer = Container.Resolve <ISerializationService>();
            string json = serializer.Serialize(e);

            Console.WriteLine(json);
            Base newE = serializer.Deserialize <Base>(json);

            Assert.IsInstanceOfType(newE, typeof(CollectionDerived));
            var listE = (CollectionDerived)newE;

            Assert.IsNotNull(listE.Parents);
            Assert.AreEqual(4, listE.Parents.Count());
            Assert.AreEqual(listE.Child, listE.Parents.ElementAt(0));
        }
Beispiel #7
0
        public async Task <bool> WriteCookieData(CookieContainer container)
        {
            try
            {
                var cookies         = container.GetCookies(new Uri("https://www.flashback.org/")).Cast <Cookie>().ToList();
                var dataToBeSecured = _serializationService.Serialize(cookies);
                var buffer          = await Protect(dataToBeSecured);

                var storageFolder = ApplicationData.Current.LocalFolder;
                var sampleFile    = await storageFolder.CreateFileAsync(COOKIEFILE, CreationCollisionOption.ReplaceExisting);

                var stream = await sampleFile.OpenAsync(FileAccessMode.ReadWrite);

                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new DataWriter(outputStream))
                    {
                        dataWriter.WriteBuffer(buffer);

                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }

                stream.Dispose();

                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Fel vid skrivande av cookies: " + e.Message);
                return(false);
            }
        }
Beispiel #8
0
 protected async Task SendStatusAsync(long jobId, int status, CancellationToken cancellationToken, int numOfLearners = -1)
 {
     await client.PostAsync(
         _endPointUrl,
         new StringContent(_serializationService.Serialize(new JobStatusDto(jobId, status, numOfLearners)), Encoding.UTF8, "application/json"),
         cancellationToken);
 }
Beispiel #9
0
        private void ProcessItem(NWPlayer oPC, NWItem item, Dictionary <string, PCMigrationItem> itemMap, List <int> stripItemList)
        {
            string          resref         = item.Resref;
            int             quantity       = item.StackSize;
            int             baseItemTypeID = item.BaseItemType;
            PCMigrationItem migrationItem  = itemMap[resref];

            if (itemMap.ContainsKey(resref))
            {
                item.Destroy();
                if (!string.IsNullOrWhiteSpace(migrationItem.NewResref))
                {
                    NWItem newItem = NWItem.Wrap(_.CreateItemOnObject(migrationItem.NewResref, oPC.Object, quantity));
                    if (!newItem.Possessor.IsValid)
                    {
                        PCOverflowItem overflow = new PCOverflowItem
                        {
                            ItemResref = newItem.Resref,
                            ItemTag    = newItem.Tag,
                            ItemName   = newItem.Name,
                            ItemObject = _serialization.Serialize(newItem),
                            PlayerID   = oPC.GlobalID
                        };
                        _db.PCOverflowItems.Add(overflow);
                        _db.SaveChanges();

                        newItem.Destroy();
                    }
                }
            }
            else if (stripItemList.Contains(baseItemTypeID))
            {
                _item.StripAllItemProperties(item);
            }
        }
Beispiel #10
0
        public void Save(UserSettings userSettings)
        {
            _cachedUserSettings = userSettings;
            var serializedData = _serializationService.Serialize(_cachedUserSettings);

            _localFileService.Save(serializedData.Value, _userSettingsPath);
        }
Beispiel #11
0
        public async Task <bool> ExportOpmlFeedsAsync(Stream stream)
        {
            // Initialize new Opml instance and read categories from db.
            var opml = new Opml {
                Head = new OpmlHead {
                    Title = "Feeds from myFeed App"
                }
            };
            var categories = await _categoriesRepository.GetAllAsync();

            var outlines = categories.Select(x => new OpmlOutline
            {
                ChildOutlines = x.Channels
                                .Select(i => new { Entity = i, Uri = new Uri(i.Uri) })
                                .Select(y => new OpmlOutline
                {
                    HtmlUrl = $"{y.Uri.Scheme}://{y.Uri.Host}",
                    XmlUrl  = y.Uri.ToString(),
                    Title   = y.Uri.Host,
                    Text    = y.Uri.Host,
                    Version = "rss",
                    Type    = "rss"
                })
                                .ToList(),
                Title = x.Title,
                Text  = x.Title
            });

            // Fill opml with categories.
            opml.Body = new List <OpmlOutline>(outlines);
            _serializationService.Serialize(opml, stream);
            return(true);
        }
Beispiel #12
0
        public void TestUntrustedOut()
        {
            Derived d = new Derived();

            TypeConfiguration.TrustedTypes = TypeMatch.Type <Base>();
            ISerializationService serializer = Container.Resolve <ISerializationService>();

            Assert.ThrowsException <TypeMatchException>(() => serializer.Serialize(d));
        }
Beispiel #13
0
        public bool Run(params object[] args)
        {
            NWPlaceable terminal = Object.OBJECT_SELF;
            int         bankID   = terminal.GetLocalInt("BANK_ID");

            if (bankID <= 0)
            {
                return(false);
            }

            NWPlayer player      = _.GetLastDisturbed();
            NWItem   item        = _.GetInventoryDisturbItem();
            int      disturbType = _.GetInventoryDisturbType();
            int      itemCount   = terminal.InventoryItems.Count();
            int      itemLimit   = terminal.GetLocalInt("BANK_LIMIT");

            if (itemLimit <= 0)
            {
                itemLimit = 20;
            }

            Data.Entity.Bank bank = _data.Single <Data.Entity.Bank>(x => x.ID == bankID);

            if (disturbType == INVENTORY_DISTURB_TYPE_ADDED)
            {
                if (itemCount > itemLimit)
                {
                    _item.ReturnItem(player, item);
                    player.SendMessage(_color.Red("No more items can be placed inside."));
                }
                else
                {
                    BankItem itemEntity = new BankItem
                    {
                        ItemName   = item.Name,
                        ItemTag    = item.Tag,
                        ItemResref = item.Resref,
                        ItemID     = item.GlobalID.ToString(),
                        ItemObject = _serialization.Serialize(item),
                        BankID     = bank.ID,
                        PlayerID   = player.GlobalID,
                        DateStored = DateTime.UtcNow
                    };

                    _data.SubmitDataChange(itemEntity, DatabaseActionType.Insert);
                }
            }
            else if (disturbType == INVENTORY_DISTURB_TYPE_REMOVED)
            {
                var record = _data.Get <BankItem>(item.GlobalID);
                _data.SubmitDataChange(record, DatabaseActionType.Delete);
            }

            player.SendMessage(_color.White("Item Limit: " + (itemCount > itemLimit ? itemLimit : itemCount) + " / ") + _color.Red("" + itemLimit));
            return(true);
        }
Beispiel #14
0
        public async Task <HttpResponseMessage> PostAsync <T>(Uri requestUri, T payload) where T : class
        {
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri);
            var content        = new StringContent(serialization.Serialize(payload));

            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            requestMessage.Content      = content;

            return(await MakeRequestAsync(requestMessage));
        }
Beispiel #15
0
        public void Write <T>(string key, T value)
        {
            var result = _serializationService.Serialize(value);

            if (EnableCompression)
            {
                result = result.Compress();
            }
            _adapter.WriteString(key, result);
        }
        public void SaveConfigData <X, T>(ConfigFile <X, T> config, T data, string pathOverride = null)
            where X : class
            where T : class
        {
            var path       = pathOverride ?? $@"{_userSettingsService.Get().GameInstallLocation}\{config.GamePath}";
            var xmlclasses = _mapperFactory.GetMapper(config).Convert(data);
            var xml        = _serializationService.Serialize(data);

            _fileStorageService.Save(xml.Value, path);
        }
Beispiel #17
0
        private void TestValue <T>(T value)
        {
            TypeConfiguration.TrustedTypes = TypeMatch.Assembly(typeof(SerializerTests).Assembly);
            ISerializationService serializer = Container.Resolve <ISerializationService>();
            string json = serializer.Serialize(value);

            Console.WriteLine(json);
            T newVal = serializer.Deserialize <T>(json);

            Assert.AreEqual(value, newVal, $"Value type serialization failed on {typeof(T).Name} native serializer.");
        }
Beispiel #18
0
 /// <summary>
 /// Сохранение структуры в файл.
 /// </summary>
 private void SaveStruct()
 {
     if (_saveFileDialog.ShowDialog() != true)
     {
         return;
     }
     using (var stream = new FileStream(_saveFileDialog.FileName, FileMode.Create, FileAccess.Write))
     {
         _serializationService.Serialize(Root, stream);
     }
 }
Beispiel #19
0
        public void OnChestDisturbed(NWPlaceable oChest)
        {
            int containerID = oChest.GetLocalInt("STORAGE_CONTAINER_ID");

            if (containerID <= 0)
            {
                return;
            }

            NWPlayer oPC         = NWPlayer.Wrap(_.GetLastDisturbed());
            NWItem   oItem       = NWItem.Wrap(_.GetInventoryDisturbItem());
            int      disturbType = _.GetInventoryDisturbType();
            int      itemCount   = CountItems(oChest);
            int      itemLimit   = oChest.GetLocalInt("STORAGE_CONTAINER_ITEM_LIMIT");

            if (itemLimit <= 0)
            {
                itemLimit = 20;
            }

            StorageContainer entity = _db.StorageContainers.Single(x => x.StorageContainerID == containerID);

            if (disturbType == INVENTORY_DISTURB_TYPE_ADDED)
            {
                if (itemCount > itemLimit)
                {
                    ReturnItem(oPC, oItem);
                    oPC.SendMessage(_color.Red("No more items can be placed inside."));
                }
                else
                {
                    StorageItem itemEntity = new StorageItem
                    {
                        ItemName           = oItem.Name,
                        ItemTag            = oItem.Tag,
                        ItemResref         = oItem.Resref,
                        GlobalID           = oItem.GlobalID,
                        ItemObject         = _serialization.Serialize(oItem),
                        StorageContainerID = entity.StorageContainerID
                    };

                    entity.StorageItems.Add(itemEntity);
                    _db.SaveChanges();
                }
            }
            else if (disturbType == INVENTORY_DISTURB_TYPE_REMOVED)
            {
                var record = _db.StorageItems.Single(x => x.GlobalID == oItem.GlobalID);
                _db.StorageItems.Remove(record);
                _db.SaveChanges();
            }

            oPC.SendMessage(_color.White("Item Limit: " + itemCount + " / ") + _color.Red("" + itemLimit));
        }
 public void Send(IMessage message)
 {
     try
     {
         var message_ = _serializationService.Serialize(message);
         _serialPort.Write(message_, 0, message_.Length);
     }
     catch (Exception e)
     {
         RaiseError(e.Message);
     }
 }
Beispiel #21
0
        /// <inheritdoc/>
        public bool Send(IMessage message)
        {
            lock (_sendLock)
            {
                Debug.WriteLine("[CommunicationService] Send");
                _sendRetryCount = 0;

                while (_sendRetryCount < _sendRetryMax)
                {
                    try
                    {
                        _waitingAck = true;

                        var messageBytes = _serializationService.Serialize(message, _messageRevision);
                        _serialPort.Write(messageBytes, 0, messageBytes.Length);

                        Debug.WriteLine($"[CommunicationService] Message sent: {message.GetType()} Revision: {_messageRevision}");
                        _watch.Restart();
                        _heartbeatWatch.Restart();
                    }
                    catch (Exception e)
                    {
                        RaiseError(e.Message);
                        return(false);
                    }

                    while (_waitingAck)
                    {
                        if (_watch.Elapsed.TotalMilliseconds > _ackTimeout)
                        {
                            Debug.WriteLine($"[CommunicationService] ACK timeout Revision: {_messageRevision}");
                            break;
                        }

                        Thread.Sleep(5);
                    }

                    _messageRevision++;

                    if (!_waitingAck)
                    {
                        return(true);
                    }

                    _sendRetryCount++;
                    Debug.WriteLine($"[CommunicationService] Send retry... {_sendRetryCount}");
                }

                RaiseError($"ACK not received for revision: {_messageRevision}");
                return(false);
            }
        }
Beispiel #22
0
 protected bool TryWrite <T>(string key, T value)
 {
     try
     {
         var result = _serializer.Serialize(value);
         _container.Values[key] = result.Compress();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Beispiel #23
0
        public void ExplicitValueSerialize()
        {
            Vector2 vector = new Vector2(10, 40);

            TypeConfiguration.TrustedTypes = TypeMatch.Type <Vector2>();
            ISerializationService serializer = Container.Resolve <ISerializationService>();
            string json = serializer.Serialize(vector);

            Console.WriteLine(json);
            Vector2 newVector = serializer.Deserialize <Vector2>(json);

            Assert.AreEqual(vector, newVector);
        }
Beispiel #24
0
        public bool Run(params object[] args)
        {
            NWPlayer    oPC         = NWPlayer.Wrap(_.GetLastDisturbed());
            NWItem      item        = NWItem.Wrap(_.GetInventoryDisturbItem());
            NWPlaceable container   = NWPlaceable.Wrap(Object.OBJECT_SELF);
            int         disturbType = _.GetInventoryDisturbType();

            int structureID = container.GetLocalInt("STRUCTURE_TEMP_STRUCTURE_ID");
            PCTerritoryFlagsStructure entity = _structure.GetPCStructureByID(structureID);
            int    itemCount  = container.InventoryItems.Count;
            string itemResref = item.Resref;

            if (disturbType == INVENTORY_DISTURB_TYPE_ADDED)
            {
                if (itemCount > entity.StructureBlueprint.ItemStorageCount)
                {
                    ReturnItem(oPC, item);
                    oPC.SendMessage(_color.Red("No more items can be placed inside."));
                }
                // Only specific types of items can be stored in resource bundles
                else if (!string.IsNullOrWhiteSpace(entity.StructureBlueprint.ResourceResref) && itemResref != entity.StructureBlueprint.ResourceResref)
                {
                    ReturnItem(oPC, item);
                    oPC.SendMessage(_color.Red("That item cannot be stored here."));
                }
                else
                {
                    PCTerritoryFlagsStructuresItem itemEntity = new PCTerritoryFlagsStructuresItem
                    {
                        ItemName      = item.Name,
                        ItemResref    = itemResref,
                        ItemTag       = item.Tag,
                        PCStructureID = entity.PCTerritoryFlagStructureID,
                        GlobalID      = item.GlobalID,
                        ItemObject    = _serialization.Serialize(item)
                    };

                    entity.PCTerritoryFlagsStructuresItems.Add(itemEntity);
                    _structure.SaveChanges();
                }
            }
            else if (disturbType == INVENTORY_DISTURB_TYPE_REMOVED)
            {
                _structure.DeleteContainerItemByGlobalID(item.GlobalID);
            }

            oPC.SendMessage(_color.White("Item Limit: " + itemCount + " / ") + _color.Red(entity.StructureBlueprint.ItemStorageCount.ToString()));

            return(true);
        }
Beispiel #25
0
        /// <summary>Serializes an object and write to file in specified storage strategy</summary>
        /// <typeparam name="T">Specified type of object to serialize</typeparam>
        /// <param name="key">Path to the file in storage</param>
        /// <param name="value">Instance of object to be serialized and written</param>
        /// <param name="location">Location storage strategy</param>
        public async Task <bool> WriteFileAsync <T>(string key, T value, StorageStrategies location = StorageStrategies.Local,
                                                    CreationCollisionOption option = CreationCollisionOption.ReplaceExisting)
        {
            // create file
            var file = await CreateFileAsync(key, location, option);

            // convert to string
            var serializedValue = _serialization.Serialize(value);
            // save string to file
            await FileIO.WriteTextAsync(file, serializedValue);

            // result
            return(await FileExistsAsync(key, location));
        }
Beispiel #26
0
 //[Obsolete]
 public static bool TryWrite <T>(this ApplicationDataContainer container, string key, T value, bool compress = true, ISerializationService serializer = null)
 {
     try
     {
         serializer = serializer ?? GetDefaultSerializer();
         var result = serializer.Serialize(value);
         container.Values[key] = compress ? result.Compress() : result;
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Beispiel #27
0
        public bool Run(params object[] args)
        {
            NWPlayer    oPC           = (_.GetLastDisturbed());
            NWItem      item          = (_.GetInventoryDisturbItem());
            NWPlaceable container     = (Object.OBJECT_SELF);
            int         disturbType   = _.GetInventoryDisturbType();
            var         structureID   = new Guid(container.GetLocalString("PC_BASE_STRUCTURE_ID"));
            var         structure     = _data.Single <PCBaseStructure>(x => x.ID == structureID);
            var         baseStructure = _data.Get <BaseStructure>(structure.BaseStructureID);
            int         itemLimit     = baseStructure.Storage + structure.StructureBonus;

            int    itemCount  = container.InventoryItems.Count();
            string itemResref = item.Resref;

            if (disturbType == INVENTORY_DISTURB_TYPE_ADDED)
            {
                if (itemCount > itemLimit)
                {
                    ReturnItem(oPC, item);
                    oPC.SendMessage(_color.Red("No more items can be placed inside."));
                }
                else if (item.BaseItemType == BASE_ITEM_GOLD)
                {
                    ReturnItem(oPC, item);
                    oPC.SendMessage(_color.Red("Credits cannot be placed inside."));
                }
                else
                {
                    PCBaseStructureItem itemEntity = new PCBaseStructureItem
                    {
                        ItemName          = item.Name,
                        ItemResref        = itemResref,
                        ItemTag           = item.Tag,
                        PCBaseStructureID = structureID,
                        ItemGlobalID      = item.GlobalID.ToString(),
                        ItemObject        = _serialization.Serialize(item)
                    };
                    _data.SubmitDataChange(itemEntity, DatabaseActionType.Insert);
                }
            }
            else if (disturbType == INVENTORY_DISTURB_TYPE_REMOVED)
            {
                var dbItem = _data.Single <PCBaseStructureItem>(x => x.ItemGlobalID == item.GlobalID.ToString());
                _data.SubmitDataChange(dbItem, DatabaseActionType.Delete);
            }

            oPC.SendMessage(_color.White("Item Limit: " + itemCount + " / ") + _color.Red(itemLimit.ToString()));

            return(true);
        }
Beispiel #28
0
        public void Impound(Guid playerID, NWItem item)
        {
            PCImpoundedItem structureImpoundedItem = new PCImpoundedItem
            {
                DateImpounded = DateTime.UtcNow,
                PlayerID      = playerID,
                ItemObject    = _serialization.Serialize(item),
                ItemTag       = item.Tag,
                ItemResref    = item.Resref,
                ItemName      = item.Name
            };

            _data.SubmitDataChange(structureImpoundedItem, DatabaseActionType.Insert);
        }
        /// <summary>
        /// Serializes the value.
        /// </summary>
        public static object Serialize(object value)
        {
            var lastCacheValue = lastCache;

            if (ReferenceEquals(lastCacheValue.Item1, value))
            {
                return(lastCacheValue.Item2);
            }
            else
            {
                var result = instance.Serialize(value);
                lastCache = new Tuple <object, object>(value, result);
                return(result);
            }
        }
Beispiel #30
0
        public void TestParameterConstructor()
        {
            Base          a = new Base();
            BaseWithConst b = new BaseWithConst(a, "Fred");

            TypeConfiguration.TrustedTypes = TypeMatch.Assembly(typeof(SerializerTests).Assembly);
            ISerializationService serializer = Container.Resolve <ISerializationService>();
            string json = serializer.Serialize(b);

            Console.WriteLine(json);
            BaseWithConst newB = serializer.Deserialize <BaseWithConst>(json);

            Assert.IsInstanceOfType(newB.Child, typeof(Base));
            Assert.AreEqual(newB.Name, "Fred");
        }