Deserialize() public method

public Deserialize ( Stream stream ) : object
stream Stream
return object
Example #1
1
 public WMIBMySQL()
 {
     string file = Variables.ConfigurationDirectory + Path.DirectorySeparatorChar + "unwrittensql.xml";
     Core.RecoverFile(file);
     if (File.Exists(file))
     {
         Syslog.WarningLog("There is a mysql dump file from previous run containing mysql rows that were never successfuly inserted, trying to recover them");
         XmlDocument document = new XmlDocument();
         using (TextReader sr = new StreamReader(file))
         {
             document.Load(sr);
             using (XmlNodeReader reader = new XmlNodeReader(document.DocumentElement))
             {
                 XmlSerializer xs = new XmlSerializer(typeof(Unwritten));
                 Unwritten un = (Unwritten)xs.Deserialize(reader);
                 lock (unwritten.PendingRows)
                 {
                     unwritten.PendingRows.AddRange(un.PendingRows);
                 }
             }
         }
     }
     Thread reco = new Thread(Exec) {Name = "MySQL/Recovery"};
     Core.ThreadManager.RegisterThread(reco);
     reco.Start();
 }
        /// <summary>
        /// Retreaves StringDictionary object from database or file system
        /// </summary>
        /// <param name="extensionType">
        /// Extension Type
        /// </param>
        /// <param name="extensionId">
        /// Extension Id
        /// </param>
        /// <returns>
        /// StringDictionary object as Stream
        /// </returns>
        public object GetSettings(ExtensionType extensionType, string extensionId)
        {
            SerializableStringDictionary ssd;
            var sd = new StringDictionary();
            var serializer = new XmlSerializer(typeof(SerializableStringDictionary));

            if (Section.DefaultProvider == "XmlBlogProvider")
            {
                var stm = (Stream)BlogService.LoadFromDataStore(extensionType, extensionId);
                if (stm != null)
                {
                    ssd = (SerializableStringDictionary)serializer.Deserialize(stm);
                    stm.Close();
                    sd = ssd;
                }
            }
            else
            {
                var o = BlogService.LoadFromDataStore(extensionType, extensionId);
                if (!string.IsNullOrEmpty((string)o))
                {
                    using (var reader = new StringReader((string)o))
                    {
                        ssd = (SerializableStringDictionary)serializer.Deserialize(reader);
                    }

                    sd = ssd;
                }
            }

            return sd;
        }
        public void Generate(Package sourcePackage, Package targetPackage, FileInfo outputFile)
        {
            var serializer = new XmlSerializer(typeof(DataSchemaModel));
            var uri = PackUriHelper.CreatePartUri(new Uri("/replication.xml", UriKind.Relative));

            var sourceModel = (DataSchemaModel)serializer.Deserialize(sourcePackage.GetPart(uri).GetStream());
            var targetModel = (DataSchemaModel)serializer.Deserialize(targetPackage.GetPart(uri).GetStream());

            var outputFileSql = new List<string>();

            foreach (var publicationToCreate in sourceModel.Model.Elements.Except(targetModel.Model.Elements, x => x.Name))
            {
                var createPublicationStep = new CreatePublicationStep(publicationToCreate);
                outputFileSql.AddRange(createPublicationStep.GenerateTSQL());
            }

            foreach (var publicationToAlter in sourceModel.Model.Elements.Intersect(targetModel.Model.Elements, x => x.Name))
            {
                var sqlPublicationComparer = new SqlPublicationComparer();
                var matchingPublicationInTarget = targetModel.Model.Elements.Single(x => x.Name == publicationToAlter.Name);

                var alterPublicationStep = new AlterPublicationStep(sqlPublicationComparer.Compare(publicationToAlter, matchingPublicationInTarget));
                outputFileSql.AddRange(alterPublicationStep.GenerateTSQL());
            }

            foreach (var publicationToDrop in targetModel.Model.Elements.Except(sourceModel.Model.Elements, x => x.Name))
            {
                var dropPublicationStep = new DropPublicationStep(publicationToDrop);
                outputFileSql.AddRange(dropPublicationStep.GenerateTSQL());
            }
        }
        public void TestDeserializedObjects()
        {
            XmlSerializer ser = new XmlSerializer(typeof(OpenSearchDescription));

            // Base OpenSearch description document
            OpenSearchDescription osd1 = (OpenSearchDescription)ser.Deserialize(XmlReader.Create("../Samples/ParametersTest1.osd.xml"));
            OpenSearchParameterValueSet vs1 = OpenSearchParameterValueSet.FromOpenSearchDescription(osd1, "application/atom+xml");

            // Equivalent OpenSearch description document where parameter names are changed
            OpenSearchDescription osd2 = (OpenSearchDescription)ser.Deserialize(XmlReader.Create("../Samples/ParametersTest2.osd.xml"));
            OpenSearchParameterValueSet vs2 = OpenSearchParameterValueSet.FromOpenSearchDescription(osd2, "application/atom+xml");

            // Equivalent OpenSearch description document where parameter names and namespace prefixes are changed
            OpenSearchDescription osd3 = (OpenSearchDescription)ser.Deserialize(XmlReader.Create("../Samples/ParametersTest3.osd.xml"));
            OpenSearchParameterValueSet vs3 = OpenSearchParameterValueSet.FromOpenSearchDescription(osd3, "application/atom+xml");

            // Set values
            vs1.SetValueByIdentifier("http://a9.com/-/opensearch/extensions/geo/1.0/", "box", "5,5,6,6");
            vs1.SetValueByIdentifier("searchTerms", "test search");

            // Verify search query string correctness
            Assert.AreEqual("format=atom&count=&startPage=&startIndex=&q=test search&start=&stop=&trel=&bbox=5,5,6,6&uid=", vs1.GetQueryString(true));
            Assert.AreEqual("format=atom&q=test search&bbox=5,5,6,6", vs1.GetQueryString(false));

            // Translate value set by basic identifier matching
            vs2.TranslateFrom(vs1);
            Assert.AreEqual("format=atom&count2=&startPage2=&startIndex2=&q2=test search&start2=&stop2=&trel2=&bbox2=5,5,6,6&uid2=", vs2.GetQueryString(true));
            Assert.AreEqual("format=atom&q2=test search&bbox2=5,5,6,6", vs2.GetQueryString(false));

            // Translate value set by advanced identifier matching (verify namespace URIs)
            vs3.TranslateFrom(vs1, true);
            Assert.AreEqual("format=atom&count3=&startPage3=&startIndex3=&q3=test search&start3=&stop3=&trel3=&bbox3=5,5,6,6&uid3=", vs3.GetQueryString(true));
            Assert.AreEqual("format=atom&q3=test search&bbox3=5,5,6,6", vs3.GetQueryString(false));
        }
Example #5
0
        public void Resume()
        {
            string fname = "snake.xml";
            if (sign == '@')
                fname = "food.xml";
            if (sign == '#')
                fname = "wall.xml";
            string path = @"C:\Users\Zhandos\Documents\Visual Studio 2012\Projects\SNAKE\SNAKE\SNAKE\xml\" + fname;
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            XmlSerializer xs = new XmlSerializer(GetType());

            if (sign == 'o')
            {
                Game.snake.body.Clear();
                Game.snake = xs.Deserialize(fs) as Snake;
            }
            if (sign == '#')
            {
                Game.wall.body.Clear();
                Game.wall = xs.Deserialize(fs) as Wall;
            }
            if (sign == '@')
            {
                Game.food.body.Clear();
                Game.food = xs.Deserialize(fs) as Food;
            }
            fs.Close();
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var orderSerializer = new XmlSerializer(typeof(PurchaseOrderType));
            var ordersSerializer = new XmlSerializer(typeof(PurchaseOrdersType));

            var responseMessage = new HttpResponseMessage();
            var stream = new MemoryStream();
            var localPath = request.RequestUri.LocalPath;

            // GET /orders/notshipped
            if (localPath.EndsWith("/orders/notshipped"))
                ordersSerializer.Serialize(stream, repository.GetNotShipped());

            // GET /orders/shipped
            if (localPath.EndsWith("/orders/shipped"))
                ordersSerializer.Serialize(stream, repository.GetShipped());

            // POST /orders/{id}/ship
            if (localPath.EndsWith("/ship") && request.Method == HttpMethod.Post)
            {
                var shipUrl = localPath;
                var shipId = shipUrl.Replace("/api/orders/", string.Empty).Replace("/ship", string.Empty);
                var shipOrder = repository.Get(shipId);
                shipOrder.shipped = true;
                repository.Update(shipOrder);
            }

            // POST /orders
            if (localPath.EndsWith("/orders") && request.Method == HttpMethod.Post)
            {
                var result = request.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
                var xml = Encoding.UTF8.GetString(result);
                var newOrder = (PurchaseOrderType)orderSerializer.Deserialize(new StringReader(xml));
                repository.Add(newOrder);
            }

            // PUT /orders
            if (request.Method == HttpMethod.Put)
            {
                var result = request.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
                var xml = Encoding.UTF8.GetString(result);
                var orderToUpdate = (PurchaseOrderType)orderSerializer.Deserialize(new StringReader(xml));
                repository.Update(orderToUpdate);
            }

            if (request.Method == HttpMethod.Get && !localPath.EndsWith("/orders") && !localPath.EndsWith("/orders/") && !localPath.EndsWith("shipped"))
            {
                // GET /orders/{id}
                var url = localPath;
                var id = url.Replace("/api/orders/", string.Empty);
                var order = repository.Get(id);
                orderSerializer.Serialize(stream, order);
            }

            var content = Encoding.UTF8.GetString(stream.GetBuffer());
            content = content.Substring(content.IndexOf(Environment.NewLine) + 1);
            responseMessage.Content = new StringContent(content, Encoding.UTF8, "application/xml");

            return Task.FromResult(responseMessage);
        }
Example #7
0
        public HopsRepository()
        {
            if (hopses == null)
            {
                Assembly assembly = typeof(HopsRepository).Assembly;
                XmlSerializer serializer = new XmlSerializer(typeof(HopsData));
                HopsData loadedObject;
                var path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                HopsDataLocalPath = String.Format("{0}\\{1}\\{2}", path, assembly.GetName().Name, HOPS_DATA_FILENAME);
                if (File.Exists(HopsDataLocalPath))
                {
                   FileStream loadStream = new FileStream(HopsDataLocalPath, FileMode.Open, FileAccess.Read);
                    loadedObject = (HopsData)serializer.Deserialize(loadStream);
                    loadStream.Close();
                }
                else
                {

                    var resourceName = "WpfApplication1.Resources.hopses.xml";
                    var stream =
                        assembly.GetManifestResourceStream(resourceName);
                    var reader = new System.IO.StreamReader(stream);
                    loadedObject = (HopsData)serializer.Deserialize(reader);

                }
                hopses = loadedObject.Hopses;
            }
        }
Example #8
0
        public void Resume(Game game)
        {
            string fileName = "";
            switch (sign)
            {
                case '#':
                    fileName = "wall.xml";
                    break;
                case '$':
                    fileName = "food.xml";
                    break;
                case 'o':
                    fileName = "snake.xml";
                    break;
            }
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            XmlSerializer xs = new XmlSerializer(this.GetType());

            switch (sign)
            {
                case '#':
                    game.wall.body.Clear();
                    game.wall = xs.Deserialize(fs) as Wall;
                    break;
                case '$':
                    game.food.body.Clear();
                    game.food = xs.Deserialize(fs) as Food;
                    break;
                case 'o':
                    game.snake.body.Clear();
                    game.snake = xs.Deserialize(fs) as Snake;
                    break;
            }
            fs.Close();
        }
Example #9
0
        public void Resume()
        {
            string FileName = "";
            if (sign == 'o')
                FileName = "snake.xml";
            if (sign == '*')
                FileName = "food.xml";
            if (sign == '=')
                FileName = "wall.xml";

            FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite);
            XmlSerializer xs = new XmlSerializer(GetType());
            //BinaryFormatter bf = new BinaryFormatter();

            if (sign == '*')
                Game.food = xs.Deserialize(fs) as Food;
            if (sign == '=')
                Game.wall = xs.Deserialize(fs) as Wall;

            if (sign == 'o')
                Game.snake = xs.Deserialize(fs) as Snake;

            fs.Close();

        }
        /// <summary>
        /// Retreaves StringDictionary object from database or file system
        /// </summary>
        /// <param name="exType">Extension Type</param>
        /// <param name="exId">Extension Id</param>
        /// <returns>StringDictionary object as Stream</returns>
        public object GetSettings(ExtensionType exType, string exId)
        {
            SerializableStringDictionary ssd = null;
              StringDictionary sd = new StringDictionary();
              XmlSerializer serializer = new XmlSerializer(typeof(SerializableStringDictionary));

              if (_section.DefaultProvider == "XmlTrainProvider")
              {
            Stream stm = (Stream)TrainService.LoadFromDataStore(exType, exId);
            if (stm != null)
            {
              ssd = (SerializableStringDictionary)serializer.Deserialize(stm);
              stm.Close();
              sd = (StringDictionary)ssd;
            }
              }
              else
              {
            object o = TrainService.LoadFromDataStore(exType, exId);
            if (!string.IsNullOrEmpty((string)o))
            {
              using (StringReader reader = new StringReader((string)o))
              {
            ssd = (SerializableStringDictionary)serializer.Deserialize(reader);
              }
              sd = (StringDictionary)ssd;
            }
              }
              return sd;
        }
Example #11
0
        /// <summary>
        /// プログラムのエントリーポイント。
        /// </summary>
        /// <param name="args">コマンドライン引数。</param>
        public static void Main(string[] args)
        {
            var password = "Easy#Password";
            var serializer = new XmlSerializer(typeof(UserMan));
            UserMan userMan;

            // XML ファイルの内容をオブジェクトに読み込みます。
            using (var userManStream = new FileStream("UserMan.xml", FileMode.Open, FileAccess.Read))
            {
                userMan = serializer.Deserialize(userManStream) as UserMan;
                foreach (var user in userMan.UserList)
                {
                    Console.WriteLine("User ID: {0}", user.UserID);
                    Console.WriteLine("User Name: {0}", user.UserName);
                }
            }
            // オブジェクトを暗号化して保存します。
            using (var encryptor = new Encryptor("userMan.xml.enc", password))
            {
                serializer.Serialize(encryptor.EncryptStream, userMan);
            }
            // 暗号化したファイルを復号化して、オブジェクトに読み込みます。
            using (var decryptor = new Decryptor("UserMan.xml.enc", password))
            {
                UserMan decryptedUserMan = serializer.Deserialize(decryptor.DecryptStream) as UserMan;
                foreach (var user in decryptedUserMan.UserList)
                {
                    Console.WriteLine("User ID: {0}", user.UserID);
                    Console.WriteLine("User Name: {0}", user.UserName);
                }
            }
        }
Example #12
0
        public static void Main(string[] args)
        {
            XmlSerializer x = new XmlSerializer(typeof(Configuration));

              Configuration Cf;
              string xmlfile;
              string shefile;
              if (args.Length == 2)
              {
            if (Path.GetExtension(args[0]).ToLower() == ".xml")
            {
              xmlfile = args[0];
              shefile = args[1];
            }
            else
            {
              xmlfile = args[1];
              shefile = args[0];
            }

            using (FileStream fs = new FileStream(xmlfile, System.IO.FileMode.Open))
              Cf = (Configuration)x.Deserialize(fs);

            Cf.SheFile = shefile;
              }
              else
            Cf = (Configuration)x.Deserialize(new FileStream(args[0], System.IO.FileMode.Open));

              Controller C = new Controller(Cf);
              C.Run();
        }
Example #13
0
    static async Task RunAsync()
    {
      try
      {
        using (var client = new HttpClient())
        {
          client.BaseAddress = new Uri(s_wepApiServer);
          client.DefaultRequestHeaders.Accept.Clear();
          client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
          MitchellClaimType claim = null;
          HttpResponseMessage response;

          // Get all Claims
          List<MitchellClaimType> claims = Claims(client).Result;
          XmlSerializer xmlSerializer = new XmlSerializer(typeof(MitchellClaimType));
          string[] files = Directory.GetFiles("../../NewClaims", "*.xml");

          // Add New Claims
          foreach (string fileName in files)
          {
            using (StreamReader reader = new StreamReader(fileName))
            {
              claim = (MitchellClaimType)xmlSerializer.Deserialize(reader);
              response = await client.PostAsJsonAsync<MitchellClaimType>(autoClaimApi, claim).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
            }
          }
          claims = Claims(client).Result;
          claim = Claim(client, claims.First().MitchellClaimTypeId).Result;

          // Update Claims
          files = Directory.GetFiles("../../ClaimUpdates", "*.xml");
          foreach (string fileName in files)
          {
            using (StreamReader reader = new StreamReader(fileName))
            {
              MitchellClaimType claimUpdates = (MitchellClaimType)xmlSerializer.Deserialize(reader);
              claim = (from c in claims where c.ClaimNumber == claimUpdates.ClaimNumber select c).FirstOrDefault();
              if (claimUpdates.MitchellClaimTypeId != claim.MitchellClaimTypeId)
                claimUpdates.MitchellClaimTypeId = claim.MitchellClaimTypeId;
              // more to do response = await client.PutAsJsonAsync<MitchellClaimType>(autoClaimApi + "/" + claim.MitchellClaimTypeId, claimUpdates).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
            }
          }

          // Read a Claim
          claim = Claim(client, claim.MitchellClaimTypeId).Result;

          // Delete a claim
          // more to do response = await client.DeleteAsync(autoClaimApi + "/" + claim.MitchellClaimTypeId).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());

          claim = Claim(client, claim.MitchellClaimTypeId).Result;
        }
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
      }
    }
        public override async Task ExecuteAsync(Update update, Dictionary<string, string> parsedMessage)
        {
            var responseStream = new StreamReader(await GetCurrencyRates());
            var xmlDeserializer = new XmlSerializer(typeof(CurrencyContainerXml.DailyExRates));
            var currencyContainer = new CurrencyContainerXml() { DailyRates = xmlDeserializer.Deserialize(responseStream) as CurrencyContainerXml.DailyExRates };

            // Get data for previous date for comparison
            if (_previousDayCurrencyContainer == null ||
                DateTime.ParseExact(_previousDayCurrencyContainer.DailyRates.Date, "MM/dd/yyyy", null).AddDays(1) !=
                DateTime.ParseExact(currencyContainer.DailyRates.Date, "MM/dd/yyyy", null))
            {
                var ondate = DateTime.ParseExact(currencyContainer.DailyRates.Date, "MM/dd/yyyy", null).AddDays(-1);
                // Rates do not update on weekend (at least here, duh)
                if (ondate.DayOfWeek == DayOfWeek.Sunday)
                {
                    ondate = ondate.AddDays(-2);
                }
                var ondatestring = ondate.ToString(@"MM\/dd\/yyyy");
                responseStream = new StreamReader(await GetCurrencyRates(OnDateParam + ondatestring));
                _previousDayCurrencyContainer = new CurrencyContainerXml() { DailyRates = xmlDeserializer.Deserialize(responseStream) as CurrencyContainerXml.DailyExRates };
            }

            var sb = new StringBuilder();
            sb.Append("Курсы валют на ");
            sb.AppendLine(DateTime.ParseExact(currencyContainer.DailyRates.Date, "MM/dd/yyyy", null).ToShortDateString());
            sb.Append("По отношению к ");
            sb.AppendLine(DateTime.ParseExact(_previousDayCurrencyContainer.DailyRates.Date, "MM/dd/yyyy", null).ToShortDateString());
            sb.AppendLine();

            List<string> currenciesList = new List<string>();
            if (parsedMessage.ContainsKey("message"))
            {
                var names = parsedMessage["message"].Split(',').ToList();
                currenciesList.AddRange(names.Select(cname => cname.ToUpper()));
            }
            if (currenciesList.Count == 0)
                currenciesList = _defaultCurrenciesList;

            foreach (var currency in currencyContainer.DailyRates.Currency.Where(x => currenciesList.Contains(x.CharCode)))
            {
                sb.Append(currency.CharCode + ": " + currency.Rate);
                if (_previousDayCurrencyContainer != null)
                {
                    var diff = currency.Rate -
                               _previousDayCurrencyContainer.DailyRates.Currency.First(
                                   x => x.CharCode == currency.CharCode).Rate;
                    sb.Append(" _(");
                    sb.Append(diff > 0 ? "+" : "-");
                    sb.Append(Math.Abs(diff));
                    sb.Append(")_");
                }
                sb.AppendLine();
            }

            await Bot.SendTextMessage(update.Message.Chat.Id, sb.ToString(), false, update.Message.MessageId, null, true);
        }
Example #15
0
 public void Resume()
 {
     Type t = this.GetType();
     FileStream fs = new FileStream(string.Format("{0}.xml", t.Name), FileMode.Open, FileAccess.Read);
     XmlSerializer xs = new XmlSerializer(t);
     if (t == typeof(Snake)) Game.s = xs.Deserialize(fs) as Snake;
     if (t == typeof(Food)) Game.f = xs.Deserialize(fs) as Food;
     if (t == typeof(Wall)) Game.w = xs.Deserialize(fs) as Wall;
     fs.Close();
 }
        public void Compare()
        {
            var comparer = new SqlPublicationComparer();

            var serializer = new XmlSerializer(typeof (Element));
            var source = (Element)serializer.Deserialize(new FileStream(@"Samples\Compiled Model.xml", FileMode.Open));
            var target = (Element)serializer.Deserialize(new FileStream(@"Samples\Extracted Model.xml", FileMode.Open));

            comparer.Compare(source, target);
        }
Example #17
0
 public void Resume()
 {
     Type t = GetType();
     FileStream fs = new FileStream(string.Format("{0}.xml", t.Name), FileMode.Open, FileAccess.Read);
     XmlSerializer xs = new XmlSerializer(t); // сериализация жасайды
     if (t == typeof(Wall)) Game.wall = xs.Deserialize(fs) as Wall;
     if (t == typeof(Snake)) Game.snake = xs.Deserialize(fs) as Snake;
     if (t == typeof(Food)) Game.food = xs.Deserialize(fs) as Food;
     fs.Close();
 }
 public void loadActigoHistoricalStocks(string filename1, string filename2, string filename3)
 {
     FileStream file1 = File.Open(filename1, FileMode.OpenOrCreate);
     FileStream file2 = File.Open(filename2, FileMode.OpenOrCreate);
     FileStream file3 = File.Open(filename3, FileMode.OpenOrCreate);
     XmlSerializer serializer = new XmlSerializer(typeof(List<HistoricalStock>));
     EuroStoxx50 = ((List<HistoricalStock>)serializer.Deserialize(file1));
     Sp500 = ((List<HistoricalStock>)serializer.Deserialize(file2));
     SpAsx200 = ((List<HistoricalStock>)serializer.Deserialize(file3));
     file1.Close();
     file2.Close();
     file3.Close();
 }
Example #19
0
        static int Main(string[] args)
        {
            var exitCode = 1;

            try
            {
                var cmdOptions = PowerArgs.Args.Parse<CommandLineOptions>(args);

                if (string.Compare(cmdOptions.Baseline, cmdOptions.Live, StringComparison.OrdinalIgnoreCase) == 0)
                    throw new ArgumentException("The values of baseline and live parameters cannot be identical.");

                var xmls = new XmlSerializer(typeof(AggregateEventsData));

                AggregateEventsData baseline = null;
                AggregateEventsData live = null;

                using (StreamReader reader = new StreamReader(cmdOptions.Baseline))
                {
                    baseline = (AggregateEventsData)xmls.Deserialize(reader);
                }

                using (StreamReader reader = new StreamReader(cmdOptions.Live))
                {
                    live = (AggregateEventsData)xmls.Deserialize(reader);
                }

                var dataComparer = new AggregateEventsDataComparer(baseline, live);

                if (dataComparer.CompareResults())
                {
                    Console.WriteLine("PASS: perf results are ok");
                    exitCode = 0;
                }
                else
                {
                    Console.WriteLine("FAIL: perf results out of tolerance");
                }
            }
            catch (PowerArgs.ArgException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(PowerArgs.ArgUsage.GenerateUsageFromTemplate<CommandLineOptions>());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            return exitCode;
        }
        public object Create(object parent, object configContext, XmlNode section)
        {
            var serializer = new XmlSerializer(GetType());
            var config = (WebConfigurationSectionHandler)serializer.Deserialize(new XmlNodeReader(section));
            var path = config.FilePath;
            if(string.IsNullOrEmpty(path))
                return config;
            var httpConfig = configContext as HttpConfigurationContext;
            if(httpConfig != null)
                path = HttpContext.Current.Server.MapPath(httpConfig.VirtualPath + "/" + path);

            using(var file = File.OpenRead(path))
                return serializer.Deserialize(file);
        }
Example #21
0
        public ViewModelLocator()
        {
            #if DEBUG
            if (ViewModelBase.IsInDesignModeStatic)
            {
                LocationDescriptionsTestValues = new ObservableCollection<LocationDescription>();
                TransitDescriptionsTestValues = new ObservableCollection<TransitDescription>();

                var bingMapsResponseSerializer = new XmlSerializer(typeof(Response));
                var bingSearchResponseSerializer = new XmlSerializer(typeof(SearchResponse));

                var bmlocresx = new Uri("TestData/bingmapslocations.xml", UriKind.Relative);
                var bmbusresx = new Uri("TestData/bingmapstransit.xml", UriKind.Relative);
                var bsphoresx = new Uri("TestData/bingservicephonebook.xml", UriKind.Relative);

                var sr1 = new StreamReader(System.Windows.Application.GetResourceStream(bmlocresx).Stream);
                var sr2 = new StreamReader(System.Windows.Application.GetResourceStream(bsphoresx).Stream);
                var sr3 = new StreamReader(System.Windows.Application.GetResourceStream(bmbusresx).Stream);

                var locRsp = (Response)bingMapsResponseSerializer.Deserialize(sr1);
                foreach (Location location in locRsp.ResourceSets[0].Resources)
                {
                    LocationDescriptionsTestValues.Add(new LocationDescription(location));
                }

                var phoRsp = (SearchResponse)bingSearchResponseSerializer.Deserialize(sr2);
                foreach (PhonebookResult phone in phoRsp.Phonebook.Results)
                {
                    LocationDescriptionsTestValues.Add(new LocationDescription(phone));
                }

                var busRsp = (Response)bingMapsResponseSerializer.Deserialize(sr3);
                foreach (Route route in busRsp.ResourceSets[0].Resources)
                {
                    TransitDescriptionsTestValues.Add(new TransitDescription(route, TransitDescription.DirectionType.Transit));
                }

                sr1.Dispose();
                sr2.Dispose();
                sr3.Dispose();
            }
            #endif

            CreateMainMapViewModel();
            CreateLocationSelectionViewModel();
            CreateDirectionsViewModel();
            CreateSettingsViewModel();
        }
Example #22
0
		public static TriviaMessage Deserialize(string dataReceived)
		{
            /*
bool correctEnding = (dataReceived.EndsWith("</TriviaMessage>"));
if (!correctEnding)
{
	throw new InvalidOperationException("Deserialization will fail...");
}
             */
			XmlSerializer serializer = new XmlSerializer(typeof(TriviaMessage));
			StringReader reader = new StringReader(dataReceived);

			TriviaMessage message = null;

            try
            {
                message = (TriviaMessage)(serializer.Deserialize(reader));
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(string.Format("Failed to deserialize this data received '{0}'", dataReceived), ex);
            }

			reader.Close();
			
			return message;
		}
        public static object DeserializeAudioTracks(string tracksString)
        {
            XmlSerializer xmlDeSerializer = new XmlSerializer(typeof(List<BackgroundTrackItem>));
            StringReader textReader = new StringReader(tracksString);

            return xmlDeSerializer.Deserialize(textReader) as List<BackgroundTrackItem>;
        }
        public static BackgroundTrackItem DeserializeObjectAudioTrack(this string s)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(BackgroundTrackItem));
            StringReader textReader = new StringReader(s);

            return xmlSerializer.Deserialize(textReader) as BackgroundTrackItem;
        }
Example #25
0
        public email()
        {
            Data rx=null;
            XmlSerializer reader = new XmlSerializer(typeof(Data));
            string appPath = Path.GetDirectoryName(Application.ExecutablePath);
            using (FileStream input = File.OpenRead([email protected]"\data.xml"))
            {
                if(input.Length !=0)
                   rx = reader.Deserialize(input) as  Data;
            }

            if (rx != null)
            {
                try
                {
                    emaila = rx.userName;
                    passwd = UnprotectPassword(rx.passwd);
                    loginInfo = new NetworkCredential(emaila, passwd);
                    msg = new MailMessage();
                    smtpClient = new SmtpClient(rx.outGoing, rx.port);
                    smtpClient.EnableSsl = rx.ssl;
                    smtpClient.UseDefaultCredentials = false;
                    smtpClient.Credentials = loginInfo;
                    this.createMessage();
                    Environment.Exit(0);
                }
                catch (SmtpException sysex)
                {

                    MessageBox.Show("Taxi Notification App Has Encountered a Problem " +sysex.Message + " Please Check Your Configuration Settings", "Taxi Notification Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
            }
            else Environment.Exit(0);
        }
Example #26
0
        /// <summary>
        /// Initialise the forums element from the server.
        /// </summary>
        private void Initialise()
        {
            string url = string.Format("cix.svc/user/{0}/topics.xml", _data.Name);
            WebRequest wrGeturl = WebRequest.Create(CIXOAuth.GetUri(url));
            wrGeturl.Method = "GET";

            try
            {
                Stream objStream = wrGeturl.GetResponse().GetResponseStream();
                if (objStream != null)
                {
                    using (XmlReader reader = XmlReader.Create(objStream))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(UserTopicResultSet));
                        UserTopicResultSet listOfTopics = (UserTopicResultSet)serializer.Deserialize(reader);

                        _topics = new Topics();
                        foreach (UserTopicResultSetUserTopicsUserTopic topic in listOfTopics.UserTopics)
                        {
                            Topic newTopic = new Topic(topic, this);
                            _topics.Add(newTopic);
                        }
                    }
                }
            }
            catch (WebException e)
            {
                if (e.Message.Contains("401"))
                {
                    throw new AuthenticationException("Authentication Failed", e);
                }
            }
            _initialised = true;
        }
Example #27
0
        public config GetDefault()
        {
            config config;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.buy4.com/api/toolbar/config.xml");

            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "text/xml";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            XmlSerializer serializer = new XmlSerializer(typeof(config));
            Stream stream = response.GetResponseStream();

            using (XmlReader reader = XmlReader.Create(stream))
                {
                config = (config)serializer.Deserialize(reader);

                }

            stream.Close();

            return config;
        }
Example #28
0
        public static void Serialization1(Human human)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Human));
            StringBuilder sb = new StringBuilder();

            /* SERIALIZATION */
            using (StringWriter writer = new StringWriter(sb))
            {
                serializer.Serialize(writer, human);
            }
            // XML file
            //Console.WriteLine("SB: " +sb.ToString());
            /* END SERIALIZATION */



            /* DESERIALIZATION */
            Human newMartin = new Human();
            using (StringReader reader = new StringReader(sb.ToString()))
            {
                newMartin = serializer.Deserialize(reader) as Human;
            }
            Console.WriteLine(newMartin.ToString() + Environment.NewLine);
            /* END DESERIALIZATION */
        }
 public async Task<SummaryTemperatureData> GetStdAsync()
 {
     // var uri = new Uri("http://jeffa.org:81/ha/SummaryData.php");
     //var uri = new Uri(App.SummaryDataUrl);
     //var client = new HttpClient();
     //var opContent = (await client.GetAsync(uri)).Content;
     //string foo = await opContent.ReadAsStringAsync();
     //var fooo = JsonConvert.DeserializeObjectAsync<SummaryTemperatureData>(foo);
     //return await fooo;
     var applicationDataSettingsService = new ApplicationDataSettingsService();
     try
     {
     // ToDo need to wrap this a bit. error checking. disposal....
     WebHeaderCollection headers = new WebHeaderCollection();
     WebRequest request = WebRequest.Create(new Uri(applicationDataSettingsService.SummaryDataUrl));
     request.ContentType = "application/xml";
     WebResponse response = await request.GetResponseAsync();
     // response.Close(); // ?? hmmm
     Debug.WriteLine("\nThe HttpHeaders are \n{0}", request.Headers);
     Stream inputStream = response.GetResponseStream();
     XmlReader xmlReader = XmlReader.Create(inputStream);
     XmlSerializer xml = new XmlSerializer(typeof(SummaryTemperatureData));
     var stdXml = (SummaryTemperatureData)xml.Deserialize(xmlReader);
     return stdXml;
     }
     catch (Exception e)
     {
         Utility.Log(this, e.ToString());
         return null;
     }
 }
Example #30
0
        private async Task<Device> GetXml(Dictionary<string, string> headers)
        {
            if (headers.ContainsKey("location"))
            {
                WebRequest request = WebRequest.Create(new Uri(headers["location"]));

                var r = (HttpWebResponse) await request.GetResponseAsync();
                if (r.StatusCode == HttpStatusCode.OK)
                {
                    try
                    {
                        var ser = new XmlSerializer(typeof (Device));
                        return (Device) ser.Deserialize(r.GetResponseStream());
                    }
                    catch (InvalidOperationException ex)
                    {
                        Debug.WriteLine(ex.Message);
                        return null;
                    }
                }

                throw new Exception("Cannot connect to service");
            }

            throw new Exception("No service Uri defined");
        }