Ejemplo n.º 1
0
        private string TranslateMethod(string authToken, string text)
        {
            string translation = string.Empty;
            string from = "en";
            string to = "ja";

            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"));
                    translation = (string)dcs.ReadObject(stream);
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }

            return translation;
        }
Ejemplo n.º 2
0
        public static string TranslateMethod(string authToken, string originalS, string from, string to)
        {
            string text = originalS; //"你能听见我";
            //string from = "en";
            //string to = "zh-CHS";
            //string from = Constants.from;// "zh-CHS";
            //string to = Constants.to; // "en";

            string transuri = ConstantParam.ApiUri + System.Net.WebUtility.UrlEncode(text) + "&from=" + from + "&to=" + to;

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(transuri);
            //  httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Headers["Authorization"] = authToken;
            //httpWebRequest.Method = "GET";
            string trans;

            Task<WebResponse> response = httpWebRequest.GetResponseAsync();

            using (Stream stream = response.Result.GetResponseStream())
            {
                System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                //DataContractJsonSerializer dcs = new DataContractJsonSerializer(Type.GetType("System.String"));
                trans = (string)dcs.ReadObject(stream);
                return trans;

            }
        }
        public override string Translate(string text)
        {
            string result = "nothing yet...";

            Stream stream = null;

            try
            {
                using (stream = GetResponse(text).GetResponseStream())
                {
                    var dataContractSerializer
                        = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                    result = (string) dataContractSerializer.ReadObject(stream);
                }
            }
            catch (WebException e)
            {
                result = e.Message;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }

            return result;
        }
        public object Deserialize(string serializedObject, Type type)
        {
            using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(serializedObject)))
            {
                var serializer = new System.Runtime.Serialization.DataContractSerializer(type, null, Int32.MaxValue, false, false, null, _dataContractResolver);

                return serializer.ReadObject(memoryStream);
            }
        }
 internal static string GetXml(object o) {
   var formatter = new System.Runtime.Serialization.DataContractSerializer(o.GetType());
   using (var stringWriter = new StringWriter())
   using (var xmlWriter = new XmlTextWriter(stringWriter)) {
     xmlWriter.Formatting = Formatting.Indented;
     xmlWriter.QuoteChar = '\'';
     formatter.WriteObject(xmlWriter, o);
     return stringWriter.ToString();
   }
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Creates a new object that is a copy of the current instance.
 /// </summary>
 /// <returns>
 /// A new object that is a copy of this instance.
 /// </returns>
 object ICloneable.Clone()
 {
     var serializer = new System.Runtime.Serialization.DataContractSerializer(GetType());
     using (var ms = new System.IO.MemoryStream())
     {
         serializer.WriteObject(ms, this);
         ms.Position = 0;
         return serializer.ReadObject(ms);
     }
 }
        object ICloneable.Clone()
        {
            var serializer = new System.Runtime.Serialization.DataContractSerializer(GetType());

            using (var ms = new System.IO.MemoryStream())
            {
                serializer.WriteObject(ms, this);
                ms.Position = 0;
                return(serializer.ReadObject(ms));
            }
        }
Ejemplo n.º 8
0
        public TokenViewer()
        {
            // Создаём форму
            InitializeComponent();

            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog
            {
                FileName   = "TokenCollectorlog",
                DefaultExt = ".xml",
                Filter     = "(XML documents .xml)|*.xml",
            };

            if (dlg.ShowDialog() == true)
            {
                using (System.IO.FileStream stream = new System.IO.FileStream(dlg.FileName, System.IO.FileMode.Open))
                {
                    Type[] types = new Type[] {
                        typeof(AndBlock),
                        typeof(DuplicateOutputsBlock),
                        typeof(CadResource),
                        typeof(WorkerResource),
                        typeof(TechincalSupportResource),
                        typeof(MethodolgicalSupportResource),
                        typeof(TokensCollector),
                        typeof(ConnectionManager),
                        typeof(ArrangementProcedure),
                        typeof(Assembling),
                        typeof(ClientCoordinationPrrocedure),
                        typeof(DocumentationCoordinationProcedure),
                        typeof(ElectricalSchemeSimulation),
                        typeof(FixedTimeBlock),
                        typeof(FormingDocumentationProcedure),
                        typeof(Geometry2D),
                        typeof(KDT),
                        typeof(KinematicСalculations),
                        typeof(PaperworkProcedure),
                        typeof(QualityCheckProcedure),
                        typeof(SampleTestingProcedure),
                        typeof(SchemaCreationProcedure),
                        typeof(StrengthСalculations),
                        typeof(TracingProcedure),
                        typeof(Process)
                    };

                    System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(typeof(TokensCollector), types);
                    _collector = (TokensCollector)ser.ReadObject(stream);
                    StartView();
                }
            }
            else
            {
                throw new ArgumentNullException("Файл не выбран");
            }
        }
Ejemplo n.º 9
0
        public void TestSer()
        {
            var f = new SomeTestingViewModel() {  Result="hahahaha"};

            var dx = new System.Runtime.Serialization.DataContractSerializer(typeof(SomeTestingViewModel));
            var s = new MemoryStream();
            dx.WriteObject(s, f);
            s.Position = 0;
            var s2 = dx.ReadObject(s) as SomeTestingViewModel;
            Assert.AreEqual(s2.Result, f.Result);
        }
Ejemplo n.º 10
0
        public static T Clone <T>(this T source)
        {
            var dcs = new System.Runtime.Serialization.DataContractSerializer(typeof(T));

            using (var ms = new System.IO.MemoryStream())
            {
                dcs.WriteObject(ms, source);
                ms.Seek(0, System.IO.SeekOrigin.Begin);
                return((T)dcs.ReadObject(ms));
            }
        }
Ejemplo n.º 11
0
        public static T DeepReadFromFile <T>(string filename)
        {
#if !__WP8__
            var deepDeserializer = new XmlDeepDeserializer();
            return((T)deepDeserializer.Deserialize(filename));
#else
            var ser = new System.Runtime.Serialization.DataContractSerializer(typeof(T));

            using (var fs = new FileStream(filename, FileMode.Open))
                return((T)ser.ReadObject(fs));
#endif
        }
Ejemplo n.º 12
0
        public static void DeepWriteToFile <T>(string filename, T obj)
        {
#if !__WP8__
            var deepSerializer = new XmlDeepSerializer();
            deepSerializer.Serialize(obj, filename);
#else
            var serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
            using (var sw = new FileStream(filename, FileMode.OpenOrCreate))
                using (var xw = System.Xml.XmlWriter.Create(sw))
                    serializer.WriteObject(xw, obj);
#endif
        }
Ejemplo n.º 13
0
        private Message Deserialize(TransportMessage message)
        {
            var messageTypeName = message.Headers[MessageHeaders.EventType];
            var messageType     = MessageTypeConverters.GetNameType(messageTypeName);

            var dataContractSerializer = new System.Runtime.Serialization.DataContractSerializer(messageType);

            using (var memoryStream = new MemoryStream(message.Body))
            {
                return(new Message(dataContractSerializer.ReadObject(memoryStream), new Dictionary <string, string>(message.Headers)));
            }
        }
        internal static string GetXml(object o)
        {
            var formatter = new System.Runtime.Serialization.DataContractSerializer(o.GetType());

            using (var stringWriter = new StringWriter())
                using (var xmlWriter = new XmlTextWriter(stringWriter)) {
                    xmlWriter.Formatting = Formatting.Indented;
                    xmlWriter.QuoteChar  = '\'';
                    formatter.WriteObject(xmlWriter, o);
                    return(stringWriter.ToString());
                }
        }
Ejemplo n.º 15
0
        public void ParsingErrors_Serialization()
        {
            using var stream = new MemoryStream();
            var ser = new System.Runtime.Serialization.DataContractSerializer(typeof(ParsingErrors));

            ser.WriteObject(stream, new ParsingErrors());
            stream.Position = 0;

            var exception = ser.ReadObject(stream) as ParsingErrors;

            Assert.That(exception, Is.TypeOf <ParsingErrors>());
        }
Ejemplo n.º 16
0
        public static T GetDeserialized <T>(byte[] serialized)
            where T : rsEntityBase
        {
            var dcs = new System.Runtime.Serialization.DataContractSerializer(typeof(T));

            using (var ms = new System.IO.MemoryStream())
            {
                ms.Write(serialized, 0, serialized.Length);
                ms.Seek(0, System.IO.SeekOrigin.Begin);
                return((T)dcs.ReadObject(ms));
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Saves HID keymap to local state as XML file
        /// </summary>
        public async Task SaveHid()
        {
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(HID_KEYMAP_FILENAME, CreationCollisionOption.ReplaceExisting);

            var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(HIDDataMap <RemoteControl>));

            using (var stream = await file.OpenStreamForWriteAsync())
            {
                serializer.WriteObject(stream, ControlMap);
                await stream.FlushAsync();
            }
        }
Ejemplo n.º 18
0
        public static byte[] GetSerialized <T>(T source)
            where T : rsEntityBase
        {
            var dcs = new System.Runtime.Serialization.DataContractSerializer(typeof(T));

            using (var ms = new System.IO.MemoryStream())
            {
                dcs.WriteObject(ms, source);
                ms.Seek(0, System.IO.SeekOrigin.Begin);
                return(ms.ToArray());
            }
        }
 public byte[] ToBinary()
 {
     byte[] buffer;
     using (var ms = new System.IO.MemoryStream())
         using (var writer = System.Xml.XmlDictionaryWriter.CreateBinaryWriter(ms))
         {
             var serializer = new System.Runtime.Serialization.DataContractSerializer(GetType());
             serializer.WriteObject(writer, this);
             writer.Flush();
             buffer = ms.ToArray();
         }
     return(buffer);
 }
Ejemplo n.º 20
0
    static void Main(string[] args)
    {
        var obj = "bugaga!";

        System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
        MemoryStream ms = new MemoryStream();

        using (XmlWriter xdw = XmlWriter.Create(ms))
        {
            ser.WriteObject(xdw, obj);
        }
        Console.WriteLine(ms.Length);
    }
Ejemplo n.º 21
0
        public static XElement Serialize <T>(this T obj)
        {
            var serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());

            using (var ms = new MemoryStream())
                using (var xwr = new XmlTextWriter(ms, Encoding.UTF8))
                {
                    serializer.WriteObject(xwr, obj);
                    xwr.Flush();
                    ms.Position = 0;
                    return(XElement.Load(ms));
                }
        }
Ejemplo n.º 22
0
        public string ToXml()
        {
            WebCatchException.MyException rtt = (WebCatchException.MyException)(this);

            System.Runtime.Serialization.DataContractSerializer ser =
                new System.Runtime.Serialization.DataContractSerializer(typeof(WebCatchException.MyException));

            using (var mso = new System.IO.MemoryStream())
            {
                ser.WriteObject(mso, rtt);
                return(System.Text.Encoding.UTF8.GetString(mso.ToArray()));
            }
        }
 internal async Task<IEnumerable> InternalLoadSnapshotAsync()
 {
     var f = await workingFile;
     var sl = new System.Runtime.Serialization.DataContractSerializer(typeof(PicLibFolder[]));
     var ms = new MemoryStream();
     using (var inps = (await f.OpenReadAsync()).GetInputStreamAt(0).AsStreamForRead())
     {
         await inps.CopyToAsync(ms);
         ms.Position = 0;
     }
     var r = sl.ReadObject(ms) as PicLibFolder[];
     return r;
 }
 /// <summary>
 /// Serializes the object to a string.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="entity">The entity.</param>
 /// <returns></returns>
 public string SerializeObject <T>(T entity)
 {
     using (var memoryStream = new MemoryStream())
     {
         using (var reader = new StreamReader(memoryStream))
         {
             var serializer = new System.Runtime.Serialization.DataContractSerializer(entity.GetType());
             serializer.WriteObject(memoryStream, entity);
             memoryStream.Position = 0;
             return(reader.ReadToEnd());
         }
     }
 }
Ejemplo n.º 25
0
 public static byte[] Serialize <T>(T data)
 {
     using (var memory = new System.IO.MemoryStream())
     {
         var ser = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
         using (var binaryDictionaryWriter = System.Xml.XmlDictionaryWriter.CreateBinaryWriter(memory))
         {
             ser.WriteObject(binaryDictionaryWriter, data);
             binaryDictionaryWriter.Flush();
         }
         return(memory.ToArray());
     }
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Returns a byte array that represents the current <see cref="T:System.Object"/>. 
 /// </summary>
 /// <returns>A byte array that represents the current <see cref="T:System.Object"/>.</returns>
 public virtual byte[] ToBinary()
 {
     byte[] buffer;
     using (var ms = new System.IO.MemoryStream())
     using (var writer = System.Xml.XmlDictionaryWriter.CreateBinaryWriter(ms))
     {
         var serializer = new System.Runtime.Serialization.DataContractSerializer(GetType());
         serializer.WriteObject(writer, this);
         writer.Flush();
         buffer = ms.ToArray();
     }
     return buffer;
 }
Ejemplo n.º 27
0
        private static System.Collections.ObjectModel.ObservableCollection <ImageSymbolEntry> GetImageSymbolEntries()
        {
            Assembly a = typeof(SymbolConfigProvider).Assembly;

            using (Stream str = a.GetManifestResourceStream("ESRI.ArcGIS.Mapping.Core.Embedded.ImageSymbolLookup.xml"))
            {
                var xmlSerializer = new System.Runtime.Serialization.DataContractSerializer(typeof(System.Collections.ObjectModel.ObservableCollection <ImageSymbolEntry>));
                str.Position = 0;
                var imageSymbolLookup = (System.Collections.ObjectModel.ObservableCollection <ImageSymbolEntry>)xmlSerializer.ReadObject(str);
                str.Close();
                return(imageSymbolLookup);
            }
        }
Ejemplo n.º 28
0
        public void UsesCryptoToSave()
        {
            WorkItem             host      = container;
            ICryptographyService cryptoSvc = new DataProtectionCryptographyService();

            host.Services.Add(typeof(ICryptographyService), cryptoSvc);
            FileStatePersistenceService perSvc = new FileStatePersistenceService();

            host.Services.Add(typeof(IStatePersistenceService), perSvc);
            NameValueCollection settings = new NameValueCollection();

            settings["UseCryptography"] = "True";
            perSvc.Configure(settings);

            string id        = Guid.NewGuid().ToString();
            State  testState = new State(id);

            testState["someValue"] = "value";
            perSvc.Save(testState);


            byte[] stateData = null;
            string filename  = string.Format(CultureInfo.InvariantCulture, "{0}.state", id);

            using (FileStream stream = File.OpenRead(filename))
            {
                byte[] cipherData = new byte[stream.Length];
                stream.Read(cipherData, 0, (int)stream.Length);
                stateData = ProtectedData.Unprotect(cipherData, null, DataProtectionScope.CurrentUser);
            }

            //BinaryFormatter fmt = new BinaryFormatter();
            //State recovered = (State)fmt.Deserialize(ms);
#pragma warning disable CS0618 // Type or member is obsolete
            System.Runtime.Serialization.DataContractSerializer fmt = new System.Runtime.Serialization.DataContractSerializer(typeof(State),
                                                                                                                              new System.Collections.Generic.List <Type>()
            {
                typeof(System.Collections.CaseInsensitiveHashCodeProvider), typeof(System.Collections.CaseInsensitiveComparer), typeof(System.String[]), typeof(System.Object[])
            });
#pragma warning restore CS0618 // Type or member is obsolete
            MemoryStream ms        = new MemoryStream(stateData.Prune());
            State        recovered = (State)fmt.ReadObject(ms);

            Assert.AreEqual(id, recovered.ID, "The state id is different.");
            Assert.AreEqual("value", recovered["someValue"]);

            if (File.Exists(filename))
            {
                File.Delete(filename);
            }
        }
Ejemplo n.º 29
0
        public CodeCompileUnit DeSerializationCodeCompileUnit( )
        {
            FileStream fs = new FileStream(@"D:\ccc.xml", FileMode.Open);

            var serializer             = new System.Runtime.Serialization.DataContractSerializer(typeof(CodeCompileUnit));
            XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());

            CodeCompileUnit ccu = (CodeCompileUnit)serializer.ReadObject(reader, true, new AllowAllContractResolver());

            reader.Close();
            fs.Close();

            return(ccu);
        }
Ejemplo n.º 30
0
        private void OnSaveAs(object sender, ExecuteEventArgs e)
        {
            using (SaveFileDialog dialog = new SaveFileDialog())
            {
                dialog.Filter           = "Shader file (*.sh)|*.sh|All files (*.*)|*.*";
                dialog.FilterIndex      = 0;
                dialog.RestoreDirectory = true;

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    using (var stream = dialog.OpenFile())
                    {
                        using (var xmlStream = new System.IO.MemoryStream())
                        {
                            var nodeGraph  = ModelConversion.ToShaderPatcherLayer(graphControl);
                            var serializer = new System.Runtime.Serialization.DataContractSerializer(
                                typeof(ShaderPatcherLayer.NodeGraph));
                            var settings = new System.Xml.XmlWriterSettings()
                            {
                                Indent      = true,
                                IndentChars = "\t",
                                Encoding    = System.Text.Encoding.ASCII
                            };

                            // write the xml to a memory stream to begin with
                            using (var writer = System.Xml.XmlWriter.Create(xmlStream, settings))
                            {
                                serializer.WriteObject(writer, nodeGraph);
                            }

                            // we hide the memory stream within a comment, and write
                            // out a hlsl shader file
                            // The HLSL compiler doesn't like UTF files... It just wants plain ASCII encoding

                            using (var sw = new System.IO.StreamWriter(stream, System.Text.Encoding.ASCII))
                            {
                                var shader = ShaderPatcherLayer.NodeGraph.GenerateShader(nodeGraph, System.IO.Path.GetFileNameWithoutExtension(dialog.FileName));
                                sw.Write(shader);

                                sw.Write("/* **** **** NodeEditor **** **** \r\nNEStart{");
                                sw.Flush();
                                xmlStream.WriteTo(stream);
                                sw.Write("}NEEnd\r\n **** **** */\r\n");
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 31
0
 public static void LoadDictionary <T>(string targetFile, out T subject)
 {
     if (File.Exists(targetFile))
     {
         using (var fstream = new FileStream(targetFile, FileMode.Open, FileAccess.Read, FileShare.None))
         {
             var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
             subject = (T)serializer.ReadObject(fstream);
         }
     }
     else
     {
         subject = default(T);
     }
 }
Ejemplo n.º 32
0
        public static void Update(Config config)
        {
            var serializer  = new System.Runtime.Serialization.DataContractSerializer(typeof(Config));
            var xmlSettings = new XmlWriterSettings()
            {
                Encoding = new UTF8Encoding(false),
                Indent   = true
            };

            using (var xw = XmlWriter.Create(ConfigFilePath, xmlSettings))
            {
                serializer.WriteObject(xw, config);
                xw.Flush();
            }
        }
Ejemplo n.º 33
0
        public void TestSer()
        {
            var f = new SomeTestingViewModel()
            {
                Result = "hahahaha"
            };

            var dx = new System.Runtime.Serialization.DataContractSerializer(typeof(SomeTestingViewModel));
            var s  = new MemoryStream();

            dx.WriteObject(s, f);
            s.Position = 0;
            var s2 = dx.ReadObject(s) as SomeTestingViewModel;

            Assert.AreEqual(s2.Result, f.Result);
        }
Ejemplo n.º 34
0
        public static object DataContractDeserialize(string buffer, bool compress)
        {
            if (!string.IsNullOrEmpty(buffer))
            {
                int idx = buffer.IndexOf('@');
                string assemblyQualifiedName = buffer.Substring(0, idx);
                string objBuffer = buffer.Substring(idx + 1);
                Type objType = Type.GetType(assemblyQualifiedName, true);

                System.Runtime.Serialization.DataContractSerializer aa = new System.Runtime.Serialization.DataContractSerializer(objType);
                XmlReader reader = XmlReader.Create(new StringReader(objBuffer));
                return aa.ReadObject(reader);
            }
            else
                return null;
        }
        public static void AssertDefaultDataContractSerializationSuccessForValueType <T>(this T value) where T : struct
        {
            var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T));

            using (MemoryStream stream = new MemoryStream())
            {
                serializer.WriteObject(stream, value);

                stream.Seek(0, SeekOrigin.Begin);

                var deserializedValue = (T)serializer.ReadObject(stream);

                deserializedValue.Should().NotBeSameAs(value);
                value.Equals(deserializedValue).Should().BeTrue();
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        ///     将C#数据实体转化为xml数据
        /// </summary>
        /// <param name="obj">要转化的数据实体</param>
        /// <returns>xml格式字符串</returns>
        public static string XmlSerialize <T>(T obj)
        {
            var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
            var stream     = new MemoryStream();

            serializer.WriteObject(stream, obj);
            stream.Position = 0;

            var sr        = new StreamReader(stream);
            var resultStr = sr.ReadToEnd();

            sr.Close();
            stream.Close();

            return(resultStr);
        }
Ejemplo n.º 37
0
        public string DetectLanguage(string text)
        {
            string         authToken      = getAuthToken();
            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"));
                    string languageDetected = (string)dcs.ReadObject(stream);
                    Console.WriteLine(string.Format("Language detected:{0}", languageDetected));
                    return(languageDetected);
                }
        }
Ejemplo n.º 38
0
        internal static IModelList <TModel> Deserialize <TModel>(string xml, Type modelListType)
            where TModel : ModelBase
        {
            if (string.IsNullOrEmpty(xml))
            {
                return(null);
            }

            var serializer = new System.Runtime.Serialization.DataContractSerializer(modelListType);

            using (TextReader tr = new StringReader(xml))
                using (XmlReader xr = new XmlTextReader(tr))
                {
                    return((IModelList <TModel>)serializer.ReadObject(xr));
                }
        }
        internal async Task InternalSaveSnapshotAsync(IPicLibFolder[] folders)
        {
            var sl = new System.Runtime.Serialization.DataContractSerializer(typeof(PicLibFolder[]));

            var ms = new MemoryStream();

            sl.WriteObject(ms, folders.OfType <PicLibFolder>().ToArray());
            ms.Position = 0;
            GetCacheFile(CreationCollisionOption.ReplaceExisting);
            var f = await workingFile;

            using (var ws = await f.OpenStreamForWriteAsync())
            {
                await ms.CopyToAsync(ws);
            }
        }
        internal async Task <IEnumerable> InternalLoadSnapshotAsync()
        {
            var f  = await workingFile;
            var sl = new System.Runtime.Serialization.DataContractSerializer(typeof(PicLibFolder[]));
            var ms = new MemoryStream();

            using (var inps = (await f.OpenReadAsync()).GetInputStreamAt(0).AsStreamForRead())
            {
                await inps.CopyToAsync(ms);

                ms.Position = 0;
            }
            var r = sl.ReadObject(ms) as PicLibFolder[];

            return(r);
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Used to perform the actual translation
        /// </summary>
        /// <param name="InputString"></param>
        /// <returns></returns>
        public override string TranslateString(string InputString)
        {
            Console.WriteLine("Processing: " + InputString);
            string result = "";

            using (WebClient client = new WebClient())
            {
                using (Stream data = client.OpenRead(this.BuildRequestString(InputString)))
                {
                    System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                    result = (string)dcs.ReadObject(data);

                    data.Close();
                }
            }

            return result;
        }
        public static string[] GetLanguageNames(string[] languageCodes)
        {
            string uri = "http://api.microsofttranslator.com/v2/Http.svc/GetLanguageNames?locale=" + languageCodes[0] + "&appId=" + appId;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            httpWebRequest.ContentType = "text/xml";
            httpWebRequest.Method = "POST";
            System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String[]"));
            using (System.IO.Stream stream = httpWebRequest.GetRequestStream())
            {
                dcs.WriteObject(stream, languageCodes);
            }

            WebResponse response = null;
            try
            {
                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    return (string[])dcs.ReadObject(stream);
                }
            }
            catch (WebException)
            {
                if (languageCodes.Length == 1 && languageCodes[0] == "en")
                    return new string[] { "English" };
                else
                    throw;
            }
            catch
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }
Ejemplo n.º 43
0
        public static string DataContractSerialize(Object obj, bool compress)
        {
            if (obj != null)
            {
                Type objType = obj.GetType();
                System.Runtime.Serialization.DataContractSerializer aa = new System.Runtime.Serialization.DataContractSerializer(objType);
                StringBuilder sb = new StringBuilder();

                // Inserisce l'assembly qualified name nello stream del buffer come primo elemento separato dalla @
                sb.Append(objType.AssemblyQualifiedName);
                sb.Append('@');

                XmlWriter writer = XmlWriter.Create(sb);
                aa.WriteObject(writer, obj);
                writer.Close();

                return sb.ToString();
            }
            else
                return null;
        }
Ejemplo n.º 44
0
        public static string TranslateMethod(string authToken, string originalS, string from, string to)
        {
            string text = originalS; 
            string transuri = ConstantParam.ApiUri + System.Net.WebUtility.UrlEncode(text) + "&from=" + from + "&to=" + to;

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

            httpWebRequest.Headers["Authorization"] = authToken;
            string trans;

            Task<WebResponse> response = httpWebRequest.GetResponseAsync();

            using (Stream stream = response.Result.GetResponseStream())
            {
                System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));

                trans = (string)dcs.ReadObject(stream);
                return trans;

            }
        }
        public string Serialize(object serializableObject)
        {
            using (var memoryStream = new MemoryStream())
            {
                var serializer = new System.Runtime.Serialization.DataContractSerializer(serializableObject.GetType(),
                                                                                         null,
                                                                                         Int32.MaxValue,
                                                                                         false,
                                                                                         false,
                                                                                         null,
                                                                                         _dataContractResolver);

                serializer.WriteObject(memoryStream, serializableObject);
                memoryStream.Seek(0, SeekOrigin.Begin);

                using (var streamReader = new StreamReader(memoryStream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }
Ejemplo n.º 46
0
        /// <summary> Get object from isolated storage file.</summary>
        /// <param name="fullpath"> file name to retreive</param>
        /// <param name="type"> type of object to read</param>
        /// <returns> a <c>object</c> instance, or null if the operation failed.</returns>
        private async Task<object> GetObjectByType(string filepath, Type type)
        {
            object retVal = null;
            try
            {
                using (var releaser = await internalManifestDiskLock.ReaderLockAsync())
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " internalManifestDiskLock Reader Enter for Uri: " + filepath.ToString());

                    byte[] bytes = await Restore(filepath);
                    if (bytes != null)
                    {
                        try
                        {
                            using (MemoryStream ms = new MemoryStream(bytes))
                            {
                                if (ms != null)
                                {
                                    System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(type);
                                    retVal = ser.ReadObject(ms);
                                }
                            }
                        }
                        catch(Exception e)
                        {

                            System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " internalManifestDiskLock Reader Exception for Uri: " + filepath.ToString() + " Exception: " + e.Message);
                        }
                    }
                    System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " internalManifestDiskLock Reader Exit for Uri: " + filepath.ToString());

                }
            }
            catch(Exception)
            {

            }
            return retVal;
        }
Ejemplo n.º 47
0
 private bool LoadFromXML(System.IO.Stream stream)
 {
     var serializer = new System.Runtime.Serialization.DataContractSerializer(
                     typeof(ShaderPatcherLayer.NodeGraph));
     using (var xmlStream = System.Xml.XmlReader.Create(stream))
     {
         var o = serializer.ReadObject(xmlStream);
         if (o != null && o is ShaderPatcherLayer.NodeGraph)
         {
             graphControl.RemoveNodes(graphControl.Nodes.ToList());
             ModelConversion.AddToHyperGraph((ShaderPatcherLayer.NodeGraph)o, graphControl, _document);
             return true;
         }
     }
     return false;
 }
Ejemplo n.º 48
0
        public static Object LoadFromStringV3(Type objType, string xmlData)
        {
            System.Runtime.Serialization.DataContractSerializer ds = new System.Runtime.Serialization.DataContractSerializer(objType);

            Stream s = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(xmlData));
 
             return ds.ReadObject(s); ;
        }
Ejemplo n.º 49
0
        public void Search1Delegate(object frpair)
        {
            FederateRecord fr = ((SearchStart)frpair).fed;
            List<SearchResult> results = ((SearchStart)frpair).results;
            string terms = ((SearchStart)frpair).terms;

            System.Net.WebClient wc = GetWebClient();
            wc.Headers["Authorization"] = ((SearchStart)frpair).Authorization;

            System.Runtime.Serialization.DataContractSerializer xmls = new System.Runtime.Serialization.DataContractSerializer(typeof(List<SearchResult>));

            if (fr.ActivationState == FederateState.Active && fr.AllowFederatedSearch == true)
            {
                try
                {
                    byte[] data = wc.DownloadData(fr.RESTAPI + "/Search/" + terms + "/xml?ID=00-00-00");
                    List<SearchResult> fed_results = (List<SearchResult>)xmls.ReadObject(new MemoryStream(data));

                    lock (((System.Collections.IList)results).SyncRoot)
                    {
                        foreach (SearchResult sr in fed_results)
                            results.Add(sr);
                    }

                }
                catch (System.Exception e)
                {
                   // throw e;
                    fr.ActivationState = FederateState.Offline;
                    mFederateRegister.UpdateFederateRecord(fr);
                    return;
                }
            }
        }
 public DataContractSerializerWorker(Type t)
 {
     Serializer = new DCSerializer(t);
 }
 void IDocumentSerializer.Serialize(Stream s, object item)
 {
     DCSerializer serializer = new DCSerializer(item.GetType());
       serializer.WriteObject(s, item);
 }
 object IDocumentSerializer.Deserialize(Type t, Stream s)
 {
     DCSerializer serializer = new DCSerializer(t);
       return serializer.ReadObject(s);
 }
Ejemplo n.º 53
0
        private void OnSaveAs(object sender, ExecuteEventArgs e)
        {
            using (SaveFileDialog dialog = new SaveFileDialog())
            {
                dialog.Filter = "Shader file (*.sh)|*.sh|All files (*.*)|*.*";
                dialog.FilterIndex = 0;
                dialog.RestoreDirectory = true;

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    using (var stream = dialog.OpenFile())
                    {
                        using (var xmlStream = new System.IO.MemoryStream())
                        {
                            var nodeGraph = ModelConversion.ToShaderPatcherLayer(graphControl);
                            var serializer = new System.Runtime.Serialization.DataContractSerializer(
                                typeof(ShaderPatcherLayer.NodeGraph));
                            var settings = new System.Xml.XmlWriterSettings()
                            {
                                Indent = true,
                                IndentChars = "\t",
                                Encoding = System.Text.Encoding.ASCII
                            };

                                // write the xml to a memory stream to begin with
                            using (var writer = System.Xml.XmlWriter.Create(xmlStream, settings))
                            {
                                serializer.WriteObject(writer, nodeGraph);
                            }

                                // we hide the memory stream within a comment, and write
                                // out a hlsl shader file
                                // The HLSL compiler doesn't like UTF files... It just wants plain ASCII encoding

                            using (var sw = new System.IO.StreamWriter(stream, System.Text.Encoding.ASCII))
                            {
                                var shader = ShaderPatcherLayer.NodeGraph.GenerateShader(nodeGraph, System.IO.Path.GetFileNameWithoutExtension(dialog.FileName));
                                sw.Write(shader);

                                sw.Write("/* **** **** NodeEditor **** **** \r\nNEStart{");
                                sw.Flush();
                                xmlStream.WriteTo(stream);
                                sw.Write("}NEEnd\r\n **** **** */\r\n");
                            }

                        }
                    }
                }
            }
        }
        public static OrderStatus FromXml(string xml)
        {
            var deserializer = new System.Runtime.Serialization.DataContractSerializer(typeof(OrderStatus));

            using (var sr = new System.IO.StringReader(xml))
            using (var reader = System.Xml.XmlReader.Create(sr))
            {
                return deserializer.ReadObject(reader) as OrderStatus;
            }
        }
        public static RoomAvailability FromXml(string xml)
        {
            var deserializer = new System.Runtime.Serialization.DataContractSerializer(typeof(RoomAvailability));

            using (var sr = new System.IO.StringReader(xml))
            using (var reader = System.Xml.XmlReader.Create(sr))
            {
                return deserializer.ReadObject(reader) as RoomAvailability;
            }
        }
Ejemplo n.º 56
0
 async private Task RestoreMediaFilesAsync()
 {
     string fullPath = "mediafiles.xml";
     ulong size = 0;
     try
     {
         Windows.Storage.StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(fullPath);
         if (file != null)
         {
             var prop = await file.GetBasicPropertiesAsync();
             if (prop != null)
                 size = prop.Size;
         }
         var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
         if (stream != null)
         {
             using (var inputStream = stream.GetInputStreamAt(0))
             {
                 System.Runtime.Serialization.DataContractSerializer sessionSerializer = new System.Runtime.Serialization.DataContractSerializer(typeof(Dictionary<string, MediaLibraryItem>));
                 defaultMediaDictionary = (Dictionary<string, MediaLibraryItem>)sessionSerializer.ReadObject(inputStream.AsStreamForRead());
                 fileDiscovered = (uint)defaultMediaDictionary.Count();
             }
         }            
     }
     catch (Exception e)
     {
         LogMessage("Exception while restoring mediafiles:" + e.Message);
     }
 }
Ejemplo n.º 57
0
        async private Task SaveMediaFilesAsync()
        {
            string fullPath = "mediafiles.xml";
            try
            { 
                Windows.Storage.StorageFile file;
                bool bRes = await DeleteFile(fullPath);
                file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fullPath);
                if (file != null)
                {
                    using (var stream = await file.OpenStreamForWriteAsync())
                    {
                        if (stream != null)
                        {
                            System.Runtime.Serialization.DataContractSerializer sessionSerializer = new System.Runtime.Serialization.DataContractSerializer(typeof(Dictionary<string, MediaLibraryItem>));
                            sessionSerializer.WriteObject(stream, defaultMediaDictionary);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogMessage("Exception while saving mediafiles:" + e.Message);
            }

        }
Ejemplo n.º 58
0
 public static void WriteToSdcard(object obj, string fileName)
 {
     if (Directory.Exists ("/sdcard"))
     {
         using (var writer = new StreamWriter (System.IO.Path.Combine("/sdcard", fileName)))
         {
             var serializer = new System.Runtime.Serialization.DataContractSerializer (obj.GetType ());
             serializer.WriteObject (writer.BaseStream, obj);
         }
     }
 }
        public static OrderStatus FromBinary(byte[] buffer)
        {
            var deserializer = new System.Runtime.Serialization.DataContractSerializer(typeof(OrderStatus));

            using (var ms = new System.IO.MemoryStream(buffer))
            using (var reader = System.Xml.XmlDictionaryReader.CreateBinaryReader(ms, System.Xml.XmlDictionaryReaderQuotas.Max))
            {
                return deserializer.ReadObject(reader) as OrderStatus;
            }
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Returns an XML <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. 
        /// </summary>
        /// <returns>An XML <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.</returns>
        public virtual string ToXml()
        {
            var settings = new System.Xml.XmlWriterSettings();
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;

            var sb = new System.Text.StringBuilder();
            using (var writer = System.Xml.XmlWriter.Create(sb, settings))
            {
                var serializer = new System.Runtime.Serialization.DataContractSerializer(GetType());
                serializer.WriteObject(writer, this);
                writer.Flush();
            }

            return sb.ToString();
        }