ReadObject() public method

public ReadObject ( System reader ) : object
reader System
return object
Beispiel #1
1
        public string Translate(string text, string from, string to)
        {
            using (var client = new HttpClient())
            {
                var url = string.Format(
                        _translatorApiUrlFormat,
                        HttpUtility.UrlEncode(text),
                        HttpUtility.UrlEncode(from),
                        HttpUtility.UrlEncode(to));

                using (var message = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", GetAccessToken());

                    using (var result = client.SendAsync(message).Result)
                    {
                        if (!result.IsSuccessStatusCode)
                        {
                            throw new TrosiTranslationException(result.Content.ReadAsStringAsync().Result);
                        }

                        using (var responseStream = result.Content.ReadAsStreamAsync().Result)
                        {
                            var serializer = new DataContractSerializer(typeof(string));

                            return serializer.ReadObject(responseStream) as string;
                        }
                    }
                }
            }
        }
Beispiel #2
0
        public UnitInfoRepository()
        {
            var ser = new DataContractSerializer(typeof(UnitesInfo));

            natoList = new SortedList<ushort, UnitInfo>();

            using ( var reader = new FileStream(Path.Combine(Settings.Default.exeFolder, "NATO.xml"), FileMode.Open) )
            {
                UnitesInfo natoUnits = ser.ReadObject(reader) as UnitesInfo;

                foreach ( var unit in natoUnits )
                {
                    natoList.Add(unit.ShowRoomID, unit);
                }
            }

            pactList = new SortedList<ushort, UnitInfo>();

            using ( var reader = new FileStream(Path.Combine(Settings.Default.exeFolder, "PACT.xml"), FileMode.Open) )
            {
                UnitesInfo pactUnits = ser.ReadObject(reader) as UnitesInfo;

                foreach ( var unit in pactUnits)
                {
                    pactList.Add(unit.ShowRoomID, unit);
                }
            }
        }
        public DesignUnitInfoRepository()
        {
            var ser = new DataContractSerializer(typeof(UnitesInfo));

            natoList = new SortedList<ushort, UnitInfo>();

            // TODO find a better way to design time this
            using ( var reader = new FileStream(Path.Combine(@"F:\Dev\RedReplay\RedReplay\Release", "NATO.xml"), FileMode.Open) )
            {
                UnitesInfo natoUnits = ser.ReadObject(reader) as UnitesInfo;

                foreach ( var unit in natoUnits )
                {
                    natoList.Add(unit.ShowRoomID, unit);
                }
            }

            pactList = new SortedList<ushort, UnitInfo>();

            // TODO find a better way to design time this
            using ( var reader = new FileStream(Path.Combine(@"F:\Dev\RedReplay\RedReplay\Release", "PACT.xml"), FileMode.Open) )
            {
                UnitesInfo pactUnits = ser.ReadObject(reader) as UnitesInfo;

                foreach ( var unit in pactUnits )
                {
                    pactList.Add(unit.ShowRoomID, unit);
                }
            }
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            Person p = new Person() { Name = "曾小丹", Age = 18 };
            var ds = new DataContractSerializer(typeof(Person));
            var s = new MemoryStream();
            using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateBinaryWriter(s))
            {
                ds.WriteObject(w, p);
            }

            var s2 = new MemoryStream(s.ToArray());
            Person p2;
            using (XmlDictionaryReader r = XmlDictionaryReader.CreateBinaryReader(s2, XmlDictionaryReaderQuotas.Max))
            {
                p2 = (Person)ds.ReadObject(r);
            }
            //XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
            //using (XmlWriter w = XmlWriter.Create(@"D:\WebPage\Img\perosn.xml", settings))
            //{
            //    ds.WriteObject(w, p);
            //}
            System.Diagnostics.Process.Start(@"D:\WebPage\Img\perosn.xml");
            // 使用程序打开该文件?!
            //using (Stream s = File.Create(@"D:\WebPage\Img\perosn.xml"))
            //{
            //    ds.WriteObject(s, p);
            //}

            Person p2;
            using (Stream s = File.OpenRead(@"D:\WebPage\Img\perosn.xml"))
            {
                p2 = (Person)ds.ReadObject(s);
            }
            Console.WriteLine(p2.Name + "" + p2.Age);
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            /* Data contract serialization typically reads and writes XML data. You use a
             * DataContractSerializer object for data contract serialization. Its 
             * WriteObject() method can write to a stream, or it can write to an object that
             * extends XmlDictionaryWriter, an abstract class that controls XML output and 
             * can be extended to change the way the XML output is written. Objects are
             * deserialized using the ReadObject() method, which can read XML data from
             * a stream or an XmlDictionaryReader.
             */
            DataContractSerializer serializer = new DataContractSerializer(typeof(SerializableGuy));

            // We’ll create a new SerializableGuy object and serialize it using a FileStream.
            SerializableGuy guyToWrite = new SerializableGuy("Joe", 37, 150);
            using (FileStream writer = new FileStream("serialized_guy.xml", FileMode.Create))
            {
                serializer.WriteObject(writer, guyToWrite);
            }

            // We can open the file we just wrote and deserialize it into a new guy using ReadObject().
            // We’ll use the XmlDictionaryReader.CreateTextReader() method to create an object that
            // reads XML data from a stream. 
            SerializableGuy guyToRead = null;
            using (FileStream inputStream = new FileStream("serialized_guy.xml", FileMode.Open))
            using (XmlDictionaryReader reader =
                XmlDictionaryReader.CreateTextReader(inputStream, new XmlDictionaryReaderQuotas()))
            {
                guyToRead = serializer.ReadObject(reader, true) as SerializableGuy;
            }
            Console.WriteLine(guyToRead);
            // Output: Joe is 37 years old and has 150 bucks [1461194451,0]


            string xmlGuy = @"
<Guy xmlns=""http://www.headfirstlabs.com"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
   <Age>43</Age> 
   <Cash>225</Cash> 
   <Name>Bob</Name> 
   <secretNumberOne>54321</secretNumberOne>
</Guy>";
            byte[] buffer = UnicodeEncoding.UTF8.GetBytes(xmlGuy);

            using (XmlDictionaryReader reader =
                XmlDictionaryReader.CreateTextReader(buffer, new XmlDictionaryReaderQuotas()))
            {
                guyToRead = serializer.ReadObject(reader, true) as SerializableGuy;
            }
            Console.WriteLine(guyToRead);
            // Output: Bob is 43 years old and has 225 bucks [54321,0]

            Console.ReadKey();
        }
Beispiel #6
0
        internal static TestArtifact DeserializeFromFile(Type type, string filePath)
        {
            FileStream   reader       = null;
            TestArtifact testArtifact = null;

            try
            {
                // Create DataContractSerializer.
                System.Runtime.Serialization.DataContractSerializer serializer =
                    new System.Runtime.Serialization.DataContractSerializer(type);

                // Create a file stream to read into.
                reader = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                // Read into object.
                testArtifact = serializer.ReadObject(reader) as TestArtifact;
            }
            catch
            {
                throw;
            }
            finally
            {
                if (reader != null)
                {
                    // Close file.
                    reader.Close();
                }
            }

            return(testArtifact);
        }
Beispiel #7
0
        private string DetectMethod(string textToTranslate, string authToken)
        {
            //Keep appId parameter blank as we are sending access token in authorization header.
            CultureInfo ci            = CultureInfo.InstalledUICulture;
            string      currentLocale = ci.TwoLetterISOLanguageName;
            string      uri           = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + textToTranslate + "&from=&to=en";

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Headers.Add("Authorization", authToken);
            WebResponse response = null;

            try
            {
                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                    string translatedText = (string)dcs.ReadObject(stream);
                    return(translatedText);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }
        private string SendTranslateRequest(string authToken, string text, string sourceLanguage, string destinationLanguage)
        {
            string         uri            = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(text) + "&from=" + sourceLanguage + "&to=" + destinationLanguage;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
            httpWebRequest.Headers.Add("Authorization", authToken);
            string translation = "";

            try
            {
                using (WebResponse response = httpWebRequest.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                        translation = (string)dcs.ReadObject(stream);
                    }
                }
            }
            catch
            {
                throw;
            }

            return(translation);
        }
Beispiel #9
0
        private static string DetectLangInternal(string authToken, string textToDetect)
        {
            //Keep appId parameter blank as we are sending access token in authorization header.
            string         uri            = "http://api.microsofttranslator.com/v2/Http.svc/Detect?text=" + textToDetect;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Headers.Add("Authorization", authToken);
            WebResponse response = null;
            string      languageDetected;

            try
            {
                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                    languageDetected = (string)dcs.ReadObject(stream);
                }
            }

            catch
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
            return(languageDetected);
        }
 private static void TranslateMethod(string authToken)
 {
     string text = "Use pixels to express measurements for padding and margins.";
     string from = "en";
     string to = "de";
     string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(text) + "&from=" + from + "&to=" + to;
     HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
     httpWebRequest.Headers.Add("Authorization", authToken);
     WebResponse response = null;
     try
     {
         response = httpWebRequest.GetResponse();
         using (Stream stream = response.GetResponseStream())
         {
             System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
             string translation = (string)dcs.ReadObject(stream);
             Console.WriteLine("Translation for source text '{0}' from {1} to {2} is", text, "en", "de");
             Console.WriteLine(translation);
         }
         Console.WriteLine("Press any key to continue...");
         Console.ReadKey(true);
     }
     catch
     {
         throw;
     }
     finally
     {
         if (response != null)
         {
             response.Close();
             response = null;
         }
     }
 }
Beispiel #11
0
        static void Main()
        {
            Record record1 = new Record(1, 2, "+", 3);

            Console.WriteLine("Original record: {0}", record1.ToString());

            MemoryStream stream1 = new MemoryStream();

            //Serialize the Record object to a memory stream using DataContractSerializer.
            System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(Record));
            serializer.WriteObject(stream1, record1);

            stream1.Position = 0;

            //Deserialize the Record object back into a new record object
            Record record2 = (Record)serializer.ReadObject(stream1);

            Console.WriteLine("Deserialized record: {0}", record2.ToString());

            MemoryStream stream2 = new MemoryStream();

            XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream2);

            serializer.WriteObject(binaryDictionaryWriter, record1);
            binaryDictionaryWriter.Flush();

            //report the length of the streams
            Console.WriteLine("Text Stream is {0} bytes long", stream1.Length);
            Console.WriteLine("Binary Stream is {0} bytes long", stream2.Length);

            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client.");
            Console.ReadLine();
        }
Beispiel #12
0
        public static object LoadFromFile(string fileName, Type t)
        {
            object o = null;
            try
            {
                byte[] fileContents = File.ReadAllBytes(fileName);

                byte[] decryptedData = Encryption.DecryptData(fileContents);

                using (MemoryStream stream = new MemoryStream())
                {
                    stream.Write(decryptedData, 0, decryptedData.Length);

                    stream.Position = 0;

                    DataContractSerializer serializer = new DataContractSerializer(t);

                    o = serializer.ReadObject(stream);
                }
            }
            catch (Exception ex)
            {
            }
            return o;
        }
        public object receiveByID(string MessageID, string InputQueue)
        {
            // Open existing queue
            using (MessageQueue queue = new MessageQueue(InputQueue))
            {
                //Peek to find message with the MessageID in the label
                while (true)
                {
                    Message[] peekedmessage = queue.GetAllMessages();
                    foreach (Message m in peekedmessage)
                    {
                        if (m.Label.StartsWith(MessageID))
                        {
                            using (Message message = queue.ReceiveById(m.Id))
                            {
                                RequestGuid = MessageID;
                                // Gets object type from the message label
                                Type objType = Type.GetType(message.Label.Split('|')[1], true, true);

                                // Derializes object from the stream
                                DataContractSerializer serializer = new DataContractSerializer(objType);
                                return serializer.ReadObject(message.BodyStream);
                            }
                        }
                    }
                    System.Threading.Thread.Sleep(10);
                }
            }
        }
Beispiel #14
0
 /// <summary>
 /// Override this method to manually deserialize child objects
 /// from data in the serialization stream.
 /// </summary>
 /// <param name="info">Object containing serialized values.</param>
 /// <param name="formatter">Reference to the current MobileFormatter.</param>
 protected virtual void OnSetChildren(SerializationInfo info, MobileFormatter formatter)
 {
     if (info.Values.ContainsKey("$list"))
     {
         bool mobileChildren = typeof(IMobileObject).IsAssignableFrom(typeof(T));
         if (mobileChildren)
         {
             List <int> references = (List <int>)info.Values["$list"].Value;
             foreach (int reference in references)
             {
                 T child = (T)formatter.GetObject(reference);
                 this.Add(child);
             }
         }
         else
         {
             byte[] buffer = (byte[])info.Values["$list"].Value;
             using (MemoryStream stream = new MemoryStream(buffer))
             {
                 serialization.DataContractSerializer dcs = new serialization.DataContractSerializer(GetType());
                 MobileList <T> list = (MobileList <T>)dcs.ReadObject(stream);
                 AddRange(list);
             }
         }
     }
 }
Beispiel #15
0
        public List <string> GetLanguagesForSpeakMethod()
        {
            string         uri            = "http://api.microsofttranslator.com/v2/Http.svc/GetLanguagesForSpeak";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Headers.Add("Authorization", _authToken);
            WebResponse response = null;

            try
            {
                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(typeof(List <string>));
                    List <string> languagesForSpeak = (List <string>)dcs.ReadObject(stream);
                    return(languagesForSpeak);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }
Beispiel #16
0
        private string Translate(string authToken)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(string.Format(URI, System.Web.HttpUtility.UrlEncode(sourceText), fromLanguage, toLanguage));

            httpWebRequest.Headers.Add("Authorization", authToken);
            WebResponse response = null;

            try
            {
                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                    return((string)dcs.ReadObject(stream));
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }
Beispiel #17
0
        private string DetectMethod(string textToDetect)
        {
            string         uri            = "http://api.microsofttranslator.com/v2/Http.svc/Detect?text=" + textToDetect;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Headers.Add("Authorization", _authToken);
            WebResponse response = null;

            try
            {
                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                    string languageDetected = (string)dcs.ReadObject(stream);
                    return(languageDetected);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }
        /// <summary>
        /// Tries to deserialized instance of <see cref="SqlDatabaseManagementError"/> to its object equivalent.
        /// A return value indicates whether the conversion succeeded or failed.
        /// </summary>
        /// <param name="input">A stream that contains a serialized instance of <see cref="SqlDatabaseManagementError"/> to convert.</param>
        /// <param name="result">When the method returns, contains the deserialized <see cref="SqlDatabaseManagementError"/> object,
        /// if the conversion succeeded, or <c>null</c>, if the conversion failed.</param>
        /// <returns><c>true</c> if the input parameter is successfully converted; otherwise, <c>false</c>.</returns>
        public static bool TryParse(string input, out SqlDatabaseManagementError result)
        {
            result = null;

            if (input == null)
            {
                return false;
            }

            // Deserialize the stream using DataContractSerializer.
            try
            {
                using (XmlDictionaryReader xmlReader = XmlDictionaryReader.CreateTextReader(
                    Encoding.UTF8.GetBytes(input),
                    new XmlDictionaryReaderQuotas()))
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(SqlDatabaseManagementError));
                    result = (SqlDatabaseManagementError)serializer.ReadObject(xmlReader, true);
                    return true;
                }
            }
            catch (Exception)
            {
            }

            return false;
        }
Beispiel #19
0
        public async Task <string> Translate(string text, string from, string to)
        {
            if (Auth == null)
            {
                Auth = new AdmAuthentication(ClientID, ClientSecret);
                await Auth.Init();
            }
            var            at             = Auth.AccessToken.access_token;
            string         uri            = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + Uri.EscapeDataString(text) + "&from=" + from + "&to=" + to;
            HttpWebRequest httpWebRequest = WebRequest.CreateHttp(uri);

            httpWebRequest.Headers["Authorization"] = "Bearer " + at;
            WebResponse response = null;

            response = await httpWebRequest.GetResponseAsync();

            string translation;

            using (Stream stream = response.GetResponseStream())
            {
                System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                translation = (string)dcs.ReadObject(stream);
            }
            return(translation);
        }
        public static async Task RestoreAsync()
        {
            _sessionState = new Dictionary<String, Object>();

            try
            {
                StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename);
                using (IInputStream inStream = await file.OpenSequentialReadAsync())
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
                    _sessionState = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());
                }

                foreach (var weakFrameReference in _registeredFrames)
                {
                    Frame frame;
                    if (weakFrameReference.TryGetTarget(out frame))
                    {
                        frame.ClearValue(FrameSessionStateProperty);
                        RestoreFrameNavigationState(frame);
                    }
                }
            }
            catch (Exception e)
            {
                throw new SuspensionManagerException(e);
            }
        }
Beispiel #21
0
        public object Parse(string xml, Type type)
        {
            try
            {
                var bytes = Encoding.UTF8.GetBytes(xml);

#if MONOTOUCH
                using (var reader = XmlDictionaryReader.CreateTextReader(bytes, null))
#elif SILVERLIGHT && !WINDOWS_PHONE
                using (var reader = XmlDictionaryReader.CreateTextReader(bytes, XmlDictionaryReaderQuotas.Max))
#elif WINDOWS_PHONE
                using (var reader = XmlDictionaryReader.CreateBinaryReader(bytes, XmlDictionaryReaderQuotas.Max))
#else
                using (var reader = XmlDictionaryReader.CreateTextReader(bytes, this.quotas))
#endif
                {
                    var serializer = new System.Runtime.Serialization.DataContractSerializer(type);
                    return(serializer.ReadObject(reader));
                }
            }
            catch (Exception ex)
            {
                throw new SerializationException("DeserializeDataContract: Error converting type: " + ex.Message, ex);
            }
        }
Beispiel #22
0
        private void deserializeInvoice_Click(object sender, EventArgs e)
        {
            var serializer = new DataContractSerializer(typeof(Invoice));

            var reader = XmlReader.Create(new StringReader(objectData.Text));

            try
            {
                var invoice = (Invoice)serializer.ReadObject(reader);
                var msg = "== Invoice Customer:\nName: " + invoice.Customer.FirstName + " " + invoice.Customer.LastName + "\nBirth Date: " + invoice.Customer.BirthDate;

                msg += "\n\n== Products";

                for (int index = 0; index < invoice.Products.Count; index++)
                {
                    msg += "\n== == Product " + index;
                    msg += "\n== Name: " + invoice.Products[index].Name;
                    msg += "\n== Price: " + invoice.Products[index].Price;
                }

                MessageBox.Show(msg);
            }
            catch (Exception)
            {
                MessageBox.Show("Object couldn't be deserialized.\nCheck you input data.");
            }
        }
        public void Client_writeToFileTest()
        {
            Client testUser = new Client("testUser","5555");

            testUser.writeToFile();

            #region ReadClientObjectFromFile

                string pathToDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                string USER_LOCATION = "\\users\\";
                string XML_EXT = ".xml";
                string writePath = pathToDir + USER_LOCATION + testUser.Name + XML_EXT;

            Client tempObj;

            //Reads from the xml file for the client.
            using (FileStream reader = new FileStream(writePath, FileMode.Open, FileAccess.Read))
            {
                DataContractSerializer ser = new DataContractSerializer(typeof(Client));
                tempObj = (Client)ser.ReadObject(reader);
            }

            Assert.AreEqual(testUser.Name, tempObj.Name);
            Assert.AreEqual(testUser.Online, tempObj.Online);
            Assert.AreEqual(testUser.Password, tempObj.Password);

            #endregion
        }
        public async Task RequiredDataIsProvided_AndModelIsBound_NoValidationErrors()
        {
            // Arrange
            var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
            var client = server.CreateClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml-dcs"));
            var input = "<Store xmlns=\"http://schemas.datacontract.org/2004/07/XmlFormattersWebSite\" " +
                        "xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><Address><State>WA</State><Zipcode>" +
                        "98052</Zipcode></Address><Id>10</Id></Store>";
            var content = new StringContent(input, Encoding.UTF8, "application/xml-dcs");

            // Act
            var response = await client.PostAsync("http://localhost/Validation/CreateStore", content);

            //Assert
            var dcsSerializer = new DataContractSerializer(typeof(ModelBindingInfo));
            var responseStream = await response.Content.ReadAsStreamAsync();
            var modelBindingInfo = dcsSerializer.ReadObject(responseStream) as ModelBindingInfo;
            Assert.NotNull(modelBindingInfo);
            Assert.NotNull(modelBindingInfo.Store);
            Assert.Equal(10, modelBindingInfo.Store.Id);
            Assert.NotNull(modelBindingInfo.Store.Address);
            Assert.Equal(98052, modelBindingInfo.Store.Address.Zipcode);
            Assert.Equal("WA", modelBindingInfo.Store.Address.State);
            Assert.Empty(modelBindingInfo.ModelStateErrorMessages);
        }
        public static DalConfig ParseDalConfigXml(string dalConfigXml)
        {
            try
            {
                var ser = new DataContractSerializer(typeof (config.models.old.DalConfig));
                var config =
                    (config.models.old.DalConfig) ser.ReadObject(XmlReader.Create(new StringReader(dalConfigXml)));

                // now try to read and parse the the connection string
                var connString =
                    ConfigurationManager.ConnectionStrings[config.ApplicationConnectionString]?.ConnectionString;

                var csb = new SqlConnectionStringBuilder(connString);

                return new DalConfig()
                {
                    DesignerConnection = new DesignerConnection()
                    {
                        Authentication =
                            ((config.DesignerConnection?.Authentication ?? new SimpleDataAccessLayer.Common.config.models.old.WindowsAuthentication()) is
                                SimpleDataAccessLayer.Common.config.models.old.WindowsAuthentication)
                                ? new config.models.Authentication { AuthenticationType = AuthenticationType.WindowsAuthentication}
                                : new config.models.Authentication
                                {
                                    AuthenticationType = AuthenticationType.SqlAuthentication,
                                    SavePassword = true,
                                    UserName =
                                        ((config.models.old.SqlAuthentication) config.DesignerConnection?.Authentication)
                                            ?.UserName,
                                    Password =
                                        ((config.models.old.SqlAuthentication) config.DesignerConnection?.Authentication)
                                            ?.Password
                                },
                        DatabaseName = csb.InitialCatalog,
                        ServerName = csb.DataSource

                    },
                    RuntimeConnectionStringName = config.ApplicationConnectionString,
                    Namespace = config.Namespace,
                    Enums = config.Enums?.Select(e => new SimpleDataAccessLayer.Common.config.models.Enum()
                    {
                        Schema = e.Schema,
                        Alias = e.Alias,
                        ValueColumn = e.ValueColumn,
                        KeyColumn = e.KeyColumn,
                        TableName = e.TableName
                    }).ToList(),
                    Procedures = config.Procedures?.Select(p => new Procedure()
                    {
                        Alias = p.Alias,
                        Schema = p.Schema,
                        ProcedureName = p.ProcedureName
                    }).ToList()
                };
            }
            catch (Exception e)
            {
                throw new DalConfigXmlConverterException("Failed to parse DalConfig XML", e);
            }
        }
Beispiel #26
0
        public void assure_object_graph_is_Serialized_correctly()
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(IEnumerable<Changeset>), null, int.MaxValue, false, false, null);


            ChangesetServer server = new ChangesetServer() { Name = "Test name", Url = "http://www.smeedee.org" };
            Changeset changeset = new Changeset() { Server = server, Comment = "SmeeDee", Revision = 1001, Author = new Author("tuxbear")};
            Changeset changeset2 = new Changeset() { Server = server, Comment = "SmeeDee2", Revision = 1002, Author = new Author("tuxbear")};
            
            server.Changesets.Add(changeset);
            server.Changesets.Add(changeset2);
            

            MemoryStream stream = new MemoryStream();

            serializer.WriteObject(stream, new [] {changeset, changeset2});
            stream.Position = 0;

            object deSerialized = serializer.ReadObject(stream);

            var changesets = deSerialized as IEnumerable<Changeset>;
            var firstDeserialized = changesets.ElementAt(0);
            firstDeserialized.Revision.ShouldBe(1001);
            var secondDeserialized = changesets.ElementAt(1);
            secondDeserialized.Revision.ShouldBe(1002);
        }
Beispiel #27
0
 public static void Load()
 {
     DataContractSerializer dcs = new DataContractSerializer(typeof(TagDB));
     XmlReader xmlr = XmlReader.Create("TagDBase.xml");
     dcs.ReadObject(xmlr);
     xmlr.Close();
 }
        public void Data_contract_serialization_will_change_the_type_of_a_collection()
        {
            using (var session = DataAccess.OpenSession())
            {
                var forum = session.Get<ForumModel>(1);

            Assert.AreEqual(typeof(NHibernate.Collection.Generic.PersistentGenericBag<TopicModel>), forum.Topics.GetType());

            var knownTypes = new List<Type>
                                 {
                                     typeof (TopicModel),
                                     typeof (NHibernate.Collection.Generic.PersistentGenericBag<TopicModel>),
                                     typeof (NHibernate.Impl.CollectionFilterImpl)
                                 };
                var serializer = new   DataContractSerializer(typeof(ForumModel), knownTypes);

            //serialize company to a memory stream
            Stream stream = new MemoryStream();
            serializer.WriteObject(stream, forum);
            Console.WriteLine();
            //deserialize the memory stream back to a company
            stream.Position = 0;
            forum = (ForumModel)serializer.ReadObject(stream);

            Assert.AreNotEqual(typeof(NHibernate.Collection.Generic.PersistentGenericBag<TopicModel>), forum.Topics.GetType());
            Assert.AreEqual(typeof(TopicModel[]), forum.Topics.GetType());
            }
        }
Beispiel #29
0
        public async Task<List<SourceDTO>> GetStoredSources(string userId)
        {
            try
            {
                await
                    ApplicationData.Current.LocalFolder.CreateFolderAsync(String.Format(@"{0}/", userId),
                        CreationCollisionOption.FailIfExists);
            }
            catch
            {
            }

            try
            {
                var file = await ApplicationData.Current.LocalFolder.GetFileAsync(String.Format(@"{0}/sources.xml", userId));

                var fileStream = await file.OpenStreamForReadAsync();

                var serializer = new DataContractSerializer(typeof(List<SourceDTO>));

                return serializer.ReadObject(fileStream) as List<SourceDTO>;
            }
            catch (Exception)
            {
                return new List<SourceDTO>();

            }
        }
Beispiel #30
0
            public async Task <TValue> RefreshAsync()
            {
                var kts = _knownTypes;

                return(await await
                       Task.Factory.StartNew(
                           async() =>
                {
                    var ms = new MemoryStream();
                    var ser = new System.Runtime.Serialization.DataContractSerializer(typeof(TValue), kts);
                    using (var strm = await _streamOpener(StreamOpenType.Read))
                    {
                        await strm.CopyToAsync(ms);
                    }
                    if (ms.Length == 0)
                    {
                        return default(TValue);
                    }
                    ms.Position = 0;

                    var obj = (TValue)ser.ReadObject(ms);
                    Value = obj;
                    return obj;
                },
                           CancellationToken.None,
                           TaskCreationOptions.AttachedToParent,
#if NET45
                           _sch.ConcurrentScheduler
#else
                           _sch
#endif

                           ));
            }
Beispiel #31
0
		public void TestSerializeDateTimeOffsetNullable ()
		{
			 // Create the writer object.
			StringBuilder stringBuilder = new StringBuilder ();

			DateTimeOffset? dto = new DateTimeOffset (2012, 05, 04, 02, 34, 00, new TimeSpan (-2, 0, 0));;

			DataContractSerializer ser = new DataContractSerializer (typeof (DateTimeOffset?));

			using (var xw = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (new StringWriter (stringBuilder))))
			{
				ser.WriteObject (xw, dto);
			}

			string actualXml   = stringBuilder.ToString ();
			string expectedXml = "<?xml version=\"1.0\" encoding=\"utf-16\"?><DateTimeOffset xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/System\"><DateTime>2012-05-04T04:34:00Z</DateTime><OffsetMinutes>-120</OffsetMinutes></DateTimeOffset>";
			
			Assert.AreEqual (expectedXml, actualXml, "#1 Nullable DateTimeOffset serialization error");

			using (var xr = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create (new StringReader (actualXml))))
			{
				DateTimeOffset? actualDto = (DateTimeOffset?)ser.ReadObject (xr, true);

				Assert.AreEqual (dto, actualDto, "#2 Nullable DateTimeOffset deserialization error");
			}
		}
 //Liefert den eingeloggten Benutzer
 private Benutzer GetBenutzer(Benutzer benutzer)
 {
     HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri + "benutzer/" + benutzer.ID + "/");
     webrequest.Method = "GET";
     HttpWebResponse webresponse = null;
     try
     {
         webresponse = (HttpWebResponse)webrequest.GetResponse();
         HttpStatusCode rc = webresponse.StatusCode;
         DataContractSerializer serl = new DataContractSerializer(typeof(Benutzer));
         return (Benutzer)serl.ReadObject(webresponse.GetResponseStream());
     }
     catch (WebException we)
     {
         if (we.Response != null)
         {
             webresponse = (HttpWebResponse)we.Response;
             MessageBox.Show(webresponse.StatusDescription + "!", "Fehler");
         }
         return null;
     }
     finally
     {
         if (webresponse != null)
             webresponse.Close();
     }
 }
        /// <summary>
        /// <para>Deserialize target's ReactiveProperty value.</para>
        /// <para>Deserialize order is at first DataMemberAttribute' Order, second alphabetical order.</para>
        /// </summary>
        /// <param name="target">ReactiveProperty holder(such as ViewModel).</param>
        /// <param name="packedData">Serialized string.</param>
        public static void UnpackReactivePropertyValue(object target, string packedData)
        {
            Dictionary<string, object> values;
            var serializer = new DataContractSerializer(typeof(Dictionary<string, object>));
            using (var sr = new StringReader(packedData))
            using (var reader = XmlReader.Create(sr))
            {
                values = (Dictionary<string, object>)serializer.ReadObject(reader);
            }

            var query = GetIValueProperties(target)
                .Select(pi =>
                {
                    var attr = (DataMemberAttribute)pi.GetCustomAttributes(typeof(DataMemberAttribute), false).FirstOrDefault();
                    var order = (attr != null) ? attr.Order : int.MinValue;
                    return new { pi, order };
                })
                .OrderBy(a => a.order)
                .ThenBy(a => a.pi.Name);

            foreach (var item in query)
            {
                object value;
                if (values.TryGetValue(item.pi.Name, out value))
                {
                    var ivalue = (IReactiveProperty)item.pi.GetValue(target, null);
                    if (ivalue != null) ivalue.Value = value;
                }
            }
        }
Beispiel #34
0
		public void TestSerializeNullDateTimeOffsetNullable ()
		{
			 // Create the writer object.
			StringBuilder stringBuilder = new StringBuilder ();

			DateTimeOffset? dto = null;

			DataContractSerializer ser = new DataContractSerializer (typeof (DateTimeOffset?));

			using (var xw = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (new StringWriter (stringBuilder))))
			{
				ser.WriteObject (xw, dto);
			}

			string actualXml   = stringBuilder.ToString ();
			string expectedXml = "<?xml version=\"1.0\" encoding=\"utf-16\"?><DateTimeOffset i:nil=\"true\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/System\" />";
			
			Assert.AreEqual (expectedXml, actualXml, "#1 Null DateTimeOffset? serialization error");

			using (var xr = XmlDictionaryReader.CreateDictionaryReader (XmlReader.Create (new StringReader (actualXml))))
			{
				DateTimeOffset? actualDto = (DateTimeOffset?)ser.ReadObject (xr, true);

				Assert.AreEqual (dto, actualDto, "#2 Null DateTimeOffset? deserialization error");
				Assert.IsNull (actualDto, "#3 Null DateTimeOffset? deserialization error");
			}
		}
Beispiel #35
0
        static void Main()
        {
            Record record1 = new Record(1, 2, "+", 3);
            Console.WriteLine("Original record: {0}", record1.ToString());

            MemoryStream stream1 = new MemoryStream();

            //Serialize the Record object to a memory stream using DataContractSerializer.
            System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(Record));
            serializer.WriteObject(stream1, record1);

            stream1.Position = 0;

            //Deserialize the Record object back into a new record object
            Record record2 = (Record)serializer.ReadObject(stream1);

            Console.WriteLine("Deserialized record: {0}", record2.ToString());

            MemoryStream stream2 = new MemoryStream();

            XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream2);
            serializer.WriteObject(binaryDictionaryWriter, record1);
            binaryDictionaryWriter.Flush();

            //report the length of the streams
            Console.WriteLine("Text Stream is {0} bytes long", stream1.Length);
            Console.WriteLine("Binary Stream is {0} bytes long", stream2.Length);

            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client.");
            Console.ReadLine();
        }
        public static List <TestBreakpoint> ReadFromFile()
        {
            FileStream            reader      = null;
            List <TestBreakpoint> breakpoints = new List <TestBreakpoint>();

            if (!string.IsNullOrEmpty(SerializationFile))
            {
                try
                {
                    // Create DataContractSerializer.
                    DataContractSerializer serializer =
                        new System.Runtime.Serialization.DataContractSerializer(typeof(List <TestBreakpoint>));

                    // Create a file stream to read into.
                    reader = new FileStream(SerializationFile, FileMode.Open, FileAccess.Read);

                    // Read into object.
                    _breakpoints = serializer.ReadObject(reader) as List <TestBreakpoint>;
                }
                catch
                {
                    throw;
                }
                finally
                {
                    if (reader != null)
                    {
                        // Close file.
                        reader.Close();
                    }
                }
            }

            return(breakpoints);
        }
Beispiel #37
0
        public async void GetGenreFromAPI()
        {

            NieuweGenres = new ObservableCollection<Genre>();
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Add(new
                System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
              
                HttpResponseMessage response = await client.GetAsync("http://localhost:18358/api/Genre");

                if (response.IsSuccessStatusCode)
                {
                    try
                    {
                        Stream stream = await response.Content.ReadAsStreamAsync();
                        DataContractSerializer dxml = new DataContractSerializer(typeof(List<FestivalLibPortable.Genre>));
                        Genres = dxml.ReadObject(stream) as List<Genre>;
                        
                    }
                    catch (Exception e)
                    {
                    }
                    
                }
                foreach (Genre g in Genres)
                {
                    NieuweGenres.Add(g);
                }
            
        }
        public CompetitionClassModel Load()
        {
            using (XmlReader reader = XmlReader.Create(path, new XmlReaderSettings { CloseInput = true }))
            {
                var serializer = new DataContractSerializer(typeof (CompetitionClassModelXml));

                try
                {
                    var xmlObject = (CompetitionClassModelXml) serializer.ReadObject(reader);
                    return CompetitionClassModelXml.FromXmlObject(xmlObject);
                }
                catch (Exception ex)
                {
                    Log.Error("Failed to load model from XML file.", ex);
                    string message = $"Failed to load run configuration from file:\n\n{path}\n\n" +
                        $"Error message: {ex.Message}\n\nClick Ok to discard this file and use default settings.\n" +
                        "Click Cancel to close this application without making changes.";
                    DialogResult response = MessageBox.Show(message, "Error - Dog Agility Competition Management System",
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
                    if (response == DialogResult.OK)
                    {
                        return new CompetitionClassModel();
                    }

                    Environment.Exit(0);
                    throw;
                }
            }
        }
Beispiel #39
0
    protected void OnTranslateButtonClicked(object sender, EventArgs e)
    {
        string fromText = fromTextInput.Buffer.Text;
        string toText = "";

        AdmAuthentication admAuth = new AdmAuthentication("", "");
        AdmAccessToken admToken = admAuth.GetAccessToken();

        string encodedFromText = System.Web.HttpUtility.UrlEncode(fromText);
        string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(fromText) + "&from=" + "en" + "&to=" + "ru";
        string authToken = "Bearer" + " " + admToken.access_token;

        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
        httpWebRequest.Headers.Add("Authorization", authToken);

        WebResponse response = httpWebRequest.GetResponse();
        //		try
        //		{
            response = httpWebRequest.GetResponse();
            using (Stream stream = response.GetResponseStream())
            {
            System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(System.Type.GetType("System.String"));
                toText = (string)dcs.ReadObject(stream);
            }
        //		}

        toTextInput.Buffer.Text = toText;
    }
        public static KeyMapCollection Load(string game, KeyMapCollection defaultKeyMap)
        {
            DataContractSerializer x = new DataContractSerializer(typeof(KeyMapCollection));
            KeyMapCollection finalCollection = new KeyMapCollection(defaultKeyMap);
            StreamReader stm = null;
            try
            {
                string filepath = KeyMapCollection.GetSettingsPath(game);
                stm = new StreamReader(filepath);

                KeyMapCollection savedCollection = (KeyMapCollection)x.ReadObject(stm.BaseStream);

                foreach (KeyMap finalkm in finalCollection.keyMaps.Values)
                    // if tha keymap by this name exists on disk
                    if (savedCollection.keyMaps.ContainsKey(finalkm.Alias))
                    {
                        KeyMap savedkm = savedCollection.keyMaps[finalkm.Alias];
                        // load those preferences, overriding the defaults
                        finalkm.LoadOverrides(savedkm);
                    }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error in LoadKeyMap " + e.StackTrace);
            }
            finally
            {
                if (stm != null)
                    stm.Close();
            }
            return finalCollection;
        }
        //Methods
        public MemberList LoadMemberList()
        {
            try
            {
                MemberList loaded = null;

                if (System.IO.File.Exists(this.fullFilePath))
                {
                    using (FileStream readFileStream = new FileStream(this.fullFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        DataContractSerializer deserializer = new DataContractSerializer(typeof(MemberList));
                        loaded = (MemberList)deserializer.ReadObject(readFileStream);
                    }

                    if (loaded != null)
                    {
                        //setup subscriptions
                        loaded.SetupSubscriptions();
                    }

                    return loaded;
                }
            }
            catch { }

            return null;
        }
Beispiel #42
0
        static void Main(string[] args)
        {
            var path = "data.xml";
            InitializeFile(path);

            Person p = new Person
            {
                Id = 1,
                Name = "John Doe"
            };

            using (Stream stream = new FileStream(path, FileMode.Open))
            {
                DataContractSerializer ser = new DataContractSerializer(typeof(Person));
                ser.WriteObject(stream, p);
                Console.WriteLine("Serialized ...");
            }

            using (Stream stream = new FileStream(path, FileMode.Open))
            {
                DataContractSerializer ser = new DataContractSerializer(typeof(Person));
                Person result = (Person)ser.ReadObject(stream);
                Console.WriteLine("Deserialize ...");
            }

            Console.Write("Press a key to exit ... ");
            Console.ReadKey();
        }
        /// <summary>
        /// Populates the products from store file.
        /// </summary>
        private async Task ReadXmlDataFromLocalStorageAsync()
        {
            try
            {
                //If product list is already loaded from XML file, skip reloading it again. 
                if (_productDataSource.AllProducts != null)
                    return;

                var dataFolder = await Package.Current.InstalledLocation.GetFolderAsync(Constants.DataFilesFolder);
                StorageFile sessionFile = await dataFolder.GetFileAsync(Constants.ProductFile);

                using (
                    IRandomAccessStreamWithContentType sessionInputStream =
                        await sessionFile.OpenReadAsync())
                {

                    var sessionSerializer = new DataContractSerializer(typeof(List<Product>));
                    var restoredData = sessionSerializer.ReadObject(sessionInputStream.AsStreamForRead());
                    _allProducts = (List<Product>)restoredData;
                }

            }
            catch (Exception ex)
            {
                _allProducts = null;
            }
        }
        public static FontCollection Load(string fontCollectionFile)
        {
            var file       = System.IO.File.OpenRead(fontCollectionFile);
            var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(FontCollection), new Type[] { typeof(Font) });

            return(serializer.ReadObject(file) as FontCollection);
        }
        private static TestProfile deserializeFromFile(string filePath)
        {
            FileStream  reader      = null;
            TestProfile TestProfile = null;

            try
            {
                // Create DataContractSerializer.
                System.Runtime.Serialization.DataContractSerializer serializer =
                    new System.Runtime.Serialization.DataContractSerializer(typeof(TestProfile));

                // Create a file stream to read into.
                reader = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                // Read into object.
                TestProfile = serializer.ReadObject(reader) as TestProfile;
            }
            catch
            {
                throw;
            }
            finally
            {
                if (reader != null)
                {
                    // Close file.
                    reader.Close();
                }
            }

            return(TestProfile);
        }
 private List<Benutzer> GetBenutzer()
 {
     HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri + "benutzer/");
     webrequest.Method = "GET";
     HttpWebResponse webresponse = null;
     try
     {
         webresponse = (HttpWebResponse)webrequest.GetResponse();
         HttpStatusCode rc = webresponse.StatusCode;
         DataContractSerializer serl = new DataContractSerializer(typeof(List<Benutzer>));
         return (List<Benutzer>)serl.ReadObject(webresponse.GetResponseStream());
     }
     catch (WebException we)
     {
         if (we.Response != null)
         {
             webresponse = (HttpWebResponse)we.Response;
             MessageBox.Show(webresponse.StatusDescription + "!", "Fehler");
         }
         else
         {
             MessageBox.Show("Server nicht erreichbar!", "Fehler");
         }
         return new List<Benutzer>();
     }
     finally
     {
         if (webresponse != null)
             webresponse.Close();
     }
 }
        private static void GetLanguagesForTranslate(string authToken)
        {
            string         uri            = "http://api.microsofttranslator.com/v2/Http.svc/GetLanguagesForTranslate";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Headers.Add("Authorization", authToken);
            WebResponse response = null;

            try
            {
                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(typeof(List <string>));

                    List <string> languagesForTranslate = (List <string>)dcs.ReadObject(stream);
                    Console.WriteLine("The languages available for translation are: ");
                    languagesForTranslate.ForEach(a => Console.WriteLine(a));
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey(true);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }
        //public static List<EB06> getEB06List()
        //{

        //    List<EB06> eb06 = new List<EB06>();
        //    eb06.Add(new EB06("", ""));
        //    eb06.Add(new EB06("6", "Hour"));
        //    eb06.Add(new EB06("7", "Day"));
        //    eb06.Add(new EB06("13", "24 Hours"));
        //    eb06.Add(new EB06("21", "Years", BenefitTimePeriod.Years));
        //    eb06.Add(new EB06("22", "Service Year", BenefitTimePeriod.ServiceYear));
        //    eb06.Add(new EB06("23", "Calendar Year", BenefitTimePeriod.CalendarYear));
        //    eb06.Add(new EB06("24", "Year to Date"));
        //    eb06.Add(new EB06("25", "Contract"));
        //    eb06.Add(new EB06("26", "Episode"));
        //    eb06.Add(new EB06("27", "Visit"));
        //    eb06.Add(new EB06("28", "Outlier"));
        //    eb06.Add(new EB06("29", "Remaining"));
        //    eb06.Add(new EB06("30", "Exceeded"));
        //    eb06.Add(new EB06("31", "Not Exceeded"));
        //    eb06.Add(new EB06("32", "Lifetime", BenefitTimePeriod.Lifetime));
        //    eb06.Add(new EB06("33", "Lifetime Remaining"));
        //    eb06.Add(new EB06("34", "Month"));
        //    eb06.Add(new EB06("35", "Week"));
        //    eb06.Add(new EB06("36", "Admisson"));
        //    return eb06;
        //}
        //public static List<EB09> getEB09List()
        //{

        //    List<EB09> eb09 = new List<EB09>();
        //    eb09.Add(new EB09("", ""));
        //    eb09.Add(new EB09("99", "Quantity Used"));
        //    eb09.Add(new EB09("CA", "Covered - Actual"));
        //    eb09.Add(new EB09("CE", "Covered - Estimated"));
        //    eb09.Add(new EB09("DB", "Deductible Blood Units"));
        //    eb09.Add(new EB09("DY", "Days"));
        //    eb09.Add(new EB09("HS", "Hours"));
        //    eb09.Add(new EB09("LA", "Life-time Reserve - Actual"));
        //    eb09.Add(new EB09("LE", "Life-time Reserve - Estimated"));
        //    eb09.Add(new EB09("MN", "Month", BenefitQuantity.Months));
        //    eb09.Add(new EB09("P6", "Number of Services or Procedures", BenefitQuantity.NumberOfServices));
        //    eb09.Add(new EB09("QA", "Quantity Approved"));
        //    eb09.Add(new EB09("S7", "Age, High Value", BenefitQuantity.AgeLimit));
        //    eb09.Add(new EB09("S8", "Age, Low Value"));
        //    eb09.Add(new EB09("VS", "Visits", BenefitQuantity.Visits));
        //    eb09.Add(new EB09("YY", "Years", BenefitQuantity.Years));
        //    return eb09;
        //}

        public static string translate(string msg, string lang)
        {
            AdmAuthentication _auth;

            _auth = new AdmAuthentication("hrdsq", "yHilGSmPryWnbkaBgsyV+qi8qn5v2gsBoAvA+YKZh14=");
            string         uri            = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + HttpUtility.UrlEncode(msg) + "&from=" + "en" + "&to=" + lang;
            string         authToken      = "Bearer" + " " + _auth.GetAccessToken().access_token;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Headers.Add("Authorization", authToken);
            WebResponse response = null;

            try
            {
                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                    string translation = (string)dcs.ReadObject(stream);
                    Console.WriteLine("Translation for source msg '{0}' from {1} to {2} is", msg, "en", lang);
                    return(translation);
                }
            }
            catch (Exception ex)
            {
                Library.WriteErrorLog(ex);
                return(msg);
            }
        }
        private static void DetectMethod(string authToken)
        {
            //Console.WriteLine("Enter Text to detect language:");
            //string textToDetect = Console.ReadLine();

            //DETECTION
            //Keep appId parameter blank as we are sending access token in authorization header.
            //string uri = "http://api.microsofttranslator.com/v2/Http.svc/Detect?text=" + textToDetect;

            //TRANSLATION
            //Keep appId parameter blank as we are sending access token in authorization header.
            string from        = "en";
            string to          = "fr";
            string englishText = "";

            using (TextReader reader = new StreamReader("sample.txt"))
            {
                englishText = reader.ReadToEnd();
            }
            Console.WriteLine("English");
            Console.WriteLine(englishText);
            Console.WriteLine("-----------");

            string uri = string.Concat("http://api.microsofttranslator.com/v2/Http.svc/Translate?text=", HttpUtility.UrlEncode(englishText),
                                       "&from=", from, "&to=", to);

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Headers.Add("Authorization", authToken);
            WebResponse response = null;

            try
            {
                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                    string translatedText = (string)dcs.ReadObject(stream);
                    Console.WriteLine("French");
                    Console.WriteLine(string.Format("Translation:{0}", translatedText));
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey(true);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }
Beispiel #50
0
        public object Deserialize(string serializedObject, Type type)
        {
            using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(serializedObject)))
            {
                var serializer = new System.Runtime.Serialization.DataContractSerializer(type, _settings);

                return(serializer.ReadObject(memoryStream));
            }
        }
Beispiel #51
0
        public static void Загрузить(string directory)
        {
            //не загружать если используется внешний кеш
            //if (MemoryCache.IsMemoryCacheClient)
            //    return;

            if (!System.IO.Directory.Exists(directory))
            {
                return;
            }

            lock (lockCacheXml)
            {
                Items.Clear();
                var ser = new System.Runtime.Serialization.DataContractSerializer(typeof(Dictionary <string, КешЭлемент>), КешЭлемент.KnownTypeList());
                foreach (var file in System.IO.Directory.GetFiles(directory, "*.cache"))
                {
                    if (new FileInfo(file).Length == 0)
                    {
                        continue;
                    }

                    //<KeyValueOfstringКешЭлементh9JraY4p>
                    //  <Key>5элемент:Z:КешИдентификаторРаздела:&amp;11d97d4f-2153-e211-bb73-0030487e046b</Key>
                    //  <Value xmlns:d3p1="http://schemas.datacontract.org/2004/07/RosService.Caching" i:type="d3p1:КешИдентификаторРаздела">
                    //    <d3p1:ДатаСоздания>2013-01-01T01:49:00.796875+04:00</d3p1:ДатаСоздания>
                    //    <d3p1:id_node>967854</d3p1:id_node>
                    //  </Value>
                    //</KeyValueOfstringКешЭлементh9JraY4p>

                    var fileXml = System.IO.File.ReadAllText(file);
                    //var xml = System.Xml.Linq.XDocument.Load(new StringReader(fileXml));
                    //foreach (var item in xml.Root.Elements().ToArray())
                    //{
                    //    if (item.Element(XName.Get("Key", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")).Value.Contains("КешИдентификаторРаздела"))
                    //        item.Remove();
                    //}

                    //var xml = System.Text.RegularExpressions.Regex.Replace(fileXml, @"<KeyValueOfstringКешЭлемент[\a\d]>(.+?)</KeyValueOfstringКешЭлемент[\a\d]>", "", RegexOptions.Multiline);
                    var obj = ser.ReadObject(XmlReader.Create(new StringReader(fileXml))) as Dictionary <string, КешЭлемент>;
                    if (obj != null)
                    {
                        foreach (var item in obj)
                        {
                            if (item.Value is КешХешьТаблицаПамять)
                            {
                                continue;
                            }
                            //else if (item.Value is КешСчётчик) continue;

                            Items.AddOrUpdate(item.Key, item.Value, (k, e) => e = item.Value);
                        }
                    }
                }
            }
        }
Beispiel #52
0
    public static List <Level> DeserializedJSONToLeves(string json)
    {
        List <Level> deserializedLevel = new List <Level>();
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));

        System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(deserializedLevel.GetType());
        deserializedLevel = ser.ReadObject(ms) as List <Level>;
        ms.Close();
        return(deserializedLevel);
    }
Beispiel #53
0
        //public static IQueryable<T> GetDataPaging<T>(this IEnumerable<T> entity, int RowsCount, int PageIndex, int PageSize)
        //{
        //    int startrow = PageSize * PageIndex;
        //    int lastrow = startrow + PageSize;


        //    return entity.Skip(startrow).Take(lastrow).AsQueryable<T>();


        //}
        //public static DataTable GetDataPaging<T>(this T entity, int PageIndex, int PageSize)where T:class
        //{
        //    int startrow = PageSize * PageIndex;
        //    int lastrow = startrow + PageSize;
        //    int rowcount=db.GetTable<T>().Count();
        //    DataTable dt = new DataTable();
        //    dt = db.GetTable <T>().CustomClone();
        //    for (int i = 0; i <= rowcount; i++)
        //    {
        //        if (i >= startrow && i <= lastrow)
        //        {
        //            dt.Merge(db.GetTable<T>().Skip(startrow).Take(lastrow).ConvertToDataTable());
        //            i = lastrow;
        //        }
        //        else
        //        {
        //            DataRow dr = dt.NewRow();
        //            dt.Rows.Add(dr);
        //        }
        //    }
        //    return dt;
        //}
        //public static int GetDataPagingCount<T>(this IEnumerable<T> entity)
        //{
        //    return entity.Count();
        //}
        // Convert type (var)any datasource to DataTable
        //public static DataTable ConvertToDataTable<T>(this  IEnumerable<T> varlist)
        //{
        //    DataTable dtReturn = new DataTable();

        //    // column names
        //    PropertyInfo[] oProps = null;

        //    if (varlist == null) return dtReturn;

        //    foreach (T rec in varlist)
        //    {
        //        // Use reflection to get property names, to create table, Only first time, others   will follow
        //        if (oProps == null)
        //        {
        //            oProps = ((Type)rec.GetType()).GetProperties();
        //            foreach (PropertyInfo pi in oProps)
        //            {
        //                Type colType = pi.PropertyType;

        //                if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()== typeof(Nullable<>)))
        //                {
        //                    colType = colType.GetGenericArguments()[0];
        //                }

        //                dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
        //            }
        //        }

        //        DataRow dr = dtReturn.NewRow();

        //        foreach (PropertyInfo pi in oProps)
        //        {
        //            dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);
        //        }

        //        dtReturn.Rows.Add(dr);
        //    }
        //    return dtReturn;
        //}
        #endregion

        public static T CloneBySerializer <T>(this T source) where T : class
        {
            var obj = new System.Runtime.Serialization.DataContractSerializer(typeof(T));

            using (var stream = new System.IO.MemoryStream())
            {
                obj.WriteObject(stream, source);
                stream.Seek(0, System.IO.SeekOrigin.Begin);
                return((T)obj.ReadObject(stream));
            }
        }
Beispiel #54
0
        public static ModEnvironmentConfiguration Load(System.IO.FileInfo xmlConfigFile)
        {
            var dcserializer = new System.Runtime.Serialization.DataContractSerializer(typeof(ModEnvironmentConfiguration));

            //var serializer = new System.Xml.Serialization.XmlSerializer(typeof(ModEnvironmentConfiguration));
            using (var fstream = xmlConfigFile.OpenRead())
            {
                var mec = (ModEnvironmentConfiguration)dcserializer.ReadObject(fstream);
                return(mec);
            }
        }
        public static T DeserializeWCF <T>(this string obj)
        {
            if (string.IsNullOrWhiteSpace(obj))
            {
                return(default(T));
            }
            var formatter = new System.Runtime.Serialization.DataContractSerializer(typeof(T));

            using (var sm = new System.Xml.XmlTextReader(new StringReader(obj)))
            {
                return((T)formatter.ReadObject(sm));
            }
        }
        public static string Detect(string authToken, string text)
        {
            string         uri            = "https://api.microsofttranslator.com/v2/Http.svc/Detect?text=" + text;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Headers.Add("Authorization", authToken);
            using (WebResponse response = httpWebRequest.GetResponse())
                using (Stream stream = response.GetResponseStream())
                {
                    System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                    return((string)dcs.ReadObject(stream));
                }
        }
Beispiel #57
0
        private static void BreakSentencesMethod(string authToken)
        {
            string         text           = "Use the Microsoft Translator webpage widget to deliver your site in the visitor’s language. The visitor never leaves your site, and the widget seamlessly translates each page as they navigate.";
            string         uri            = "http://api.microsofttranslator.com/v2/Http.svc/BreakSentences?text=" + text + "&language=en";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Headers.Add("Authorization", authToken);
            WebResponse response = null;

            try
            {
                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(typeof(List <int>));
                    List <int> result = (List <int>)dcs.ReadObject(stream);
                    Console.WriteLine(text);
                    Console.WriteLine("BreakSentences broke up the above sentence into " + result.Count + " sentences.");

                    int curPos = 0; //Set the current position to 0
                    for (int i = 0; i < result.Count; i++)
                    {
                        if (i == 0)
                        {
                            strTest = text.Substring(0, result[i] - 1);
                            curPos  = result[i];
                        }
                        else
                        {
                            strTest = text.Substring(curPos, result[i] - 1);
                            curPos += result[i];
                        }
                    }
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey(true);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }
Beispiel #58
0
        public void NotificationObjectShouldBeDataContractSerializable()
        {
            var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(TestNotificationObject));
            var stream     = new System.IO.MemoryStream();

            var testObject = new TestNotificationObject();

            serializer.WriteObject(stream, testObject);

            stream.Seek(0, System.IO.SeekOrigin.Begin);

            var reconstitutedObject = serializer.ReadObject(stream) as TestNotificationObject;

            Assert.IsNotNull(reconstitutedObject);
        }
Beispiel #59
0
        public string Detect(string text)
        {
            var lang = "";
            var uri  = new Uri("https://api.microsofttranslator.com/v2/Http.svc/Detect?text=" + text);

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", AuthToken);
                var stream = client.GetStreamAsync(uri).Result;

                DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                lang = (string)dcs.ReadObject(stream);
            }

            return(lang);
        }
Beispiel #60
0
        static public File_Finds FileLoad(string file_path)
        {
            if (File.Exists(file_path))
            {
                using (var fs = new FileStream(file_path, FileMode.Open))
                {
                    var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(File_Finds));

                    File_Finds file = (File_Finds)serializer.ReadObject(fs);

                    return(file);
                }
            }

            return(new File_Finds());
        }