Inheritance: XmlObjectSerializer
Exemple #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;
                        }
                    }
                }
            }
        }
        public void PingAdversary(ProximityDevice device, NotifyNfcReady notify)
        {
            if (subscribeId != -1)
            {
                proximityDevice.StopSubscribingForMessage(subscribeId);
                subscribeId = -1;
            }

            if (publishId != -1)
            {
                proximityDevice.StopPublishingMessage(publishId);
                publishId = -1;
            }

            if (state == NfcManager.ProtoState.Busy)
            {
                return;
            }

            state = NfcManager.ProtoState.NotReady;
            notifyReady = notify;
            initialMessage.devicetime = random.NextDouble();
            MemoryStream stream = new MemoryStream();
            DataContractSerializer serializer = new DataContractSerializer(initialMessage.GetType());
            serializer.WriteObject(stream, initialMessage);
            stream.Position = 0;
            var dataWriter = new DataWriter();
            dataWriter.WriteBytes(stream.GetBuffer());
            proximityDevice = device;
            publishId = proximityDevice.PublishBinaryMessage("Windows.CarTrumps", dataWriter.DetachBuffer());
            subscribeId = proximityDevice.SubscribeForMessage("Windows.CarTrumps", OnMessageReceived);
        }
        /// <summary>
        /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
        /// registered with <see cref="RegisterFrame"/> will also preserve their current
        /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
        /// to save its state.
        /// </summary>
        /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
        public static async Task SaveAsync()
        {
            try
            {
                // Save the navigation state for all registered frames
                foreach (var weakFrameReference in _registeredFrames)
                {
                    Frame frame;
                    if (weakFrameReference.TryGetTarget(out frame))
                    {
                        SaveFrameNavigationState(frame);
                    }
                }

                // Serialize the session state synchronously to avoid asynchronous access to shared
                // state
                MemoryStream sessionData = new MemoryStream();
                DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
                serializer.WriteObject(sessionData, _sessionState);

                // Get an output stream for the SessionState file and write the state asynchronously
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
                using (Stream fileStream = await file.OpenStreamForWriteAsync())
                {
                    sessionData.Seek(0, SeekOrigin.Begin);
                    await sessionData.CopyToAsync(fileStream);
                }
            }
            catch (Exception e)
            {
                throw new SuspensionManagerException(e);
            }
        }
Exemple #4
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");
			}
		}
    /// <summary>
    /// Den aktuellen <see cref="SessionState"/> speichern.  Alle <see cref="Frame"/>-Instanzen,
    /// die bei <see cref="RegisterFrame"/> registriert wurden, behalten ebenfalls ihren aktuellen
    /// Navigationsstapel bei, wodurch deren aktive <see cref="Page"/> eine Gelegenheit
    /// zum Speichern des zugehörigen Zustands erhält.
    /// </summary>
    /// <returns>Eine asynchrone Aufgabe, die das Speichern des Sitzungszustands wiedergibt.</returns>
    public static async Task SaveAsync()
    {
      try
      {
        // Navigationszustand für alle registrierten Rahmen speichern
        foreach (var weakFrameReference in _registeredFrames)
        {
          Frame frame;
          if (weakFrameReference.TryGetTarget(out frame))
          {
            SaveFrameNavigationState(frame);
          }
        }

        // Sitzungszustand synchron serialisieren, um einen asynchronen Zugriff auf den freigegebenen
        // Zustand
        MemoryStream sessionData = new MemoryStream();
        DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
        serializer.WriteObject(sessionData, _sessionState);

        // Einen Ausgabedatenstrom für die SessionState-Datei abrufen und den Zustand asynchron schreiben
        StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
        using (Stream fileStream = await file.OpenStreamForWriteAsync())
        {
          sessionData.Seek(0, SeekOrigin.Begin);
          await sessionData.CopyToAsync(fileStream);
        }
      }
      catch (Exception e)
      {
        throw new SuspensionManagerException(e);
      }
    }
        public async void SaveKittenToStorage()
        {
            // Get the current values of the object we want to save
            KittenObject ko = new KittenObject();
            ko.KittenName = _currentKittenName;
            ko.KittenAge = _currentKittenAge;
            ko.KittenImage = _currentKittenImg.OriginalString;

            // Add that object to our ObservableCollection
            if (KittenItems == null)
                KittenItems = new ObservableCollection<KittenObject>();
            KittenItems.Add(ko);

            // Create or the file we want to save
            StorageFile kittenFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("Kittens4Ever.kitten", CreationCollisionOption.ReplaceExisting);
            // Get the file stream
            var writeStream = await kittenFile.OpenStreamForWriteAsync();

            // Serialize our data to this file stream
            DataContractSerializer kittenSerial = new DataContractSerializer(typeof(ObservableCollection<KittenObject>));
            kittenSerial.WriteObject(writeStream, KittenItems);
            await writeStream.FlushAsync();
            writeStream.Close();

            // Reset the bound properties
            CurrentKittenAge = "0";
            CurrentKittenImg = new Uri("http://placekitten.com/205/205");
            CurrentKittenName = "";
        }
        /// <summary>
        /// Сохранение текущего <see cref="SessionState"/>.  Любые экземпляры <see cref="Frame"/>,
        /// зарегистрированные с помощью <see cref="RegisterFrame"/>, также сохранят свой текущий
        /// стек навигации, который, в свою очередь, предоставляет их активной <see cref="Page"/> возможность
        /// сохранения своего состояния.
        /// </summary>
        /// <returns>Асинхронная задача, отражающая сохранение состояния сеанса.</returns>
        public static async Task SaveAsync()
        {
            try
            {
                // Сохранение состояния навигации для всех зарегистрированных фреймов
                foreach (var weakFrameReference in _registeredFrames)
                {
                    Frame frame;
                    if (weakFrameReference.TryGetTarget(out frame))
                    {
                        SaveFrameNavigationState(frame);
                    }
                }

                // Синхронная сериализация состояния сеанса с целью запрета асинхронного доступа к общему
                // состоянию
                MemoryStream sessionData = new MemoryStream();
                DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
                serializer.WriteObject(sessionData, _sessionState);

                // Получение выходного потока для файла SessionState и асинхронная запись состояния
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
                using (Stream fileStream = await file.OpenStreamForWriteAsync())
                {
                    sessionData.Seek(0, SeekOrigin.Begin);
                    await sessionData.CopyToAsync(fileStream);
                }
            }
            catch (Exception e)
            {
                throw new SuspensionManagerException(e);
            }
        }
        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.");
            }
        }
        /// <summary>
        /// 現在の <see cref="SessionState"/> を保存します。
        /// <see cref="RegisterFrame"/> で登録された <see cref="Frame"/> インスタンスは、現在のナビゲーション スタックも保存します。
        /// これは、アクティブな <see cref="Page"/> に状態を保存する機会を
        /// 順番に提供します。
        /// </summary>
        /// <returns>セッション状態が保存されたときに反映される非同期タスクです。</returns>
        public static async Task SaveAsync()
        {
            try
            {
            // 登録されているすべてのフレームのナビゲーション状態を保存します
            foreach (var weakFrameReference in _registeredFrames)
            {
                Frame frame;
                if (weakFrameReference.TryGetTarget(out frame))
                {
                    SaveFrameNavigationState(frame);
                }
            }

            // セッション状態を同期的にシリアル化して、共有状態への非同期アクセスを
            // 状態
            MemoryStream sessionData = new MemoryStream();
            DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
            serializer.WriteObject(sessionData, _sessionState);
            
                // SessionState ファイルの出力ストリームを取得し、状態を非同期的に書き込みます
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
                using (Stream fileStream = await file.OpenStreamForWriteAsync())
                {
                    sessionData.Seek(0, SeekOrigin.Begin);
                    await sessionData.CopyToAsync(fileStream);
                    await fileStream.FlushAsync();
                }
            }
            catch (Exception e)
            {
                throw new SuspensionManagerException(e);
            }
        }
        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);
            }
        }
        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
        }
Exemple #12
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);
        }
 public void SaveConfig(string path, CheckConfiguration config)
 {
     var writer = new DataContractSerializer(typeof(CheckConfiguration));
     var file = File.Open(path, FileMode.Create);
     writer.WriteObject(file, config);
     file.Close();
 }
Exemple #14
0
 public static void Save()
 {
     DataContractSerializer dcs = new DataContractSerializer(typeof(TagDB));
     XmlWriter xmlw = XmlWriter.Create("TagDBase.xml");
     dcs.WriteObject(xmlw, new TaskTagDB());
     xmlw.Close();
 }
Exemple #15
0
 public static void Load()
 {
     DataContractSerializer dcs = new DataContractSerializer(typeof(TagDB));
     XmlReader xmlr = XmlReader.Create("TagDBase.xml");
     dcs.ReadObject(xmlr);
     xmlr.Close();
 }
        /// <summary>
        /// Guardar el <see cref="SessionState"/> actual.  Toda instancia de <see cref="Frame"/>
        /// registrada en <see cref="RegisterFrame"/> también conservará la
        /// pila de navegación actual que, a su vez, ofrece a la <see cref="Page"/> activa la oportunidad
        /// de guardar su estado.
        /// </summary>
        /// <returns>Tarea asincrónica que refleja cuándo se ha guardado el estado de la sesión.</returns>
        public static async Task SaveAsync()
        {
            try
            {
                // Guardar el estado de navegación para todos los marcos registrados
                foreach (var weakFrameReference in _registeredFrames)
                {
                    Frame frame;
                    if (weakFrameReference.TryGetTarget(out frame))
                    {
                        SaveFrameNavigationState(frame);
                    }
                }

                // Serializar el estado de la sesión de forma sincrónica para impedir el acceso asincrónico al estado
                // compartido
                MemoryStream sessionData = new MemoryStream();
                DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
                serializer.WriteObject(sessionData, _sessionState);

                // Obtener un flujo de salida para el archivo SessionState y escribir el estado de forma asincrónica
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
                using (Stream fileStream = await file.OpenStreamForWriteAsync())
                {
                    sessionData.Seek(0, SeekOrigin.Begin);
                    await sessionData.CopyToAsync(fileStream);
                }
            }
            catch (Exception e)
            {
                throw new SuspensionManagerException(e);
            }
        }
        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);
                }
            }
        }
        /// <summary>
        ///     Deserialize the given data to an output description
        /// </summary>
        public IOutputDescription Deserialize(string data)
        {
            IOutputDescription outputDescription = null;

            if (!string.IsNullOrWhiteSpace(data))
            {
                data = data.Replace("<![CDATA[", "");
                data = data.Replace("]]>", "");

                var dataContractSerializer = new DataContractSerializer(typeof (IOutputDescription), _knownTypes);

                using (var stringReader = new StringReader(StripKnownLegacyTags(data)))
                {
                    using (var xmlTextReader = new XmlTextReader(stringReader))
                    {
                        try
                        {
                            outputDescription = dataContractSerializer.ReadObject(xmlTextReader) as IOutputDescription;
                        }
                        catch (Exception ex)
                        {
                            Dev2Logger.Log.Error(ex);
                            // we want to return null                    
                        }
                    }
                }
            }

            return outputDescription;
        }
        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;
        }
        /// <summary>
        /// Enregistre le <see cref="SessionState"/> actuel. Toutes les instances de <see cref="Frame"/>
        /// inscrites avec <see cref="RegisterFrame"/> conservent également leur
        /// pile de navigation actuelle, ce qui permet à leur <see cref="Page"/> active
        /// d'enregistrer son état.
        /// </summary>
        /// <returns>Tâche asynchrone qui reflète quand l'état de session a été enregistré.</returns>
        public static async Task SaveAsync()
        {
            try
            {
                // Enregistre l'état de navigation pour tous les frames inscrits
                foreach (var weakFrameReference in _registeredFrames)
                {
                    Frame frame;
                    if (weakFrameReference.TryGetTarget(out frame))
                    {
                        SaveFrameNavigationState(frame);
                    }
                }

                // Sérialise l'état de session de manière synchrone pour éviter un accès asynchrone à un
                // état
                MemoryStream sessionData = new MemoryStream();
                DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
                serializer.WriteObject(sessionData, _sessionState);

                // Obtient un flux de sortie pour le fichier SessionState file et écrit l'état de manière asynchrone
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
                using (Stream fileStream = await file.OpenStreamForWriteAsync())
                {
                    sessionData.Seek(0, SeekOrigin.Begin);
                    await sessionData.CopyToAsync(fileStream);
                    await fileStream.FlushAsync();
                }
            }
            catch (Exception e)
            {
                throw new SuspensionManagerException(e);
            }
        }
        /// <summary>
        /// 保存当前 <see cref="SessionState"/>。  任何 <see cref="Frame"/> 实例
        /// (已向 <see cref="RegisterFrame"/> 注册)都还将保留其当前的
        /// 导航堆栈,从而使其活动 <see cref="Page"/> 可以
        /// 保存其状态。
        /// </summary>
        /// <returns>反映会话状态保存时间的异步任务。</returns>
        public static async Task SaveAsync()
        {
            try
            {
                // 保存所有已注册框架的导航状态
                foreach (var weakFrameReference in _registeredFrames)
                {
                    Frame frame;
                    if (weakFrameReference.TryGetTarget(out frame))
                    {
                        SaveFrameNavigationState(frame);
                    }
                }

                // 以同步方式序列化会话状态以避免对共享
                // 状态
                MemoryStream sessionData = new MemoryStream();
                DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
                serializer.WriteObject(sessionData, _sessionState);

                // 获取 SessionState 文件的输出流并以异步方式写入状态
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
                using (Stream fileStream = await file.OpenStreamForWriteAsync())
                {
                    sessionData.Seek(0, SeekOrigin.Begin);
                    await sessionData.CopyToAsync(fileStream);
                }
            }
            catch (Exception e)
            {
                throw new SuspensionManagerException(e);
            }
        }
Exemple #22
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;
    }
 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();
     }
 }
 //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();
     }
 }
Exemple #25
0
        static void Main(string[] args)
        {
            List<Employee> list = new List<Employee>(6);
            Employee Employee1 = new Employee(1, "John");
            Employee Employee2 = new Employee(2, "Jane");

            list.Add(Employee1);
            list.Add(Employee2);
            list.Add(Employee1);
            

            FileStream writer = new FileStream("sample.xml", FileMode.Create);
            DataContractSerializer ser =
                new DataContractSerializer(
                type: typeof(List<Employee>),
                rootName: "root",
                rootNamespace: "rootns",
                knownTypes: null,
                maxItemsInObjectGraph: int.MaxValue,
                ignoreExtensionDataObject: false,
                preserveObjectReferences: true, // false is default value
                dataContractSurrogate: null);

            ser.WriteObject(writer, list);
            writer.Close();
        }
Exemple #26
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");
			}
		}
        /// <summary>
        /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
        /// registered with <see cref="RegisterFrame"/> will also preserve their current
        /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
        /// to save its state.
        /// </summary>
        /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
        public static async Task SaveAsync()
        {
            // Save the navigation state for all registered frames
            foreach (var weakFrameReference in RegisteredFrames)
            {
                Frame frame;
                if (weakFrameReference.TryGetTarget(out frame))
                {
                    SaveFrameNavigationState(frame);
                }
            }

            var sessionData = new MemoryStream();
            var serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
            serializer.WriteObject(sessionData, sessionState);

            // Get an output stream for the SessionState file and write the state asynchronously
            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(SessionStateFilename, CreationCollisionOption.ReplaceExisting);
            using (var fileStream = await file.OpenStreamForWriteAsync())
            {
                sessionData.Seek(0, SeekOrigin.Begin);
                await sessionData.CopyToAsync(fileStream);
                await fileStream.FlushAsync();
            }
        }
        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;
                }
            }
        }
        public async Task SaveAsync()
        {
            try
            {
                SaveFrameNavigationState(_frame);

                // Serialize the session state synchronously to avoid asynchronous access to shared state
                MemoryStream sessionData = new MemoryStream();
                DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, Dictionary<string, object>>), _knownTypes);
                serializer.WriteObject(sessionData, _sessionState);

                // Get an output stream for the SessionState file and write the state asynchronously
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(Constants.SessionStateFileName, CreationCollisionOption.ReplaceExisting);
                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    sessionData.Seek(0, SeekOrigin.Begin);
                    var provider = new DataProtectionProvider("LOCAL=user");

                    // Encrypt the session data and write it to disk.
                    await provider.ProtectStreamAsync(sessionData.AsInputStream(), fileStream);
                    await fileStream.FlushAsync();
                }
            }
            catch (Exception e)
            {
                throw new SessionStateServiceException(e);
            }
        }
        //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;
        }
Exemple #31
0
    public static string WriteFromObject()
    {
        Level level = new Level();

        MemoryStream ms = new MemoryStream();

        System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(typeof(Level));
        ser.WriteObject(ms, level);
        byte[] json = ms.ToArray();
        ms.Close();
        return(Encoding.UTF8.GetString(json, 0, json.Length));
    }
    public static void Main(string [] args)
    {
        var source = new List <string>();

        source.Add("a");
        source.Add("b");
        using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) {
            var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(List <string>));
            serializer.WriteObject(stream, source);
            stream.Flush();
        }
    }
Exemple #33
0
 public static void SerializeToWriter <T>(T value, TextWriter writer)
 {
     try
     {
         using (var xw = new XmlTextWriter(writer))
         {
             var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
             serializer.WriteObject(xw, value);
         }
     }
     catch (Exception ex)
     {
         throw new SerializationException(string.Format("Error serializing object of type {0}", typeof(T).FullName), ex);
     }
 }
Exemple #34
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);
        }
Exemple #35
0
        public string Serialize(object serializableObject)
        {
            using (var memoryStream = new MemoryStream())
            {
                var serializer = new System.Runtime.Serialization.DataContractSerializer(serializableObject.GetType(), _settings);
                serializer.WriteObject(memoryStream, serializableObject);
                memoryStream.Seek(0, SeekOrigin.Begin);

                using (var streamReader = new StreamReader(memoryStream))
                {
                    var result = streamReader.ReadToEnd();
                    return(result);
                }
            }
        }
Exemple #36
0
        public string ConvertToHTML(DisplFormat format)
        {
            var dSer = new System.Runtime.Serialization.DataContractSerializer(this.GetType());

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            var    xTrf     = new System.Xml.Xsl.XslCompiledTransform();
            var    xTrfArg  = new System.Xml.Xsl.XsltArgumentList();
            var    xSet     = new System.Xml.Xsl.XsltSettings(true, true);
            var    mstr     = new System.Xml.XmlTextWriter(new System.IO.MemoryStream(), System.Text.Encoding.UTF8);
            var    doc      = new System.Xml.XmlDocument();
            string xsltName = "";

            switch (format)
            {
            case DisplFormat.single_item:
                xsltName = "~/xslt/ViewTransforms/RQI2SingleItemView.xslt";
                break;

            case DisplFormat.short_title:
                xsltName = "~/xslt/ViewTransforms/RQI2ShortTitleView.xslt";
                break;

            default:
                xsltName = "~/xslt/ViewTransforms/RQI2SingleItemView.xslt";
                break;
            }
            dSer.WriteObject(ms, this);
            //TESTDATEI(EZEUGEN)
            //XmlDocument Doc = new XmlDocument();
            //ms.Seek(0, System.IO.SeekOrigin.Begin);
            //Doc.Load(ms);
            //Doc.Save("C:/MVCTest.xml");
            //ENDE TESTDATEI
            System.IO.TextReader tr = new System.IO.StringReader(System.Text.Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position));
            xTrf.Load(HttpContext.Current.Server.MapPath(xsltName), xSet, new XmlUrlResolver());
            xTrfArg.AddParam("ApplPath", "", "http://" + HttpContext.Current.Request.ServerVariables.Get("HTTP_HOST") + (HttpContext.Current.Request.ApplicationPath.Equals("/") ? "" : HttpContext.Current.Request.ApplicationPath) + "/");
            xTrfArg.AddParam("MyDocsPath", "", "http://" + HttpContext.Current.Request.ServerVariables.Get("HTTP_HOST") + (HttpContext.Current.Request.ApplicationPath.Equals("/") ? "" : HttpContext.Current.Request.ApplicationPath) + "/");
            xTrfArg.AddExtensionObject("urn:TransformHelper", new TransformHelper.TransformUtils());
            xTrf.Transform(new System.Xml.XPath.XPathDocument(tr), xTrfArg, mstr);
            mstr.BaseStream.Flush();
            mstr.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
            doc.Load(mstr.BaseStream);
            //TESTDATEI EZEUGEN
            //doc.Save("C:/MVCTest.xml");
            //mstr.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
            //var rd = new System.Xml.XmlTextReader(mstr.BaseStream);
            return(doc.OuterXml);
        }
Exemple #37
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());
        }
        public static string Serialize <T>(T objectToSerialize, params Type[] otherTypes)
        {
            using (var memStm = new MemoryStream())
            {
                var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T), otherTypes ?? Type.EmptyTypes);
                serializer.WriteObject(memStm, objectToSerialize);

                memStm.Seek(0, SeekOrigin.Begin);

                using (var streamReader = new StreamReader(memStm))
                {
                    string result = streamReader.ReadToEnd();
                    return(result);
                }
            }
        }
 public string Parse <XmlDto>(XmlDto from, bool indentXml)
 {
     try
     {
         using (var ms = new MemoryStream())
         {
             var dcs = new System.Runtime.Serialization.DataContractSerializer(from.GetType());
             dcs.WriteObject(ms, from);
             return(Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position));
         }
     }
     catch (Exception ex)
     {
         throw new SerializationException(string.Format("Error serializing object of type {0}", from.GetType().FullName), ex);
     }
 }
Exemple #40
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);
        }
Exemple #41
0
    private string SerializeHashtable(Dictionary <object, object> obj)
    {
        //string serializedDictionary;

        //Serialize
        using (MemoryStream stream = new MemoryStream())
        {
            System.Runtime.Serialization.DataContractSerializer s1 = new System.Runtime.Serialization.DataContractSerializer(typeof(Dictionary <object, object>));
            s1.WriteObject(stream, obj);

            //serializedDictionary = Encoding.UTF8.GetString(stream.ToArray());
            return(Encoding.UTF8.GetString(stream.ToArray()));
            //take a look it's been serialized
            // Console.WriteLine(serializedDictionary);
        }
    }
Exemple #42
0
        public override string ToString()
        {
            var sb       = new StringBuilder();
            var settings = new XmlWriterSettings();

            settings.Indent             = true;
            settings.OmitXmlDeclaration = true;

            var ser = new System.Runtime.Serialization.DataContractSerializer(this.GetType());

            using (var xml = XmlWriter.Create(sb, settings))
            {
                ser.WriteObject(xml, this);
                xml.Flush();
                return(sb.ToString());
            }
        }
        private List <string> getSupportedLangs()
        {
            //check to see if token is null
            if (authToken == null)
            {
                authToken = getAuthToken();
            }

            //check to see if token expired and if so, get a new one
            if (DateTime.Now.CompareTo(tokenExpiresAt) >= 0)
            {
                authToken = getAuthToken();
            }

            string         uri            = "http://api.microsofttranslator.com/v2/Http.svc/GetLanguagesForTranslate";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Headers.Add("Authorization", authToken); //add token to request headers

            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> results = (List <string>)dcs.ReadObject(stream);
                    return(results);
                }
            }
            catch (WebException e)
            {
                string mesg = ProcessWebException(e, MtEnhancedTradosPlugin.PluginResources.MsApiFailedGetLanguagesMessage);
                throw new Exception(mesg); //throw error up to calling program
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }
Exemple #44
0
        public string Translate(string text, string from, string to)
        {
            string translatedText = "";
            var    uri            = new Uri("https://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Net.WebUtility.UrlEncode(text) + "&from=" + from + "&to=" + to);
            string requestBody    = GenerateTranslateOptionsRequestBody("general", "text/plain", "", "", "", "TestUserId");

            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"));
                translatedText = (string)dcs.ReadObject(stream);
            }

            return(translatedText);
        }
        public object Parse(string xml, Type type)
        {
            try
            {
                var bytes = Encoding.UTF8.GetBytes(xml);

                using (var reader = XmlDictionaryReader.CreateTextReader(bytes, this.quotas))
                {
                    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);
            }
        }
Exemple #46
0
        internal static string Serialize(Query запрос)
        {
            var sb       = new StringBuilder();
            var settings = new XmlWriterSettings();

            settings.Indent             = true;
            settings.OmitXmlDeclaration = true;

            var ser = new System.Runtime.Serialization.DataContractSerializer(запрос.GetType());

            using (var xml = XmlWriter.Create(sb, settings))
            {
                ser.WriteObject(xml, запрос);
                xml.Flush();
                return(sb.ToString());
            }
        }
Exemple #47
0
        public void TestMethod1()
        {
            AppSetting setting = new AppSetting();

            setting.Steps.Add(new InstallInformationStep());
            setting.Steps[0].StepCode = "sdf";
            //var knownTypes = new List<Type>() { typeof(AppSetting), typeof(IList<InstallInformationStep>) };
            //Assembly assembly = Assembly.GetAssembly(typeof(AppSetting));
            //var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(AppSetting), null, int.MaxValue, false, true, null, new MyDataContractResolver(assembly));
            var serializer    = new System.Runtime.Serialization.DataContractSerializer(typeof(AppSetting));
            var stringbuilder = new StringBuilder();
            var xml           = System.Xml.XmlWriter.Create(stringbuilder);

            serializer.WriteObject(xml, setting);
            xml.Flush();
            var str = stringbuilder.ToString();
        }
Exemple #48
0
        private static void GetLanguageNamesMethod(string authToken, string[] languageCodes)
        {
            string uri = "http://api.microsofttranslator.com/v2/Http.svc/GetLanguageNames?locale=en";
            // create the request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            request.Headers.Add("Authorization", authToken);
            request.ContentType = "text/xml";
            request.Method      = "POST";
            System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String[]"));
            using (System.IO.Stream stream = request.GetRequestStream())
            {
                dcs.WriteObject(stream, languageCodes);
            }
            WebResponse response = null;

            try
            {
                response = request.GetResponse();

                using (Stream stream = response.GetResponseStream())
                {
                    string[] languageNames = (string[])dcs.ReadObject(stream);

                    Console.WriteLine("Language codes = Language name");
                    for (int i = 0; i < languageNames.Length; i++)
                    {
                        Console.WriteLine("      {0}       = {1}", languageCodes[i], languageNames[i]);
                    }
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey(true);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }
Exemple #49
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="targetLang">ar,bg,ca,zh-CHS,zh-CHT,cs,da,nl,en,et,fi,fr,de,el,ht,he,hi,mww,hu,id,it,ja,tlh,tlh-QON,ko,lv,lt,ms,no,fa,pl,pt,ro,ru,sk,sl,es,sv,th,tr,uk,ur,vi</param>
        /// <param name="authToken"></param>
        /// <param name="textToTranslate"></param>
        /// <returns></returns>
        private static string TranslateInternal(string targetLang, string authToken, string textToTranslate)
        {
            //https://api.datamarket.azure.com/Bing/MicrosoftTranslator/v1/Translate?Text=%27%D7%9B%D7%A8%D7%92%D7%99%D7%9C%27&To=%27en%27
            //Console.WriteLine("Enter Text to detect language:");
            //string textToDetect = Console.ReadLine();
            //Keep appId parameter blank as we are sending access token in authorization header.
            //textToTranslate = "דרור אכל גלידה";
            //string uri = "https://api.datamarket.azure.com/Bing/MicrosoftTranslator/v1/Translate?text='" + textToTranslate + "'" + "&To='" + targetLang + "'";
            string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?" + "to=" + targetLang + "&text=" + HttpUtility.UrlEncode(textToTranslate);
            //string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?to=" + HttpUtility.UrlEncode(targetLang);

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

            httpWebRequest.Headers.Add("Authorization", authToken);

            //httpWebRequest.Headers.Add("text", HttpUtility.UrlEncode(textToTranslate.Substring(0,1000)));
            //httpWebRequest.Headers.Add("text", HttpUtility.UrlEncode(textToTranslate.Substring(0, 9000)));

            WebResponse response = null;
            string      translatedText;

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

            catch
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
            return(translatedText);
        }
        public static string SerializeWCF <T>(this T obj)
        {
            if (obj == null)
            {
                return(string.Empty);
            }
            var formatter = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());

            using (var sm = new StringWriter())
            {
                using (var sx = new System.Xml.XmlTextWriter(sm))
                {
                    formatter.WriteObject(sx, obj);
                    sx.Flush();
                }
                return(sm.ToString());
            }
        }
        public string SerializeToString <XmlDto>(XmlDto from)
        {
            var sb = new StringBuilder();

            try
            {
                using (var writer = new XmlTextWriter(new StringWriter(sb)))
                {
                    var dcs = new System.Runtime.Serialization.DataContractSerializer(from.GetType());
                    dcs.WriteObject(writer, from);
                    return(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                throw new SerializationException(string.Format("Error serializing object of type {0}", from.GetType().FullName), ex);
            }
        }
        public static async void Save(string FileName, MasterDictionary data)
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            //await storageFolder.RenameAsync("LearnerToolsFolder");
            //System.Diagnostics.Debug.WriteLine(storageFolder.Path);

            using (var Stream = await storageFolder.OpenStreamForWriteAsync(FileName, Windows.Storage.CreationCollisionOption.ReplaceExisting))
            {
                System.Runtime.Serialization.DataContractSerializer Serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(List <MasterDictionary>));

                Serializer.WriteObject(Stream, data);
            }



            //Windows.Storage.StorageFile File = await storageFolder.CreateFileAsync(FileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);
        }
Exemple #53
0
        static ReceiptResponse signXml(ReceiptRequest request, string url, Guid cashboxid = default(Guid), string accesstoken = "00000000")
        {
            if (!url.EndsWith("/"))
            {
                url += "/";
            }

            var ms         = new System.IO.MemoryStream();
            var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(fiskaltrust.ifPOS.v0.ReceiptRequest));

            serializer.WriteObject(ms, request);

            var webreq = (HttpWebRequest)HttpWebRequest.Create(url + "xml/sign");

            webreq.Method      = "POST";
            webreq.ContentType = "application/xml;charset=utf-8";

            webreq.Headers.Add("cashboxid", cashboxid.ToString());
            webreq.Headers.Add("accesstoken", accesstoken);

            webreq.ContentLength = ms.Length;
            using (var reqStream = webreq.GetRequestStream())
            {
                reqStream.Write(ms.ToArray(), 0, (int)ms.Length);
            }

            var webresp = (HttpWebResponse)webreq.GetResponse();

            if (webresp.StatusCode == HttpStatusCode.OK)
            {
                serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(fiskaltrust.ifPOS.v0.ReceiptResponse));
                ms         = new System.IO.MemoryStream();
                webresp.GetResponseStream().CopyTo(ms);

                ms.Position = 0;
                fiskaltrust.ifPOS.v0.ReceiptResponse resp = (fiskaltrust.ifPOS.v0.ReceiptResponse)serializer.ReadObject(ms);
                return(resp);
            }
            else
            {
                return(null);
            }
        }
        public void TestMethod1()
        {
            ibasModules modules = new ibasModules();
            var         module  = new ibasModule();

            module.ModuleId = "nihao";
            module.Type     = emModuleType.basic;
            modules.Add(module);
            //var knownTypes = new List<Type>() { typeof(AppSetting), typeof(IList<InstallInformationStep>) };
            //Assembly assembly = Assembly.GetAssembly(typeof(AppSetting));
            //var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(AppSetting), null, int.MaxValue, false, true, null, new MyDataContractResolver(assembly));
            var serializer    = new System.Runtime.Serialization.DataContractSerializer(typeof(ibasModules));
            var stringbuilder = new StringBuilder();
            var xml           = System.Xml.XmlWriter.Create(stringbuilder);

            serializer.WriteObject(xml, modules);
            xml.Flush();
            var str = stringbuilder.ToString();
        }
Exemple #55
0
    private string SerializationLevelsToJON()
    {
        List <Level> levels = new List <Level>();

        for (int index = 0; index <= 100; index++)
        {
            Level level = new Level();
            level = GeneratorLevel(index);
            levels.Add(level);
        }

        MemoryStream ms = new MemoryStream();

        System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(typeof(List <Level>));
        ser.WriteObject(ms, levels);
        byte[] json = ms.ToArray();
        ms.Close();
        return(Encoding.UTF8.GetString(json, 0, json.Length));
    }
Exemple #56
0
        static void signXml(string url, Guid cashboxid = default(Guid), string accesstoken = "00000000")
        {
            var reqdata = UseCase17Request(1, 5, 5, cashboxid.ToString());

            var ms         = new System.IO.MemoryStream();
            var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(fiskaltrust.ifPOS.v0.ReceiptRequest));

            serializer.WriteObject(ms, reqdata);
            Console.WriteLine("{0:G} Sign request {1}", DateTime.Now, Encoding.UTF8.GetString(ms.ToArray()));

            var webreq = (HttpWebRequest)HttpWebRequest.Create(url + "/xml/sign");

            webreq.Method      = "POST";
            webreq.ContentType = "application/xml;charset=utf-8";

            webreq.Headers.Add("cashboxid", cashboxid.ToString());
            webreq.Headers.Add("accesstoken", accesstoken);

            webreq.ContentLength = ms.Length;
            using (var reqStream = webreq.GetRequestStream())
            {
                reqStream.Write(ms.ToArray(), 0, (int)ms.Length);
            }

            var webresp = (HttpWebResponse)webreq.GetResponse();

            if (webresp.StatusCode == HttpStatusCode.OK)
            {
                serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(fiskaltrust.ifPOS.v0.ReceiptResponse));
                ms         = new System.IO.MemoryStream();
                webresp.GetResponseStream().CopyTo(ms);

                Console.WriteLine("{0:G} Sign response {1}", DateTime.Now, Encoding.UTF8.GetString(ms.ToArray()));

                ms.Position = 0;
                fiskaltrust.ifPOS.v0.ReceiptResponse resp = (fiskaltrust.ifPOS.v0.ReceiptResponse)serializer.ReadObject(ms);
            }
            else
            {
                Console.WriteLine("{0:G} {1} {2}", DateTime.Now, webresp.StatusCode, webresp.StatusDescription);
            }
        }
Exemple #57
0
        public void DataContractSerializer_CanSerialize()
        {
            //arrange
            var ms         = new System.IO.MemoryStream();
            var dataUri    = new DataUri("text/plain", new byte[] { 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49 });
            var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(DataUri));

            var expectedVal = "data:text/plain;base64,QEFCQ0RFRkdISQ==";

            //act
            serializer.WriteObject(ms, dataUri);

            var       streamString = System.Text.Encoding.UTF8.GetString(ms.ToArray());
            XDocument xdoc         = XDocument.Parse("<root>" + streamString + "</root>");
            XElement  datauriEl    = xdoc.Element("root").Element(XName.Get("DataUri", "http://schemas.datacontract.org/2004/07/System"));

            //assert

            Assert.That(datauriEl.Value, Is.EqualTo(expectedVal));
        }
Exemple #58
0
        private static string GetTranslation(string text, string fromLanguage, string toLanguage, AdmAccessToken token)
        {
            // TRANSLATE
            string headerValue = "Bearer " + token.access_token;
            string textEncoded = WebUtility.UrlEncode(text);
            string uri         = string.Format("http://api.microsofttranslator.com/v2/Http.svc/Translate?text={0}&from={1}&to={2}", text, fromLanguage, toLanguage);

            WebRequest translateRequest = WebRequest.Create(uri);

            translateRequest.Headers.Add("Authorization", headerValue);

            WebResponse response = translateRequest.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);
                return(translation);
            }
        }
Exemple #59
0
        public static object ReadObjectByType(string filepath, Type type)
        {
            object retVal = null;

            try
            {
                FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
                if (fs != null)
                {
                    System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(type);
                    retVal = ser.ReadObject(fs);
                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception while reading config file: " + ex.Message);
            }
            return(retVal);
        }
Exemple #60
0
 private void LoadDefaultModules()
 {
     try
     {
         var path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "ibasStandardModules.xml");
         if (File.Exists(path))
         {
             var xml        = System.Xml.XmlReader.Create(path);
             var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(ibasModules));
             var model      = serializer.ReadObject(xml) as ibasModules;
             if (model != null)
             {
                 this.InstallModules = model;
             }
         }
     }
     catch (Exception error)
     {
     }
 }