/// <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);
        }
    }
 /// <summary>
 /// Guarda la puntuación maxima.
 /// </summary>
 private void XML_GuardarNuevaPuntuacionMaxima()
 {
     using (var fileStream = new FileStream("puntuacionMaxima.xml", FileMode.Create))
     {
         DataContractSerializer serializer = new DataContractSerializer(typeof(int));
         serializer.WriteObject(fileStream, Puntuacion);
     }
 }
Esempio n. 3
0
    /// <summary>
    /// Serializes a set of Reminders to an XML file.
    /// </summary>
    /// 
    /// <param name="filename">Desired filename of XML file. Will overwrite if exists.</param>
    public static void SerializeReminders(ReminderCollection reminders, string filename)
    {
        DataContractSerializer x = new DataContractSerializer(typeof(ReminderCollection));

        FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
        x.WriteObject(fs, reminders);

        fs.Close();
    }
Esempio n. 4
0
    public static void SerializeDiaryEntryCollection(DiaryEntryCollection collection, string filename)
    {
        DataContractSerializer x = new DataContractSerializer(typeof(DiaryEntryCollection));

        FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
        x.WriteObject(fs, collection);

        fs.Close();
    }
Esempio n. 5
0
    /// <summary>
    /// Construct a set of Reminders from an XML file. It is assumed
    /// that the filename path is correctly constructed.
    /// </summary>
    /// 
    /// <param name="filename">Path to the XML file.</param>
    /// 
    /// <returns>Reminders constructed from serialized version.</returns>
    public static ReminderCollection DeserializeReminders(string filename)
    {
        DataContractSerializer x = new DataContractSerializer(typeof(ReminderCollection));

        FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
        ReminderCollection reminders = x.ReadObject(fs) as ReminderCollection;
        fs.Close();

        return reminders;
    }
        public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
        {
            DataContractSerializer dataContractSerializer = new DataContractSerializer(Type.GetTypeFromHandle(declaredTypeHandle),
                GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList), 1, false, false); //  maxItemsInObjectGraph //  ignoreExtensionDataObject //  preserveObjectReferences

            MemoryStream memoryStream = new MemoryStream();
            dataContractSerializer.WriteObject(memoryStream, obj);
            memoryStream.Position = 0;
            string serialized = new StreamReader(memoryStream).ReadToEnd();
            jsonWriter.WriteString(serialized);
        }
Esempio n. 7
0
 // Save the current session state
 static async public Task SaveAsync()
 {
     // Get the output stream for the SessionState file.
     StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
     using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
     {
         // Serialize the Session State.
         DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), knownTypes_);
         serializer.WriteObject(transaction.Stream.AsStreamForWrite(), sessionState_);
         await transaction.CommitAsync();
     }
 }
Esempio n. 8
0
 static void Speichern(string filename, LernMoment moment)
 {
     DataContractSerializer serializer = new DataContractSerializer(typeof(LernMoment));
     using (Stream stream = new FileStream(filename, FileMode.Create, FileAccess.Write))
     {
         using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8))
         {
             writer.WriteStartDocument();
             serializer.WriteObject(writer, moment);
         }
     }
 }
    public static void DCS_MyPersonSurrogate_Stress()
    {
        // This test is to verify a bug fix made in ObjectToIdCache.cs.
        // There was a bug with ObjectToIdCache.RemoveAt() method which might cause
        // one item be added into the cache more than once.
        // The issue could happen in the following scenario,
        // 1) ObjectToIdCache is used. ObjectToIdCache is used for DataContract types 
        //    marked with [DataContract(IsReference = true)].
        // 2) ObjectToIdCache.RemoveAt() is called. The method is called only when one uses
        //    DataContract Surrogate.
        // 3) There's hash-key collision in the cache and elements are deletes at certain position.
        //
        // The reason that I used multi-iterations here is because the issue does not always repro.
        // It was a matter of odds. The more iterations we run here the more likely we repro the issue. 
        for (int iterations = 0; iterations < 5; iterations++)
        {
            int length = 2000;
            DataContractSerializer dcs = new DataContractSerializer(typeof(FamilyForStress));
            dcs.SetSerializationSurrogateProvider(new MyPersonSurrogateProvider());
            var members = new NonSerializablePersonForStress[2 * length];
            for (int i = 0; i < length; i++)
            {
                var m = new NonSerializablePersonForStress("name", 30);

                // We put the same object at two different slots. Because the DataContract type
                // is marked with [DataContract(IsReference = true)], after serialization-deserialization,
                // the objects at this two places should be the same object to each other.
                members[i] = m;
                members[i + length] = m;
            }

            MemoryStream ms = new MemoryStream();
            FamilyForStress myFamily = new FamilyForStress
            {
                Members = members
            };
            dcs.WriteObject(ms, myFamily);
            ms.Position = 0;
            var newFamily = (FamilyForStress)dcs.ReadObject(ms);
            Assert.StrictEqual(myFamily.Members.Length, newFamily.Members.Length);
            for (int i = 0; i < myFamily.Members.Length; ++i)
            {
                Assert.StrictEqual(myFamily.Members[i].Name, newFamily.Members[i].Name);
            }

            var resultMembers = newFamily.Members;
            for (int i = 0; i < length; i++)
            {
                Assert.Equal(resultMembers[i], resultMembers[i + length]);
            }
        }
    }
Esempio n. 10
0
 // Save the current session state
 static async public Task SaveAsync()
 {
     // Get the output stream for the SessionState file.
     StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
     IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite);
     using (IOutputStream outStream = raStream)
     {
         // Serialize the Session State.
         DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), knownTypes_);
         serializer.WriteObject(outStream.AsStreamForWrite(), sessionState_);
         await outStream.FlushAsync();
     }
 }
Esempio n. 11
0
        public static IDomainContext GetDomainContext()
        {
            var eventSerializer = new DataContractSerializer<EventBase>(TypeHelpers.FindSerializableTypes(typeof(EventBase), Assembly.GetCallingAssembly()));

            var context = new EventSourcedDomainContext(EventSourcedDB.SampleDatabasePath(), ReadModelDB1.SampleDatabasePath(), eventSerializer);
            context.EventBus.Subscribe((x) => Console.WriteLine("domain bus event {0}", x));

            var registration = AggregateRegistration.ForType<EventSourcedRoot>()
                .WithImmediateReadModel(c => new TransactionReadModelBuilder(new SqlRepository<TransactionDataContract>(EventSourcedDB.Main, "TestId")));
            context.Register(registration);

            return context;
        }
Esempio n. 12
0
 public static void TestDataContractSerializing()
 {
     var dcs = new DataContractSerializer<Test<string>>();
     using (var fileStream = File.Create(Path.Combine("save", "test.dc")))
     {
         dcs.Serialize(fileStream, Program.GetTest());
     }
     using (var fileStream = File.OpenRead(Path.Combine("save", "test.dc")))
     {
         var test = dcs.Deserialize(fileStream);
         Debug.Assert(test.SequenceEqual(Program.GetTest()));
     }
 }
Esempio n. 13
0
    static LernMoment Lesen(string filename)
    {
        LernMoment result;
        DataContractSerializer serializer = new DataContractSerializer(typeof(LernMoment));
        using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
        {
            using (var reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
            {
                result = (LernMoment)serializer.ReadObject(reader, true);
            }
        }

        return result;
    }
Esempio n. 14
0
    public void SaveGameData()
    {
        string filename = ("savegames\\save.xml");
        DataContractSerializer ds = new DataContractSerializer(typeof(List<int>));
        XmlWriterSettings s = new XmlWriterSettings();
        using (XmlWriter w = XmlWriter.Create(filename, s))
        {
            ds.WriteObject(w, stats);
        }

        /*Stream stream = File.Open(filename, FileMode.Create);
        //SoapFormatter sformatter = new SoapFormatter();
        //sformatter.Serialize(stream, stats);
        stream.Close();*/
    }
Esempio n. 15
0
    public bool LoadGameData()
    {
        DataContractSerializer ds = new DataContractSerializer(typeof(List<int>));
        string filename = ("savegames\\save.xml");
        if (!File.Exists(filename)) { return false; }
        using (XmlReader r = XmlReader.Create(filename))
        {
            stats = (List<int>)ds.ReadObject(r);
        }

        /*Stream stream = File.Open(filename, FileMode.Open);
        //SoapFormatter sformatter = new SoapFormatter();
        //stats = (List<int>)sformatter.Deserialize(stream);
        stream.Close();*/
        return true;
    }
Esempio n. 16
0
    public static DiaryEntryCollection DeserializeDiaryEntryCollection(string filename)
    {
        if (!FileManager.Exists(filename))
        {
            // No collection exists - initialise a new one now
            return new DiaryEntryCollection(DateTime.Now);
        }

        DataContractSerializer x = new DataContractSerializer(typeof(DiaryEntryCollection));

        FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
        DiaryEntryCollection collection = x.ReadObject(fs) as DiaryEntryCollection;
        fs.Close();

        return collection;
    }
Esempio n. 17
0
 static void Main()
 {
     var me = new Person
     {
         FirstName = "Brook",
         LastName = "H.",
         Age = 39
     };
     
     //This is what system.IO is reading from the program as it communicates with the parser.
     var serializer = new DataContractSerializer(me.GetType());  
     var someRam = new MemoryStream();
     someRam.WriteObject(someRam, me);
     someRam.Seek(0, SeekOrigin.Begin);
     Console.WriteLine(XElement.Parse(Encoding.ASCII.GetString(someRam.GetBuffer()).Replace("\0", "")));
     }
Esempio n. 18
0
    public static string TableToSHA(DataTable table)
    {
        // Serialize the table
        table.TableName = "poll";
        DataContractSerializer serializer = new DataContractSerializer(typeof(DataTable));
        MemoryStream memoryStream = new MemoryStream();
        XmlWriter writer = XmlDictionaryWriter.CreateBinaryWriter(memoryStream);
        serializer.WriteObject(memoryStream, table);
        byte[] serializedData = memoryStream.ToArray();

        // Calculte the serialized data's hash value
        SHA1CryptoServiceProvider SHA = new SHA1CryptoServiceProvider();
        byte[] hash = SHA.ComputeHash(serializedData);

        // Convert the hash to a base 64 string
        return Convert.ToBase64String(hash);
    }
Esempio n. 19
0
    // Restore the saved sesison state
    static async public Task RestoreAsync()
    {
        // Get the input stream for the SessionState file.
        try
        {
            StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
            if (file == null) return;
            IInputStream inStream = await file.OpenSequentialReadAsync();

            // Deserialize the Session State.
            DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), knownTypes_);
            sessionState_ = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());
        }
        catch (Exception)
        {
            // Restoring state is best-effort.  If it fails, the app will just come up with a new session.
        }
    }
Esempio n. 20
0
        private void AssertConfigurationIsValid()
        {
            if (Serializer == null && TypeProvider != null)
            {
                Serializer = new DataContractSerializer(TypeProvider);
            }

            var validatableComponents = GetType().GetProperties()
                                                 .Select(p => p.GetValue(this))
                                                 .OfType<IValidatableConfigurationSetting>()
                                                 .ToArray();

            var validationErrors = validatableComponents
                .SelectMany(c => c.Validate())
                .ToArray();

            if (validationErrors.None()) return;

            var message = string.Join(Environment.NewLine, new[] {"Bus configuration is invalid:"}.Concat(validationErrors));
            throw new BusException(message);
        }
    /// <summary>
    /// Obtiene la puntuación maxima, descrita en el archivo: \nombreArchivo\
    /// </summary>
    /// <param name="nombreArchivo">Nombre del archivo donde se encuentra la puntuación maxima de esta actuación</param>
    /// <returns>Puntuación maxima obtenida en la actuación</returns>
    public int ObtenerPuntacion(string nombreArchivo)
    {
        int puntuacionMaxima;
        using (var fileStream = new FileStream(nombreArchivo + LevantarTelon.DificultadActual.Sufijo + ".xml", FileMode.OpenOrCreate))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(int));

            try
            {
                var puntuacionCapturada = (int)serializer.ReadObject(fileStream);
                puntuacionMaxima = puntuacionCapturada; //Se obtiene la puntuación maxima registrada.
            }
            catch
            {
                //Si no existía antes el archivo, no habia puntuación maxima, por defecto 0.
                puntuacionMaxima = 0;
            }
        }

        return puntuacionMaxima;
    }
    void Start()
    {
        using (var fileStream = new FileStream("puntuacionMaxima.xml", FileMode.OpenOrCreate))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(int));

            try
            {
                var puntuacionCapturada = (int)serializer.ReadObject(fileStream);
                Puntuacion = puntuacionCapturada; //Se obtiene la puntuación maxima registrada.
            }
            catch
            {
                /*Si no existía antes el archivo, no habia puntuación maxima,
                    se pone la Puntuacion en 0.*/
                Puntuacion = 0;
            }
        }

        TextoPuntuacionMaxima = gameObject.GetComponent<Text>();
        TextoPuntuacionMaxima.text = "PUNTAJE MAS ALTO:\n" + Puntuacion;
    }
Esempio n. 23
0
    public static CharacterTalkText loadXML(string charactername)
    {
        string filename = getFilePath(charactername);
        CharacterTalkText obj = new CharacterTalkText();
        //保存先のファイル名

        //DataContractSerializerオブジェクトを作成
        DataContractSerializer serializer =
            new DataContractSerializer(typeof(CharacterTalkText));
        //読み込むファイルを開く
        XmlReader xr = XmlReader.Create(filename);

        XmlDocument doc = new XmlDocument();
        doc.Load(filename);
        XmlNode root = doc.LastChild;
        //Debug.Log(root.Name+", "+root.Value);
        XmlNodeList list = doc.GetElementsByTagName(CharacterTalkText.xmlnameRandom);
        //showNodes(list);
        getRandomTextTree(list[0],obj);
        list = doc.GetElementsByTagName(CharacterTalkText.xmlnameSequence);
        getSequenceTextTree(list[0],obj);
        list = doc.GetElementsByTagName(CharacterTalkText.xmlnameRestartKey);
        //Debug.Log(list[0].Name +", "+list[0].FirstChild.Value);
        obj.KeyOfRestart = int.Parse(list[0].FirstChild.Value);
        list = doc.GetElementsByTagName(CharacterTalkText.xmlnameTextLoop);
        obj.TextLoop = bool.Parse(list[0].FirstChild.Value);
        Debug.Log("END!");
        //Debug.Log(obj.RandomTexts.Count);
        //Debug.Log(obj.SequenceTexts.Count);
        //XMLファイルから読み込み、逆シリアル化する
        //CharacterTalkText obj = (CharacterTalkText)serializer.ReadObject(xr);
        //ファイルを閉じる
        xr.Close();
        //return obj;

        return obj;
    }
Esempio n. 24
0
		public void SerializerDynamicInvoke ()
		{
			var a = new DingusSyncData ();
			a.Aircraft = new AircraftDTO[] { new AircraftDTO () { } };
			a.AircraftTypes = new AircraftTypeDTO[] { new AircraftTypeDTO () };
			a.Airlines= new AirlineDTO[] { new AirlineDTO () };
			a.Airports= new AirportDTO[] { new AirportDTO() };
			a.Approaches= new ApproachDTO[] { new ApproachDTO() };
			a.ApproachesLegs= new ApproachesLegDTO[] { new ApproachesLegDTO() };
			a.Binaries= new BinaryCatalogDTO[] { new BinaryCatalogDTO() };
			a.Crews= new CrewDTO[] { new CrewDTO() };
			a.Days= new DayDTO[] { new DayDTO() };
			a.EmploymentEvents= new EmploymentEventDTO[] { new EmploymentEventDTO() };
			a.Events= new EventDTO[] { new EventDTO() };
			a.FlightDataInspection = new DataInspection ();
			a.GlobalSettings= new GlobalSettingDTO[] { new GlobalSettingDTO() };
			a.Hotels= new HotelDTO[] { new HotelDTO() };
			a.Legs= new LegDTO[] { new LegDTO() };
			a.Notes= new NoteDTO[] { new NoteDTO() };
			a.PayperiodEvents= new PayperiodEventDTO[] { new PayperiodEventDTO() };
			a.PayrollCategories= new PayrollCategoryDTO[] { new PayrollCategoryDTO() };
			a.Payrolls= new PayrollDTO[] { new PayrollDTO() };
			a.Performances= new PerformanceDTO[] { new PerformanceDTO() };
			a.Positions= new PositionDTO[] { new PositionDTO() };
			a.ReglatoryOperationTypes= new ReglatoryOperationTypeDTO[] { new ReglatoryOperationTypeDTO() };
			a.Trips= new TripDTO[] { new TripDTO() };
			a.UserSettings= new UserSettingDTO[] { new UserSettingDTO() };

			Console.WriteLine ("Size is: {0}", global::System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)));
			using (var ms = new MemoryStream ()) {
				DataContractSerializer serializer = new DataContractSerializer (typeof(DingusSyncData));
				serializer.WriteObject (ms, a);
				ms.Position = 0;
				var b = serializer.ReadObject (ms);
			}
		}
 public static async Task <object> ReadObjectAsync(this DataContractSerializer serializer, XmlReader reader)
 {
     return(await Task.Run(() => serializer.ReadObject(reader)));
 }
        /// <summary>
        /// Deserialize an object
        /// </summary>
        /// <typeparam name="T">The Type of object being deserialized</typeparam>
        /// <param name="xml">The results of a previous call to <see cref="ToXml"/></param>
        /// <returns>The deserialized object</returns>
        static public T FromXml <T>(string xml)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));

            return((T)_FromXml(xml, serializer));
        }
Esempio n. 27
0
        public static void Save <T>(Stream stream, T obj) where T : class
        {
            var writer = new DataContractSerializer(typeof(T));

            writer.WriteObject(stream, obj);
        }
Esempio n. 28
0
 private DataContractSerializer GetSerializer <U>()
 {
     _serializer = new DataContractSerializer(typeof(U));
     return(_serializer);
 }
Esempio n. 29
0
        private void OnWriteDataContractSerializerBodyContents(XmlDictionaryWriter writer)
        {
            Debug.Assert(_outResults != null, "Object should set empty out results");

            writer.WriteStartElement(_envelopeName, _serviceNamespace);

            foreach (var outResult in _outResults)
            {
                string value = null;

                if (outResult.Value is Guid)
                {
                    value = outResult.Value.ToString();
                }
                else if (outResult.Value is bool)
                {
                    value = outResult.Value.ToString().ToLower();
                }
                else if (outResult.Value is string)
                {
                    value = System.Security.SecurityElement.Escape(outResult.Value.ToString());
                }
                else if (outResult.Value is Enum)
                {
                    value = outResult.Value.ToString();
                }
                else if (outResult.Value == null)
                {
                    value = null;
                }
                else
                {
                    //for complex types
                    using (var ms = new MemoryStream())
                        using (var stream = new BufferedStream(ms))
                        {
                            Type outResultType = outResult.Value.GetType();
                            IEnumerable <Type> serviceKnownTypes = _operation
                                                                   .GetServiceKnownTypesHierarchy()
                                                                   .Select(x => x.Type);

                            var serializer = new DataContractSerializer(outResultType, serviceKnownTypes);
                            serializer.WriteObject(ms, outResult.Value);

                            stream.Position = 0;
                            using (var reader = XmlReader.Create(stream))
                            {
                                reader.MoveToContent();
                                value = reader.ReadInnerXml();
                            }
                        }
                }

                if (value != null)
                {
                    writer.WriteRaw(string.Format("<{0}>{1}</{0}>", outResult.Key, value));
                }
            }

            if (_result != null)
            {
                if (_result is Stream)
                {
                    writer.WriteStartElement(_resultName, _serviceNamespace);
                    WriteStream(writer, _result);
                    writer.WriteEndElement();
                }
                else
                {
                    // When operation return type is `System.Object` the `DataContractSerializer` adds `i:type` attribute with the correct object type
                    Type resultType = _operation.ReturnType;
                    IEnumerable <Type> serviceKnownTypes = _operation
                                                           .GetServiceKnownTypesHierarchy()
                                                           .Select(x => x.Type);

                    // When `KnownTypeAttribute` is present the `DataContractSerializer` adds `i:type` attribute with the correct object type
                    DataContractSerializer serializer = resultType.TryGetBaseTypeWithKnownTypes(out Type resultBaseTypeWithKnownTypes)
                                                ? new DataContractSerializer(resultBaseTypeWithKnownTypes, _resultName, _serviceNamespace, serviceKnownTypes)
                                                : new DataContractSerializer(resultType, _resultName, _serviceNamespace, serviceKnownTypes);

                    serializer.WriteObject(writer, _result);
                }
            }

            writer.WriteEndElement();
        }
Esempio n. 30
0
        public About GetAboutData()
        {
            // trace getting data
            TraceHelper.AddMessage("Get About Data");

            // get a stream to the about XML file
            Stream stream = AppResourcesHelper.GetResourceStream("About.xml");

            // deserialize the file
            DataContractSerializer dc = new DataContractSerializer(typeof(About));
            return (About) dc.ReadObject(stream);
        }
        public void Run(ICompiledApplication application)
        {
            TelemetryListenerArray telemetry = null;

            if (application.Configurations.TryGetValue(typeof(ReactiveMachine.TelemetryBlobWriter.Configuration), out var c))
            {
                telemetry = new TelemetryListenerArray((ReactiveMachine.TelemetryBlobWriter.Configuration)c, application, this.GetType(), deploymentId, deploymentTimestamp);
                application.HostServices.RegisterTelemetryListener(telemetry);
            }

            application.HostServices.RegisterSend(Send);
            application.HostServices.RegisterGlobalExceptionHandler(HandleGlobalException);
            application.HostServices.RegisterGlobalShutdown(() => shutdown.Cancel());
            _serializer = new DataContractSerializer(typeof(IMessage), application.SerializableTypes);


            processes = new ProcessInfo[application.NumberProcesses];
            for (uint i = 0; i < application.NumberProcesses; i++)
            {
                processes[i] = new ProcessInfo()
                {
                    Inbox = new List <IMessage>(),
                };
            }
            for (uint i = 0; i < application.NumberProcesses; i++)
            {
                var info = processes[i];

                logger.LogDebug($"Recovering process {i}.");

                info.Process = application.MakeProcess(i);
                info.Process.FirstStart();
            }
            for (uint i = 0; i < application.NumberProcesses; i++)
            {
                uint processId = i;
                new Thread(() => RunProcess(processId, processes[processId], application)).Start();
            }

            bool someoneBusy = true;

            while (!shutdown.IsCancellationRequested)
            {
                someoneBusy = false;
                for (uint i = 0; i < application.NumberProcesses; i++)
                {
                    var  info = processes[i];
                    long received;
                    bool busy;
                    lock (info)
                    {
                        received = info.Received;
                        busy     = (info.Inbox.Count > 0) || (info.Process?.RequestsOutstanding() ?? true);
                    }
                    someoneBusy = busy || someoneBusy;
                    logger.LogInformation($"Process {i}: Received={received:D12} busy={busy}");
                }
                if (!someoneBusy)
                {
                    break;
                }

                shutdown.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(10));
            }

            telemetry?.Shutdown().Wait();
        }
Esempio n. 32
0
        static void Main(string[] args)
        {
            Random rnd = new Random();
            int    n   = rnd.Next(5, 10);

            ConsoleSimbolStruct[] symbols = new ConsoleSimbolStruct[n];
            for (int i = 0; i < n; i++)
            {
                if (i % 2 == 0)
                {
                    symbols[i] = new ConsoleSimbolStruct((char)rnd.Next('a', 'z'), rnd.Next(0, 15), rnd.Next(0, 15));
                    Console.WriteLine($"symbol: {symbols[i].simb} x: {symbols[i].x} y: {symbols[i].y}");
                }
                else
                {
                    symbols[i] = new ColorConsoleSymbol((char)rnd.Next('a', 'z'), rnd.Next(0, 15), rnd.Next(0, 15), rnd.Next(0, 100));
                    Console.WriteLine($"colored symbol: {symbols[i].simb} x: {symbols[i].x} y: {symbols[i].y} color: {((ColorConsoleSymbol)symbols[i]).color}");
                }
            }
            Console.WriteLine("\n");
            ConsoleSimbolStruct[] newSymbols;
            // binary

            // создаем объект BinaryFormatter
            BinaryFormatter formatter = new BinaryFormatter();

            // получаем поток, куда будем записывать сериализованный объект
            using (FileStream fs = new FileStream("symbols.dat", FileMode.Create))
            {
                formatter.Serialize(fs, symbols);
                Console.WriteLine("Объект сериализован - binary");
            }

            // десериализация из файла
            using (FileStream fs = new FileStream("symbols.dat", FileMode.Open))
            {
                newSymbols = (ConsoleSimbolStruct[])formatter.Deserialize(fs);
                Console.WriteLine("Объект десериализован - binary");
                foreach (ConsoleSimbolStruct s in newSymbols)
                {
                    if (s is ColorConsoleSymbol)
                    {
                        Console.WriteLine($"colored symbol: {s.simb} x: {s.x} y: {s.y} color: {((ColorConsoleSymbol)s).color}");
                    }
                    else
                    {
                        Console.WriteLine($"symbol: {s.simb} x: {s.x} y: {s.y}");
                    }
                }
            }

            //XML

            XmlSerializer XMLserializer = new XmlSerializer(typeof(ConsoleSimbolStruct[]), new Type[] { typeof(ColorConsoleSymbol) });

            // получаем поток, куда будем записывать сериализованный объект
            using (FileStream fs = new FileStream("symbols.xml", FileMode.Create))
            {
                XMLserializer.Serialize(fs, symbols);

                Console.WriteLine("Объект сериализован - XML");
            }

            // десериализация
            using (FileStream fs = new FileStream("symbols.xml", FileMode.Open))
            {
                newSymbols = (ConsoleSimbolStruct[])XMLserializer.Deserialize(fs);

                Console.WriteLine("Объект десериализован - XML");
                foreach (ConsoleSimbolStruct s in newSymbols)
                {
                    if (s is ColorConsoleSymbol)
                    {
                        Console.WriteLine($"colored symbol: {s.simb} x: {s.x} y: {s.y} color: {((ColorConsoleSymbol)s).color}");
                    }
                    else
                    {
                        Console.WriteLine($"symbol: {s.simb} x: {s.x} y: {s.y}");
                    }
                }
            }

            // JSON

            // сериализация в файл
            string json = JsonSerializer.Serialize(symbols, new JsonSerializerOptions {
            });

            File.WriteAllText("symbols.json", json);
            Console.WriteLine("file serialized - JSON");
            Console.WriteLine(json);
            // десериализация
            newSymbols = JsonSerializer.Deserialize <ConsoleSimbolStruct[]>(File.ReadAllText("symbols.json"));
            Console.WriteLine("file deserialized - JSON");
            foreach (ConsoleSimbolStruct s in newSymbols)
            {
                if (s is ColorConsoleSymbol)
                {
                    Console.WriteLine($"colored symbol: {s.simb} x: {s.x} y: {s.y} color: {((ColorConsoleSymbol)s).color}");
                }
                else
                {
                    Console.WriteLine($"symbol: {s.simb} x: {s.x} y: {s.y}");
                }
            }

            // data contract


            using (FileStream fs = new FileStream("symbols.txt", FileMode.Create))
            {
                //Serialize the Record object to a memory stream using DataContractSerializer.
                DataContractSerializer serializer = new DataContractSerializer(typeof(ConsoleSimbolStruct[]), new Type[] { typeof(ColorConsoleSymbol) });
                serializer.WriteObject(fs, symbols);
                Console.WriteLine("data serialized - data contracts");

                fs.Position = 0;

                //Deserialize the Record object back into a new record object.
                newSymbols = (ConsoleSimbolStruct[])serializer.ReadObject(fs);

                Console.WriteLine("data deserialized - data contracts");
                foreach (ConsoleSimbolStruct s in newSymbols)
                {
                    if (s is ColorConsoleSymbol)
                    {
                        Console.WriteLine($"colored symbol: {s.simb} x: {s.x} y: {s.y} color: {((ColorConsoleSymbol)s).color}");
                    }
                    else
                    {
                        Console.WriteLine($"symbol: {s.simb} x: {s.x} y: {s.y}");
                    }
                }
            }
        }
Esempio n. 33
0
 public AirlineSerializer()
 {
     serializer = new DataContractSerializer(typeof(Airline));
 }
        /// <summary>
        /// Serialize an object
        /// </summary>
        /// <param name="o">The object to convert to XML</para
        /// <param name="rootName">Typically the object name, 'Employees', for instance</param>
        /// <param name="rootNamespace">An xml namespaces, example, 'http://www.entityspaces.net'</param>
        /// <returns>The serialized contract in the form of a string</returns>
        static public string ToXml(object o, string rootName, string rootNamespace)
        {
            DataContractSerializer dcs = new DataContractSerializer(o.GetType(), rootName, rootNamespace);

            return(_ToXml(o, dcs));
        }
Esempio n. 35
0
        /// <summary>
        /// Deserialise the previously serialised repository. Perform as a single step so that it
        /// goes faster at the cost of providing less feedbak to the user.
        /// </summary>

        public void DeSerializeRepository()
        {
            localGVLogging.LogRoutineEntry(nameof(DeSerializeRepository));

            try
            {
                DataContractSerializer ser = new DataContractSerializer(typeof(DataInstance));

                using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // Check of the file exists
                    string DataInstanceFileName = typeof(DataInstance).Name.Trim() + ".json";

                    if (!isoStore.FileExists(DataInstanceFileName))
                    {
                        DataStore.CN.NotifyError("DeSerializeRepository - File: " + DataInstanceFileName + " does not exist.  Reload the GPKG file");
                        CommonLocalSettings.DataSerialised = false;
                        return;
                    }

                    var stream = new IsolatedStorageFileStream(DataInstanceFileName, FileMode.Open, isoStore);

                    using (StreamReader file = new StreamReader(stream))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        serializer.Converters.Add(new GrampsView.Converters.NewtonSoftColorConverter());

                        DataInstance t = (DataInstance)serializer.Deserialize(file, typeof(DataInstance));

                        // Check for nulls
                        if (t.AddressData != null)
                        {
                            DataStore.DS.AddressData = t.AddressData;
                        }
                        else
                        {
                            CommonLocalSettings.DataSerialised = false;
                            DataStore.CN.NotifyError("Bad Address deserialisation error.  Data loading cancelled. Restart the program and reload the data.");
                        }

                        if (t.BookMarkCollection != null)
                        {
                            DataStore.DS.BookMarkCollection = t.BookMarkCollection;
                        }
                        else
                        {
                            CommonLocalSettings.DataSerialised = false;
                            DataStore.CN.NotifyError("Bad BookMark deserialisation error.  Data loading cancelled. Restart the program and reload the data.");
                        }

                        if (t.CitationData != null)
                        {
                            DataStore.DS.CitationData = t.CitationData;
                        }
                        else
                        {
                            CommonLocalSettings.DataSerialised = false;
                            DataStore.CN.NotifyError("Bad Citation deserialisation error.  Data loading cancelled. Restart the program and reload the data.");
                        }

                        if (t.EventData != null)
                        {
                            DataStore.DS.EventData = t.EventData;
                        }
                        else
                        {
                            CommonLocalSettings.DataSerialised = false;
                            DataStore.CN.NotifyError("Bad Event deserialisation error.  Data loading cancelled. Restart the program and reload the data.");
                        }

                        if (t.FamilyData != null)
                        {
                            DataStore.DS.FamilyData = t.FamilyData;
                        }
                        else
                        {
                            CommonLocalSettings.DataSerialised = false;
                            DataStore.CN.NotifyError("Bad Family deserialisation error.  Data loading cancelled. Restart the program and reload the data.");
                        }

                        if (t.MediaData != null)
                        {
                            DataStore.DS.MediaData = t.MediaData;
                        }
                        else
                        {
                            CommonLocalSettings.DataSerialised = false;
                            DataStore.CN.NotifyError("Bad Media deserialisation error.  Data loading cancelled. Restart the program and reload the data.");
                        }

                        if (t.PersonData != null)
                        {
                            DataStore.DS.PersonData = t.PersonData;
                        }
                        else
                        {
                            CommonLocalSettings.DataSerialised = false;
                            DataStore.CN.NotifyError("Bad Person deserialisation error.  Data loading cancelled. Restart the program and reload the data.");
                        }

                        if (t.PersonNameData != null)
                        {
                            DataStore.DS.PersonNameData = t.PersonNameData;
                        }
                        else
                        {
                            CommonLocalSettings.DataSerialised = false;
                            DataStore.CN.NotifyError("Bad Person Name deserialisation error.  Data loading cancelled. Restart the program and reload the data.");
                        }

                        // Check for nulls
                        if (t.SourceData != null)
                        {
                            DataStore.DS.SourceData = t.SourceData;
                        }
                        else
                        {
                            CommonLocalSettings.DataSerialised = false;
                            DataStore.CN.NotifyError("Bad Source data deserialisation error.  Data loading cancelled. Restart the program and reload the data.");
                        }

                        // Check for nulls
                        if (t.TagData != null)
                        {
                            DataStore.DS.TagData = t.TagData;
                        }
                        else
                        {
                            CommonLocalSettings.DataSerialised = false;
                            DataStore.CN.NotifyError("Bad Tag data deserialisation error.  Data loading cancelled. Restart the program and reload the data.");
                        }

                        // TODO Finish setting the checks up on these
                        DataStore.DS.HeaderData  = t.HeaderData;
                        DataStore.DS.NameMapData = t.NameMapData;
                        DataStore.DS.NoteData    = t.NoteData;

                        DataStore.DS.PlaceData      = t.PlaceData;
                        DataStore.DS.RepositoryData = t.RepositoryData;
                    }
                }

                localGVLogging.LogRoutineExit(nameof(DeSerializeRepository));
            }
            catch (Exception ex)
            {
                localGVLogging.LogProgress("DeSerializeRepository - Exception ");
                CommonLocalSettings.DataSerialised = false;
                DataStore.CN.NotifyException("Old data deserialisation error.  Data loading cancelled", ex);
                throw;
            }

            return;
        }
        /// <summary>
        /// This overload can preserve object references
        /// </summary>
        /// <param name="o">The object to convert to XML</para
        /// <param name="rootName">Typically the object name, 'Employees', for instance</param>
        /// <param name="rootNamespace">An xml namespaces, example, 'http://www.entityspaces.net'</param>
        /// <param name="preserveObjectReferences">If 'True' then if the same object is in the graph twice it will only be serialized once. The other instance will be a pointer to the first</param>
        /// <returns>The serialized contract in the form of a string</returns>
        static public string ToXml(object o, string rootName, string rootNamespace, bool preserveObjectReferences)
        {
            DataContractSerializer dcs = new DataContractSerializer(o.GetType(), rootName, rootNamespace, null, Int32.MaxValue, true, true, null);

            return(_ToXml(o, dcs));
        }
    /// <summary>
    /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
    /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
    /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
    /// state.
    /// </summary>
    /// <returns>An asynchronous task that reflects when session state has been read.  The
    /// content of <see cref="SessionState"/> should not be relied upon until this task
    /// completes.</returns>
    public static async Task RestoreAsync()
    {
        _sessionState = new Dictionary<String, Object>();

        try
        {
            // Get the input stream for the SessionState file
            StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename);
            using (IInputStream inStream = await file.OpenSequentialReadAsync())
            {
                // Deserialize the Session State
                DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
                _sessionState = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());
            }

            // Restore any registered frames to their saved state
            foreach (var weakFrameReference in _registeredFrames)
            {
                Frame frame;
                if (weakFrameReference.TryGetTarget(out frame))
                {
                    frame.ClearValue(FrameSessionStateProperty);
                    RestoreFrameNavigationState(frame);
                }
            }
        }
        catch (Exception e)
        {
            throw new SuspensionManagerException(e);
        }
    }
Esempio n. 38
0
        object Request(OperationDescription od, bool isAsync, ref object [] parameters, OperationContext context)
        {
            ClientOperation op = runtime.Operations [od.Name];

            object [] inspections = new object [runtime.MessageInspectors.Count];
            Message   req         = CreateRequest(op, parameters, context);

            for (int i = 0; i < inspections.Length; i++)
            {
                inspections [i] = runtime.MessageInspectors [i].BeforeSendRequest(ref req, this);
            }

            Message res = Request(req, OperationTimeout);

            if (res.IsFault)
            {
                var          resb  = res.CreateBufferedCopy(runtime.MaxFaultSize);
                MessageFault fault = MessageFault.CreateFault(resb.CreateMessage(), runtime.MaxFaultSize);
                var          conv  = OperationChannel.GetProperty <FaultConverter> () ?? FaultConverter.GetDefaultFaultConverter(res.Version);
                Exception    ex;
                if (!conv.TryCreateException(resb.CreateMessage(), fault, out ex))
                {
                    if (fault.HasDetail)
                    {
                        Type detailType           = typeof(ExceptionDetail);
                        var  freader              = fault.GetReaderAtDetailContents();
                        DataContractSerializer ds = null;
                        foreach (var fci in op.FaultContractInfos)
                        {
                            if (res.Headers.Action == fci.Action || fci.Serializer.IsStartObject(freader))
                            {
                                detailType = fci.Detail;
                                ds         = fci.Serializer;
                                break;
                            }
                        }
                        if (ds == null)
                        {
                            ds = new DataContractSerializer(detailType);
                        }
                        var detail = ds.ReadObject(freader);
                        ex = (Exception)Activator.CreateInstance(typeof(FaultException <>).MakeGenericType(detailType), new object [] { detail, fault.Reason, fault.Code, res.Headers.Action });
                    }

                    if (ex == null)
                    {
                        ex = new FaultException(fault);
                    }
                }
                throw ex;
            }

            for (int i = 0; i < inspections.Length; i++)
            {
                runtime.MessageInspectors [i].AfterReceiveReply(ref res, inspections [i]);
            }

            if (!op.DeserializeReply)
            {
                return(res);
            }

            if (isAsync && od.EndMethod != null)
            {
                var endParams = od.EndMethod.GetParameters();
                parameters = new object [endParams.Length - 1];
            }

            return(op.Formatter.DeserializeReply(res, parameters));
        }
Esempio n. 39
0
        protected IShortcodeResult Execute(string endpoint, string url, IEnumerable <string> query, IExecutionContext context)
        {
            // Get the oEmbed response
            EmbedResponse embedResponse;

            using (HttpClient httpClient = context.CreateHttpClient())
            {
                string request = $"{endpoint}?url={WebUtility.UrlEncode(url)}";
                if (query != null)
                {
                    request += "&" + string.Join("&", query);
                }
                HttpResponseMessage response = httpClient.GetAsync(request).Result;
                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    Trace.Error($"Received 404 not found for oEmbed at {request}");
                }
                response.EnsureSuccessStatusCode();
                if (response.Content.Headers.ContentType.MediaType == "application/json" ||
                    response.Content.Headers.ContentType.MediaType == "text/html")
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(EmbedResponse));
                    using (Stream stream = response.Content.ReadAsStreamAsync().Result)
                    {
                        embedResponse = (EmbedResponse)serializer.ReadObject(stream);
                    }
                }
                else if (response.Content.Headers.ContentType.MediaType == "text/xml")
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(EmbedResponse));
                    using (Stream stream = response.Content.ReadAsStreamAsync().Result)
                    {
                        embedResponse = (EmbedResponse)serializer.ReadObject(stream);
                    }
                }
                else
                {
                    throw new InvalidDataException("Unknown content type for oEmbed response");
                }
            }

            // Switch based on type
            if (!string.IsNullOrEmpty(embedResponse.Html))
            {
                return(context.GetShortcodeResult(embedResponse.Html));
            }
            else if (embedResponse.Type == "photo")
            {
                if (string.IsNullOrEmpty(embedResponse.Url) ||
                    string.IsNullOrEmpty(embedResponse.Width) ||
                    string.IsNullOrEmpty(embedResponse.Height))
                {
                    throw new InvalidDataException("Did not receive required oEmbed values for image type");
                }
                return(context.GetShortcodeResult($"<img src=\"{embedResponse.Url}\" width=\"{embedResponse.Width}\" height=\"{embedResponse.Height}\" />"));
            }
            else if (embedResponse.Type == "link")
            {
                if (!string.IsNullOrEmpty(embedResponse.Title))
                {
                    return(context.GetShortcodeResult($"<a href=\"{url}\">{embedResponse.Title}</a>"));
                }
                return(context.GetShortcodeResult($"<a href=\"{url}\">{url}</a>"));
            }

            throw new InvalidDataException("Could not determine embedded content for oEmbed response");
        }
Esempio n. 40
0
 static UsageCredit()
 {
     UsageCredit.Serializer = new DataContractSerializer(typeof(UsageCredit));
 }
Esempio n. 41
0
        public void TestDataContractSerializer()
        {
            var o        = CreateM2();
            var messages = new IMessage[]
            {
                o
            };

            var dataContractSerializer = new DataContractSerializer(typeof(ArrayList), new[]
            {
                typeof(M2),
                typeof(SomeEnum),
                typeof(M1),
                typeof(Risk),
                typeof(List <M1>)
            });

            var sw = new Stopwatch();

            sw.Start();

            var xmlWriterSettings = new XmlWriterSettings
            {
                OmitXmlDeclaration = false
            };

            var xmlReaderSettings = new XmlReaderSettings
            {
                IgnoreProcessingInstructions = true,
                ValidationType   = ValidationType.None,
                IgnoreWhitespace = true,
                CheckCharacters  = false,
                ConformanceLevel = ConformanceLevel.Auto
            };

            for (var i = 0; i < numberOfIterations; i++)
            {
                using (var stream = new MemoryStream())
                    DataContractSerialize(xmlWriterSettings, dataContractSerializer, messages, stream);
            }

            sw.Stop();
            Debug.WriteLine("serialization " + sw.Elapsed);

            sw.Reset();

            File.Delete("a.xml");
            using (var fs = File.Open("a.xml", FileMode.OpenOrCreate))
                DataContractSerialize(xmlWriterSettings, dataContractSerializer, messages, fs);

            var s = new MemoryStream();

            DataContractSerialize(xmlWriterSettings, dataContractSerializer, messages, s);
            var buffer = s.GetBuffer();

            s.Dispose();

            sw.Start();

            for (var i = 0; i < numberOfIterations; i++)
            {
                using (var reader = XmlReader.Create(new MemoryStream(buffer), xmlReaderSettings))
                    dataContractSerializer.ReadObject(reader);
            }

            sw.Stop();
            Debug.WriteLine("deserializing: " + sw.Elapsed);
        }
        private void ImportColorCollections()
        {
            int importCount = 0;

            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                DefaultExt  = ".vcc",
                Filter      = @"Vixen 3 Color Collections (*.vcc)|*.vcc|All Files (*.*)|*.*",
                FilterIndex = 0
            };

            if (_lastFolder != string.Empty)
            {
                openFileDialog.InitialDirectory = _lastFolder;
            }
            if (openFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            _lastFolder = Path.GetDirectoryName(openFileDialog.FileName);

            if (File.Exists(openFileDialog.FileName))
            {
                using (FileStream reader = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
                {
                    DataContractSerializer ser = new DataContractSerializer(typeof(List <ColorCollection>));
                    foreach (ColorCollection colorCollection in (List <ColorCollection>)ser.ReadObject(reader))
                    {
                        if (ColorCollections.Contains(colorCollection))
                        {
                            //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                            MessageBoxForm.msgIcon = SystemIcons.Warning;                             //this is used if you want to add a system icon to the message form.
                            var messageBox = new MessageBoxForm("A collection with the name " + colorCollection.Name + @" already exists. Do you want to overwrite it?", "Overwrite collection?", true, false);
                            messageBox.ShowDialog();
                            if (messageBox.DialogResult == DialogResult.OK)
                            {
                                //Remove the collection to overwrite, we will add the new one below.
                                ColorCollections.Remove(colorCollection);
                            }
                            else
                            {
                                continue;
                            }
                        }
                        importCount++;
                        ColorCollections.Add(colorCollection);
                        _isDirty = true;
                    }
                }
                PopulateCollectionList();
                if (_currentCollection != null)
                {
                    comboBoxCollections.Text = _currentCollection.Name;
                }
                {
                    //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                    MessageBoxForm.msgIcon = SystemIcons.Information;                     //this is used if you want to add a system icon to the message form.
                    var messageBox = new MessageBoxForm("Imported " + importCount + @" Color Collections.", "Color Collections Import", false, false);
                    messageBox.ShowDialog();
                }
            }
        }
Esempio n. 43
0
        private object[] GetRequestArguments(Message requestMessage, System.Xml.XmlDictionaryReader xmlReader, OperationDescription operation, ref Dictionary <string, object> outArgs)
        {
            var parameters = operation.NormalParameters;
            // avoid reallocation
            var arguments = new List <object>(parameters.Length + operation.OutParameters.Length);

            // Find the element for the operation's data
            xmlReader.ReadStartElement(operation.Name, operation.Contract.Namespace);

            for (int i = 0; i < parameters.Length; i++)
            {
                var parameterName = parameters[i].Name;
                var parameterNs   = parameters[i].Namespace;

                if (xmlReader.IsStartElement(parameterName, parameterNs))
                {
                    xmlReader.MoveToStartElement(parameterName, parameterNs);

                    if (xmlReader.IsStartElement(parameterName, parameterNs))
                    {
                        var elementType = parameters[i].Parameter.ParameterType.GetElementType();
                        if (elementType == null || parameters[i].Parameter.ParameterType.IsArray)
                        {
                            elementType = parameters[i].Parameter.ParameterType;
                        }

                        switch (_serializer)
                        {
                        case SoapSerializer.XmlSerializer:
                        {
                            // see https://referencesource.microsoft.com/System.Xml/System/Xml/Serialization/XmlSerializer.cs.html#c97688a6c07294d5
                            var serializer = CachedXmlSerializer.GetXmlSerializer(elementType, parameterName, parameterNs);
                            lock (serializer)
                                arguments.Add(serializer.Deserialize(xmlReader));
                        }
                        break;

                        case SoapSerializer.DataContractSerializer:
                        {
                            var serializer = new DataContractSerializer(elementType, parameterName, parameterNs);
                            arguments.Add(serializer.ReadObject(xmlReader, verifyObjectName: true));
                        }
                        break;

                        default: throw new NotImplementedException();
                        }
                    }
                }
                else
                {
                    arguments.Add(null);
                }
            }

            foreach (var parameterInfo in operation.OutParameters)
            {
                if (parameterInfo.Parameter.ParameterType.Name == "Guid&")
                {
                    outArgs[parameterInfo.Name] = Guid.Empty;
                }
                else if (parameterInfo.Parameter.ParameterType.Name == "String&" || parameterInfo.Parameter.ParameterType.GetElementType().IsArray)
                {
                    outArgs[parameterInfo.Name] = null;
                }
                else
                {
                    var type = parameterInfo.Parameter.ParameterType.GetElementType();
                    outArgs[parameterInfo.Name] = Activator.CreateInstance(type);
                }
            }
            return(arguments.ToArray());
        }
Esempio n. 44
0
        public static TE DeserializeXml <TE>(this XmlReader reader)
        {
            DataContractSerializer dsc = new DataContractSerializer(typeof(TE));

            return((TE)dsc.ReadObject(reader));
        }
Esempio n. 45
0
        private void Save(string filePath)
        {
            DataContractSerializer ser = new DataContractSerializer(typeof(WindowSettings));

            byte[] fileBody = null;

            using (var memoryStream = new MemoryStream())
            {
                try
                {
                    XmlWriterSettings settings = new XmlWriterSettings
                    {
                        Indent   = true,
                        Encoding = Encoding.UTF8
                    };

                    using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, settings))
                    {
                        ser.WriteObject(xmlWriter, this);
                        xmlWriter.Flush();
                    }

                    memoryStream.Seek(0, SeekOrigin.Begin);

                    fileBody = memoryStream.ToArray();
                }
                catch (Exception ex)
                {
                    DTEHelper.WriteExceptionToLog(ex);

                    fileBody = null;
                }
            }

            if (fileBody != null)
            {
                using (Mutex mutex = new Mutex(false, FileOperations.GetMutexName(filePath)))
                {
                    try
                    {
                        mutex.WaitOne();

                        try
                        {
                            using (var stream = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                            {
                                stream.Write(fileBody, 0, fileBody.Length);
                            }
                        }
                        catch (Exception ex)
                        {
                            DTEHelper.WriteExceptionToLog(ex);
                        }
                    }
                    finally
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }
        }
Esempio n. 46
0
        public static void SerializeXml <TE>(this TE objectToSerialize, XmlWriter writer)
        {
            DataContractSerializer dsc = new DataContractSerializer(typeof(TE));

            dsc.WriteObject(writer, objectToSerialize);
        }
Esempio n. 47
0
        public static T Load <T>(Stream stream) where T : class
        {
            var reader = new DataContractSerializer(typeof(T));

            return(reader.ReadObject(stream) as T);
        }
 public static async Task WriteObjectAsync(this DataContractSerializer serializer, XmlWriter writer, object graph)
 {
     await Task.Run(() => serializer.WriteObject(writer, graph));
 }
Esempio n. 49
0
        public static void InitSample()
        {
            if (Remote == null)
            {
                TestId = Guid.NewGuid();

                var eventSerializer = new DataContractSerializer<EventBase>(TypeHelpers.FindSerializableTypes(typeof(EventBase), Assembly.GetCallingAssembly()));
                var commandSerializer = new DataContractSerializer<CommandBase>(TypeHelpers.FindSerializableTypes(typeof(CommandBase), Assembly.GetCallingAssembly()));

                Remote = new EventSourcedDomainContext(RemoteDB.SampleDatabasePath(), eventSerializer);
                Client1 = new EventSourcedDomainContext(Client1DB.SampleDatabasePath(), ReadModelDB1.SampleDatabasePath(), eventSerializer) { CommandSerializer = commandSerializer };
                Client2 = new EventSourcedDomainContext(Client2DB.SampleDatabasePath(), ReadModelDB2.SampleDatabasePath(), eventSerializer) { CommandSerializer = commandSerializer };

                var registration = AggregateRegistration.ForType<EventSourcedRoot>();
                //    .WithImmediateReadModel(c => new TransactionReadModelBuilder(new SqlRepository<TransactionDataContract>(EventSourcedDB.Main, "TestId")));
                Client1.Register(registration.WithDelayedReadModel(
                    // TODO: pass in read model db as a scope
                    scope => new TransactionReadModelBuilder(new SqlRepository<TransactionDataContract>(scope, "TestId"))));

                Client1.StartDelayedReadModels();

                Client2.Register(registration);
            }
        }
        /// <summary>
        /// Deserialize an object
        /// </summary>
        /// <param name="xml">The results of a previous call to <see cref="ToXml"/></param>
        /// <param name="type">Type type of the object, in C# use typeof(), VB use GetType()</param>
        /// <param name="rootName">Typically the object name, 'Employees', for instance</param>
        /// <param name="rootNamespace">An xml namespaces, example, 'http://www.entityspaces.net'</param>
        /// <returns>The deserialized object</returns>
        static public object FromXml(string xml, Type type, string rootName, string rootNamespace)
        {
            DataContractSerializer serializer = new DataContractSerializer(type, rootName, rootNamespace);

            return(_FromXml(xml, serializer));
        }
 /// <summary>
 /// Guarda el tiempo record
 /// </summary>
 private void XML_GuardarNuevoTiempoRecord()
 {
     using (var fileStream = new FileStream(Actuacion.ListaActuaciones[Application.loadedLevel - 1].TiempoRecordArchivo + LevantarTelon.DificultadActual.Sufijo + ".xml", FileMode.Create))
     {
         DataContractSerializer serializer = new DataContractSerializer(typeof(double));
         serializer.WriteObject(fileStream, Personaje.Tiempo);
     }
 }
Esempio n. 52
0
 public static void IXmlTextReaderInitializerTest()
 {
     DataContractSerializer serializer = new DataContractSerializer(typeof(TestData));
     MemoryStream ms = new MemoryStream();
     TestData td = new TestData();
     Encoding encoding = Encoding.UTF8;
     XmlDictionaryWriter textWriter = XmlDictionaryWriter.CreateTextWriter(ms, encoding, false);
     IXmlTextWriterInitializer writerInitializer = (IXmlTextWriterInitializer)textWriter;
     writerInitializer.SetOutput(ms, encoding, false);
     serializer.WriteObject(ms, td);
     textWriter.Flush();
     byte[] xmlDoc = ms.ToArray();
     textWriter.Close();
     XmlDictionaryReader textReader = XmlDictionaryReader.CreateTextReader(xmlDoc, 0, xmlDoc.Length, encoding, XmlDictionaryReaderQuotas.Max, new OnXmlDictionaryReaderClose((XmlDictionaryReader reader) => { }));
     IXmlTextReaderInitializer readerInitializer = (IXmlTextReaderInitializer)textReader;
     readerInitializer.SetInput(xmlDoc, 0, xmlDoc.Length, encoding, XmlDictionaryReaderQuotas.Max, new OnXmlDictionaryReaderClose((XmlDictionaryReader reader) => { }));
     textReader.ReadContentAsObject();
     textReader.Close();
 }
Esempio n. 53
0
        private void btnRandomSequenceModel_Click(object sender, EventArgs e)
        {
            // Check if we either have an saved Sequence or the user has chosen a sequence to use
            if (this.listBoxChosenCompares.Items.Count == 0 && this.lstRandomizedObjectsA == null && this.lstRandomizedObjectsB == null)
            {
                MessageBox.Show("Please select at least one compare or load a randomized set of data", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Extract the options
            NeedlemanWunschOptions options = this.controlOptions.Options;

            List <ObjectInSequence> lstSequenceA = new List <ObjectInSequence>(), lstSequenceB = new List <ObjectInSequence>();
            // Make 2 List for the ObjectsInSequences
            List <List <ObjectInSequence> > lstSequencesA = new List <List <ObjectInSequence> >(), lstSequencesB = new List <List <ObjectInSequence> >();

            // Differ if we have loaded sequences or use the chosen compares
            if (this.lstRandomizedObjectsA != null && this.lstRandomizedObjectsB != null)
            {
                lstSequenceA  = this.lstRandomizedObjectsA[0];
                lstSequencesA = this.lstRandomizedObjectsA.GetRange(1, this.lstRandomizedObjectsA.Count - 1);
                lstSequenceB  = this.lstRandomizedObjectsB[0];
                lstSequencesB = this.lstRandomizedObjectsB.GetRange(1, this.lstRandomizedObjectsB.Count - 1);

                // GO!
                ConcurrentBag <Tuple <decimal, int, int, int, int> > lstDistances = new ConcurrentBag <Tuple <decimal, int, int, int, int> >();

                // Create the Alignment
                NeedlemanWunsch nw = new NeedlemanWunsch(lstSequenceA, lstSequenceB, options, true);

                // DebugCode if we need to see the Original Alignment
                //DialogNeedlemanWunschShowAlign dialogShow = new DialogNeedlemanWunschShowAlign();
                //dialogShow.SetData(nw);
                //dialogShow.ShowDialog(this.FindForm());

                // Now loop over the created sequences and compare all of them
                Parallel.ForEach(lstSequencesA, seqA =>
                {
                    Parallel.ForEach(lstSequencesB, seqB =>
                    {
                        // Build the alignment
                        NeedlemanWunsch nwRandom = new NeedlemanWunsch(seqA, seqB, options, true);
                        // Now we need the distance
                        lstDistances.Add(Tuple.Create(nwRandom.Distance, nwRandom.NumberOfChanges, nwRandom.Backtraces.Min(bt => bt.WayBack.Count), nwRandom.SequenceA.Count, nwRandom.SequenceB.Count));
                    });
                });

                MessageBox.Show(this.FindForm(), $"Distance: {nw.Distance}{Environment.NewLine}" +
                                $"Average Random Distance: {lstDistances.Sum(dis => dis.Item1) / lstDistances.Count}{Environment.NewLine}" +
                                $"Minimum Random Distance: {lstDistances.Min(dis => dis.Item1)}{Environment.NewLine}" +
                                $"Maximum Random Distance: {lstDistances.Max(dis => dis.Item1)}{Environment.NewLine}");

                // Export all distances if wanted
                if (this.saveFileDialogCSV.ShowDialog(this.FindForm()) == DialogResult.OK)
                {
                    SaveCSV(this.saveFileDialogCSV.FileName, nw, lstDistances, lstSequenceA, lstSequenceB);
                }
            }
            else
            {
                // Here we loop over the chosen Compares
                foreach (object objAktuell in this.listBoxChosenCompares.Items)
                {
                    if (objAktuell is CompareObject compObj)
                    {
                        // Create the original sequences - Copy the choosen ones from the List if possible as default
                        lstSequenceA = new List <ObjectInSequence>();
                        lstSequenceB = new List <ObjectInSequence>();
                        compObj.SequenceA.ForEach(item => lstSequenceA.AddRange(item.ObjectsInSequence));
                        compObj.SequenceB.ForEach(item => lstSequenceB.AddRange(item.ObjectsInSequence));

                        // Check if we have locked sequences or create new ones
                        if (compObj.RandomizedSequencesA != null && compObj.RandomizedSequencesB != null)
                        {
                            lstSequencesA = new List <List <ObjectInSequence> >(compObj.RandomizedSequencesA);
                            lstSequencesB = new List <List <ObjectInSequence> >(compObj.RandomizedSequencesB);
                        }
                        else
                        {
                            RandomizeSequence(compObj.SequenceA, lstSequencesA);
                            RandomizeSequence(compObj.SequenceB, lstSequencesB);
                        }

                        // Now we have everything, runrunrun
                        ConcurrentBag <Tuple <decimal, int, int, int, int> > lstDistances = new ConcurrentBag <Tuple <decimal, int, int, int, int> >();

                        // Create the Alignment
                        NeedlemanWunsch nw = new NeedlemanWunsch(lstSequenceA, lstSequenceB, options, true);

                        // DebugCode if we need to see the Original Alignment
                        //DialogNeedlemanWunschShowAlign dialogShow = new DialogNeedlemanWunschShowAlign();
                        //dialogShow.SetData(nw);
                        //dialogShow.ShowDialog(this.FindForm());

                        // Now loop over the created sequences and compare all of them
                        Parallel.ForEach(lstSequencesA, seqA =>
                        {
                            Parallel.ForEach(lstSequencesB, seqB =>
                            {
                                // Build the alignment
                                NeedlemanWunsch nwRandom = new NeedlemanWunsch(seqA, seqB, options, true);
                                // Now we need the distance
                                lstDistances.Add(Tuple.Create(nwRandom.Distance, nwRandom.NumberOfChanges, nwRandom.Backtraces.Min(bt => bt.WayBack.Count), nwRandom.SequenceA.Count, nwRandom.SequenceB.Count));

                                //if (nwRandom.Distance < 35m)
                                //{
                                //  lstSusp.Add(nwRandom);
                                //}
                            });
                        });

                        // We get the filename from the CompareObject
                        string strSavePath = Path.Combine(Path.GetDirectoryName(compObj.SavePath), Path.GetFileNameWithoutExtension(compObj.SavePath) + $"_{options.Name}" + Path.GetExtension(compObj.SavePath));
                        SaveCSV(strSavePath, nw, lstDistances, lstSequenceA, lstSequenceB);
                        // Also save the Sequences
                        string strSavePathSequencesA, strSavePathSequencesB;
                        strSavePathSequencesA = Path.Combine(Path.GetDirectoryName(compObj.SavePath), Path.GetFileNameWithoutExtension(compObj.SavePath) + "_sequencesA.xml");
                        strSavePathSequencesB = Path.Combine(Path.GetDirectoryName(compObj.SavePath), Path.GetFileNameWithoutExtension(compObj.SavePath) + "_sequencesB.xml");
                        // Insert the original Sequence in A and save them
                        lstSequencesA.Insert(0, lstSequenceA);
                        DataContractSerializer serializer = new DataContractSerializer(typeof(List <List <ObjectInSequence> >));
                        using (XmlWriter writer = XmlWriter.Create(strSavePathSequencesA))
                        {
                            serializer.WriteObject(writer, lstSequencesA);
                            writer.Close();
                        }
                        // Same for B
                        lstSequencesB.Insert(0, lstSequenceB);
                        using (XmlWriter writer = XmlWriter.Create(strSavePathSequencesB))
                        {
                            serializer.WriteObject(writer, lstSequencesB);
                            writer.Close();
                        }

                        // Save the options?
                    }
                }

                // Show something so the user knows were done
                MessageBox.Show(this.FindForm(), "Done!");
            }
        }
Esempio n. 54
-1
        public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
        {
            string xmlContent = jsonReader.ReadElementContentAsString();

            DataContractSerializer dataContractSerializer = new DataContractSerializer(TraditionalDataContract.UnderlyingType,
                GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList), 1, false, false); //  maxItemsInObjectGraph //  ignoreExtensionDataObject //  preserveObjectReferences

            MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlContent));
            object xmlValue;
            XmlDictionaryReaderQuotas quotas = ((JsonReaderDelegator)jsonReader).ReaderQuotas;
            if (quotas == null)
            {
                xmlValue = dataContractSerializer.ReadObject(memoryStream);
            }
            else
            {
                xmlValue = dataContractSerializer.ReadObject(XmlDictionaryReader.CreateTextReader(memoryStream, quotas));
            }
            if (context != null)
            {
                context.AddNewObject(xmlValue);
            }
            return xmlValue;
        }