예제 #1
0
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine(@"CPUP Linker
==============
This is the CPUP Linker, it accepts files produced by the Assembler, it combines them into an output format of your choice.
It accepts just one or multiple .LIB files, it will link these into a single program. Only one of the input files can be a Program file as this will be used as the entry point.

It is recommended that you use CPUP-Build to build your program rather than calling the linker yourself. 


Format:
 CPUPA.exe [Switches] Input1 Input2 Input3...
 
Defaults:
 FileType: MIF
 Output File: ./out.mif

Switches:
 -of=VAL    | Sets the output file. do not use a space between the = and the file name. if your file name has spaces enclose it inside double quotes.
 -hex       | Outputs a .hex file (Intel Hexadecimal File)
 -bin       | Outputs a .bin file (Binary File)
 -mif       | Outputs a .mif file (Intel Memory Initialization File)
 -v         | Verbose Mode
 
");
                return(1);
            }

            //Program Settings
            string outputType = "mif"; //this will be set to the desired output type, defaulting to mif
            string outputFile = "out.mif";
            bool   verbose    = false;

            List <string> inputFileNames = new List <string>();

            foreach (string arg in args)
            {
                //Simple Switches
                if (arg.StartsWith("-") && !arg.Contains("="))
                {
                    switch (arg)
                    {
                    case "-hex":
                        outputType = "hex";
                        break;

                    case "-bin":
                        outputType = "bin";
                        break;

                    case "-mif":
                        outputType = "mif";
                        break;

                    case "-v":
                        verbose = true;
                        break;

                    default:
                        Console.WriteLine("ERROR: Unkown Switch: {0}", arg);
                        return(-1);
                    }
                }
                //OF Switch
                else if (arg.StartsWith("-of="))
                {
                    outputFile = arg.Substring(4);
                }
                //Input File Name
                else
                {
                    inputFileNames.Add(arg);
                }
            }

            //Check to make sure each file exists
            foreach (string fileName in inputFileNames)
            {
                if (!File.Exists(fileName))
                {
                    Console.WriteLine("ERROR: Input file does not exist: {0}", fileName);
                    return(-2);
                }
            }

            //Turn each input into a libray object
            Linker linker = new Linker(verbose);

            foreach (string fileName in inputFileNames)
            {
                Console.WriteLine("Importing {0}", fileName);
                FileStream             fs;
                XmlDictionaryReader    reader;
                DataContractSerializer ser;
                CPUPA.Library          lib;
                try
                {
                    fs     = new FileStream(fileName, FileMode.Open);
                    reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                    ser    = new DataContractSerializer(typeof(CPUPA.Library));
                    lib    = (CPUPA.Library)ser.ReadObject(reader, true);
                    reader.Close();
                    fs.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine("ERROR: Could not read input file {0}\n Error: {1}", fileName, e.Message);
                    return(-5);
                }

                linker.addLibrary(lib);
            }

            //Link
            linker.Link();

            //Output formatting
            byte[]         output;
            Format.IFormat formatter;
            switch (outputType)
            {
            case "mif":
                formatter = new Format.MIF();
                break;

            case "hex":
                formatter = new Format.HEX();
                break;

            case "bin":
                formatter = new Format.BIN();
                break;

            default:
                Console.WriteLine("ERROR: Invalid Format: {0}", outputType);
                return(-1);
            }
            output = formatter.getOutput(linker.getMachineCode());

            try
            {
                File.WriteAllBytes(outputFile, output);
            }catch (Exception e)
            {
                Console.WriteLine("ERROR: Could Not Write Output File {0}\n Error: {1}", outputFile, e.Message);
                return(-6);
            }
            return(0);
        }
        public static bool TryGetExceptionDetails(CommunicationException exception, out ServiceManagementError errorDetails, out HttpStatusCode httpStatusCode, out string operationId)
        {
            errorDetails   = null;
            httpStatusCode = 0;
            operationId    = null;

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

            if (exception.Message == "Internal Server Error")
            {
                httpStatusCode = HttpStatusCode.InternalServerError;
                return(true);
            }

            WebException wex = exception.InnerException as WebException;

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

            HttpWebResponse response = wex.Response as HttpWebResponse;

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

            httpStatusCode = response.StatusCode;
            if (httpStatusCode == HttpStatusCode.Forbidden)
            {
                return(true);
            }

            if (response.Headers != null)
            {
                operationId = response.Headers[Constants.OperationTrackingIdHeader];
            }

            using (var s = response.GetResponseStream())
            {
                if (s.Length == 0)
                {
                    return(false);
                }

                try
                {
                    using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(s, new XmlDictionaryReaderQuotas()))
                    {
                        DataContractSerializer ser = new DataContractSerializer(typeof(ServiceManagementError));
                        errorDetails = (ServiceManagementError)ser.ReadObject(reader, true);
                    }
                }
                catch (SerializationException)
                {
                    return(false);
                }
            }
            return(true);
        }
예제 #3
0
        /// <summary>
        /// Imports the specified profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        /// <param name="transportReportFileName">Name of the transport report file.</param>
        private void Import(TransportationProfile profile, string transportReportFileName)
        {
            int totalTreatedRecords    = 0;
            int totalImportFailures    = 0;
            int totalImportSuccess     = 0;
            int ReconnectionRetryCount = 5;

            try
            {
                TransportReport report = new TransportReport(transportReportFileName);
                //Get Transport Report
                if (File.Exists(transportReportFileName))
                {
                    report = ReadTransportReport(transportReportFileName);
                }

                MSCRMConnection connection = profile.getTargetConneciton();;
                _serviceProxy = cm.connect(connection);
                IOrganizationService service = (IOrganizationService)_serviceProxy;
                LogManager.WriteLog("Start importing data in " + connection.ConnectionName);

                //Mesure import time
                DateTime importStartDT = DateTime.Now;

                //Order import according to profile's import order
                IOrderedEnumerable <SelectedEntity> orderedSelectedEntities = profile.SelectedEntities.OrderBy(e => e.TransportOrder);

                foreach (SelectedEntity ee in orderedSelectedEntities)
                {
                    //Check if there are any records to import
                    if (ee.ExportedRecords == 0)
                    {
                        continue;
                    }

                    //Mesure import time
                    DateTime entityImportStartDT = DateTime.Now;

                    string   entityFolderPath = Folder + "\\" + profile.ProfileName + "\\Data\\" + ee.EntityName;
                    string[] filePaths        = Directory.GetFiles(entityFolderPath, "*.xml");

                    LogManager.WriteLog("Importing " + ee.EntityName + " records.");
                    int treatedRecordsForEntity  = 0;
                    int importedRecordsForEntity = 0;
                    int importFailuresForEntity  = 0;
                    foreach (string filePath in filePaths)
                    {
                        List <Type> knownTypes = new List <Type>();
                        knownTypes.Add(typeof(Entity));

                        XmlDictionaryReaderQuotas XRQ = new XmlDictionaryReaderQuotas();
                        XRQ.MaxStringContentLength = int.MaxValue;

                        using (FileStream fs = new FileStream(filePath, FileMode.Open))
                            using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, XRQ))
                            {
                                DataContractSerializer ser      = new DataContractSerializer(typeof(EntityCollection), knownTypes);
                                EntityCollection       fromDisk = (EntityCollection)ser.ReadObject(reader, true);

                                foreach (Entity e in fromDisk.Entities)
                                {
                                    //Records mapping for the Lookup attributes
                                    Entity entity = MapRecords(profile, e);

                                    string executingOperation = "";
                                    try
                                    {
                                        if (profile.ImportMode == 0)
                                        {
                                            executingOperation = "Create";
                                            service.Create(entity);
                                        }
                                        else if (profile.ImportMode == 1)
                                        {
                                            try
                                            {
                                                executingOperation = "Update";
                                                service.Update(entity);
                                            }
                                            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
                                            {
                                                executingOperation = "Create";
                                                service.Create(entity);
                                            }
                                        }
                                        else if (profile.ImportMode == 2)
                                        {
                                            executingOperation = "Update";
                                            service.Update(entity);
                                        }
                                        importedRecordsForEntity++;
                                        totalImportSuccess++;
                                    }
                                    catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                                    {
                                        totalImportFailures++;
                                        importFailuresForEntity++;
                                        ImportFailure failure = new ImportFailure
                                        {
                                            CreatedOn  = DateTime.Now.ToString(),
                                            EntityName = ee.EntityName,
                                            Operation  = executingOperation,
                                            Reason     = ex.Detail.Message,
                                            Url        = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + ee.EntityName + "&id=" + entity.Id.ToString()
                                        };
                                        report.TotalImportFailures += 1;
                                        //Insert the Failure line in the Failures Report
                                        WriteNewImportFailureLine(failure, importFailuresReportFileName);
                                    }
                                    catch (Exception ex)
                                    {
                                        //Check if the authentification session is expired
                                        if (ex.InnerException != null && ex.InnerException.Message.StartsWith("ID3242"))
                                        {
                                            LogManager.WriteLog("Error:The CRM authentication session expired. Reconnection attempt n° " + ReconnectionRetryCount);
                                            ReconnectionRetryCount--;
                                            //On 5 failed reconnections exit
                                            if (ReconnectionRetryCount == 0)
                                            {
                                                throw;
                                            }

                                            _serviceProxy = cm.connect(connection);
                                            service       = (IOrganizationService)_serviceProxy;
                                            LogManager.WriteLog("Error:The CRM authentication session expired.");
                                            totalImportFailures++;
                                            importFailuresForEntity++;
                                            ImportFailure failure = new ImportFailure
                                            {
                                                CreatedOn  = DateTime.Now.ToString(),
                                                EntityName = ee.EntityName,
                                                Operation  = executingOperation,
                                                Reason     = ex.InnerException.Message,
                                                Url        = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + ee.EntityName + "&id=" + entity.Id.ToString()
                                            };
                                            report.TotalImportFailures += 1;
                                            //Insert the Failure line in the Failures Report
                                            WriteNewImportFailureLine(failure, importFailuresReportFileName);
                                        }
                                        else
                                        {
                                            throw;
                                        }
                                    }
                                    totalTreatedRecords++;
                                    treatedRecordsForEntity++;
                                    updateTransportReport(report, ee, importedRecordsForEntity, importFailuresForEntity, entityImportStartDT);
                                }
                            }
                    }
                    LogManager.WriteLog("Treated " + treatedRecordsForEntity + " " + ee.EntityName + " records with " + importedRecordsForEntity + " successfully imported records and " + importFailuresForEntity + " failures.");
                }

                TimeSpan importTimeSpan = DateTime.Now - importStartDT;
                LogManager.WriteLog("Import finished for " + connection.ConnectionName + ". Treated " + totalTreatedRecords + " records in " + importTimeSpan.ToString().Substring(0, 10) + ". Successfuly imported " + totalImportSuccess + " records and " + totalImportFailures + " failures.");
                //WriteTransportReport(report, transportReportFileName);
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                LogManager.WriteLog("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    LogManager.WriteLog("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                }
                else
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                }
            }
        }
예제 #4
0
            internal Message SignBodyAndAddressingHeaders(Message requestMessage, ref string outboundXml)
            {
                XmlReader   reader = XmlReader.Create(new StringReader(requestMessage.ToString()));
                XmlDocument xdoc   = new XmlDocument();

                xdoc.Load(reader);
                XmlElement root = xdoc.DocumentElement;

                string soapNs          = xdoc.DocumentElement.NamespaceURI;
                XmlNamespaceManager nm = new XmlNamespaceManager(reader.NameTable);

                nm.AddNamespace("s", soapNs);
                nm.AddNamespace("a", "http://www.w3.org/2005/08/addressing");
                nm.AddNamespace("h", UserNamespace);

                // Create references
                List <string> references = new List <string>();

                // Get the body element and assign ID
                XmlElement bodyElement = (XmlElement)root.SelectSingleNode("//s:Body", nm);
                string     bodyId      = "body-" + Guid.NewGuid().ToString();

                bodyElement.SetAttribute("xml:id", bodyId);
                references.Add(bodyId);

                // Get the user element and assign ID
                XmlElement userElement = (XmlElement)root.SelectSingleNode("//s:Header/h:user", nm);
                string     userId      = "user-" + Guid.NewGuid().ToString();

                userElement.SetAttribute("xml:id", userId);
                references.Add(userId);


                // Get the timestamp element and assign ID
                XmlElement productElement = (XmlElement)root.SelectSingleNode("//s:Header/h:timestamp", nm);
                string     timestampId    = "timestamp-" + Guid.NewGuid().ToString();

                productElement.SetAttribute("xml:id", timestampId);
                references.Add(timestampId);

                if (references.Count > 0)
                {
                    // Create signature
                    XmlElement signatureElement = Sign(root, signingCertificate, references);

                    // Get the SOAP header element
                    XmlElement headerSignatureElement = (XmlElement)root.SelectSingleNode("//s:Header/h:signature", nm);

                    // Import and append the created signature
                    XmlNode signatureNode = xdoc.ImportNode(signatureElement, true);
                    headerSignatureElement.AppendChild(signatureNode);
                }



                // Get serialized text (Not necessary, just for the hell of it...)
                Stream       tempStream = new MemoryStream(Encoding.UTF8.GetBytes(root.OuterXml));
                StreamReader sr         = new StreamReader(tempStream);

                outboundXml = sr.ReadToEnd();
                bool isValid = VerifyXML(outboundXml);

                Stream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(root.OuterXml));

                //Chnaged to UTF-8 which works fine but HI Service ca not accept Funny UTF-8 Charaters like 'é'
                //// Get serialized text (Not necessary, just for the hell of it...)
                //Stream tempStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(root.OuterXml));
                //StreamReader sr = new StreamReader(tempStream);
                //outboundXml = sr.ReadToEnd();
                //bool isValid = VerifyXML(outboundXml);

                //Stream memoryStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(root.OuterXml));
                XmlDictionaryReader dictionaryReader = XmlDictionaryReader.CreateTextReader(memoryStream, new XmlDictionaryReaderQuotas());

                Message newMessage = Message.CreateMessage(dictionaryReader, int.MaxValue, requestMessage.Version);

                return(newMessage);
            }
예제 #5
0
 /// <summary>
 /// Called during deserialization to get the <see cref="XmlReader"/>.
 /// </summary>
 /// <param name="readStream">The <see cref="Stream"/> from which to read.</param>
 /// <param name="encoding">The <see cref="Encoding"/> used to read the stream.</param>
 /// <returns>The <see cref="XmlReader"/> used during deserialization.</returns>
 protected virtual XmlReader CreateXmlReader([NotNull] Stream readStream, [NotNull] Encoding encoding)
 {
     return(XmlDictionaryReader.CreateTextReader(readStream, encoding, _readerQuotas, onClose: null));
 }
 public virtual object ReadObject(Stream stream)
 {
     CheckNull(stream, "stream");
     return(ReadObject(XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max)));
 }
예제 #7
0
                protected override XmlDictionaryReader TakeXmlReader()
                {
                    ArraySegment <byte> buffer = this.Buffer;

                    return(XmlDictionaryReader.CreateTextReader(buffer.Array, buffer.Offset, buffer.Count, this.Quotas));
                }
        /// <summary>
        /// Reads the 'wresult' and returns the embedded security token.
        /// </summary>
        /// <returns>the 'SecurityToken'.</returns>
        /// <exception cref="WsFederationException">if exception occurs while reading security token.</exception>
        public virtual string GetToken()
        {
            if (Wresult == null)
            {
                LogHelper.LogWarning(FormatInvariant(LogMessages.IDX22000, nameof(Wresult)));
                return(null);
            }

            string token = null;

            using (var sr = new StringReader(Wresult))
            {
                XmlReader xmlReader = XmlReader.Create(sr);
                xmlReader.MoveToContent();

                // Read <RequestSecurityTokenResponseCollection> for wstrust 1.3 and 1.4
                if (XmlUtil.IsStartElement(xmlReader, WsTrustConstants.Elements.RequestSecurityTokenResponseCollection, WsTrustNamespaceNon2005List))
                {
                    xmlReader.ReadStartElement();
                }

                while (xmlReader.IsStartElement())
                {
                    // <RequestSecurityTokenResponse>
                    if (!XmlUtil.IsStartElement(xmlReader, WsTrustConstants.Elements.RequestSecurityTokenResponse, WsTrustNamespaceList))
                    {
                        xmlReader.Skip();
                        continue;
                    }

                    xmlReader.ReadStartElement();
                    while (xmlReader.IsStartElement())
                    {
                        if (!XmlUtil.IsStartElement(xmlReader, WsTrustConstants.Elements.RequestedSecurityToken, WsTrustNamespaceList))
                        {
                            xmlReader.Skip();
                            continue;
                        }

                        // Multiple tokens were found in the RequestSecurityTokenCollection. Only a single token is supported.
                        if (token != null)
                        {
                            throw LogExceptionMessage(new WsFederationException(LogMessages.IDX22903));
                        }

                        using (var ms = new MemoryStream())
                        {
                            using (var writer = XmlDictionaryWriter.CreateTextWriter(ms, Encoding.UTF8, false))
                            {
                                writer.WriteNode(xmlReader, true);
                                writer.Flush();
                            }

                            ms.Seek(0, SeekOrigin.Begin);
                            var memoryReader = XmlDictionaryReader.CreateTextReader(ms, Encoding.UTF8, XmlDictionaryReaderQuotas.Max, null);
                            var dom          = new XmlDocument()
                            {
                                PreserveWhitespace = true
                            };

                            dom.Load(memoryReader);
                            token = dom.DocumentElement.InnerXml;
                        }
                    }

                    // Read </RequestSecurityTokenResponse>
                    xmlReader.ReadEndElement();
                }
            }

            if (token == null)
            {
                throw LogExceptionMessage(new WsFederationException(LogMessages.IDX22902));
            }

            return(token);
        }
        private string MessageToString(ref Message message)
        {
            WebContentFormat    messageFormat = this.GetMessageContentFormat(message);
            MemoryStream        ms            = new MemoryStream();
            XmlDictionaryWriter writer        = null;

            switch (messageFormat)
            {
            case WebContentFormat.Default:
                // If we can't determine the message body format, we should ignore message body instead of creating the instance of writer object.
                break;

            case WebContentFormat.Xml:
                writer = XmlDictionaryWriter.CreateTextWriter(ms);
                break;

            case WebContentFormat.Json:
                writer = JsonReaderWriterFactory.CreateJsonWriter(ms);
                break;

            case WebContentFormat.Raw:
                // special case for raw, easier implemented separately
                return(this.ReadRawBody(ref message));
            }

            // Message body can't be determined, so writer object will be null.
            if (writer == null)
            {
                return(string.Empty);
            }

            message.WriteMessage(writer);
            writer.Flush();
            string messageBody = Encoding.UTF8.GetString(ms.ToArray());

            // Here would be a good place to change the message body, if so desired.

            // now that the message was read, it needs to be recreated.
            ms.Position = 0;

            // if the message body was modified, needs to reencode it, as show below
            // ms = new MemoryStream(Encoding.UTF8.GetBytes(messageBody));

            XmlDictionaryReader reader;

            if (messageFormat == WebContentFormat.Json)
            {
                reader = JsonReaderWriterFactory.CreateJsonReader(ms, XmlDictionaryReaderQuotas.Max);
            }
            else
            {
                reader = XmlDictionaryReader.CreateTextReader(ms, XmlDictionaryReaderQuotas.Max);
            }

            Message newMessage = Message.CreateMessage(reader, int.MaxValue, message.Version);

            newMessage.Properties.CopyProperties(message.Properties);
            message = newMessage;

            return(messageBody);
        }
        private string MessageToString(ref Message message, bool isRequest)
        {
            WebContentFormat    messageFormat = this.GetMessageContentFormat(message);
            MemoryStream        ms            = new MemoryStream();
            XmlDictionaryWriter writer        = null;

            switch (messageFormat)
            {
            case WebContentFormat.Default:
            case WebContentFormat.Xml:
                writer = XmlDictionaryWriter.CreateTextWriter(ms);
                break;

            case WebContentFormat.Json:
                writer = JsonReaderWriterFactory.CreateJsonWriter(ms);
                break;

            case WebContentFormat.Raw:
                return(CreateRawResponse(ref message));
            }

            message.WriteMessage(writer);
            writer.Flush();
            string messageBody = Encoding.UTF8.GetString(ms.ToArray());

            // Here would be a good place to change the message body, if so desired.

            // now that the message was read, it needs to be recreated.
            ms.Position = 0;

            // if the message body was modified, needs to reencode it, as show below
            // ms = new MemoryStream(Encoding.UTF8.GetBytes(messageBody));

            XmlDictionaryReader reader;
            XmlDictionaryReader xreader;

            //parse request - find field and its value
            if (messageFormat == WebContentFormat.Json)
            {
                xreader = JsonReaderWriterFactory.CreateJsonReader(ms, XmlDictionaryReaderQuotas.Max);
            }
            else
            {
                xreader = XmlDictionaryReader.CreateTextReader(ms, XmlDictionaryReaderQuotas.Max);
            }

            this.ParseRequest(xreader);
            ms.Position = 0;

            if (messageFormat == WebContentFormat.Json)
            {
                reader = JsonReaderWriterFactory.CreateJsonReader(ms, XmlDictionaryReaderQuotas.Max);
            }
            else
            {
                reader = XmlDictionaryReader.CreateTextReader(ms, XmlDictionaryReaderQuotas.Max);
            }

            Message newMessage = Message.CreateMessage(reader, int.MaxValue, message.Version);

            newMessage.Properties.CopyProperties(message.Properties);
            newMessage.Headers.CopyHeadersFrom(message.Headers);
            message = newMessage;

            return(messageBody);
        }
예제 #11
0
        public void Initialize()
        {
            playvideoostates = new PlayVideoState[2];
            // logintitlescreen = new LoginTitleScreen();

            DataContractSerializer resumeds     = new DataContractSerializer(typeof(ResumeVideoGame));
            FileStream             resumefs     = new FileStream("DefaultResumeGamePlay.xml", FileMode.Open);
            XmlDictionaryReader    resumereader =
                XmlDictionaryReader.CreateTextReader(resumefs, new XmlDictionaryReaderQuotas());

            resumevideogame = (ResumeVideoGame)resumeds.ReadObject(resumereader);

            /*  using (Stream s = File.OpenRead("LevelTwoTitleScreen.xml"))
             *    levelTwoOpeningTitleScreen = (OpeningTitleScreen)ds.ReadObject(s); */

            /*
             * DataContractSerializer ds = new DataContractSerializer(typeof(PlayVideoState));
             * FileStream fs = new FileStream("DefaultPlayVideoState.xml", FileMode.Open);
             * XmlDictionaryReader reader =
             *  XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
             * playvideostate = (PlayVideoState)ds.ReadObject(reader);
             */

            // playvideostate = new PlayVideoState();
            //  jobskills = new JobSkills();

            //LevelTwoTitleScreen

            /*
             *
             * DataContractSerializer ds = new DataContractSerializer(typeof(OpeningTitleScreen));
             * FileStream fs = new FileStream("LevelTwoTitleScreen.xml", FileMode.Open);
             * XmlDictionaryReader reader =
             *  XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
             * levelTwoOpeningTitleScreen = (OpeningTitleScreen)ds.ReadObject(reader);
             * currentScreen = levelTwoOpeningTitleScreen;
             *
             */

            //uncomment this for regular screen

            /*
             * DataContractSerializer ds = new DataContractSerializer(typeof(MainScreen));
             * FileStream fs = new FileStream("MainOpeningScreen.xml", FileMode.Open);
             * XmlDictionaryReader reader =
             *  XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
             * OpeningMainScreen = (MainScreen)ds.ReadObject(reader);
             * currentScreen = OpeningMainScreen;
             */

            // this is the special screen for wakanda con

            DataContractSerializer ds     = new DataContractSerializer(typeof(MainScreen));
            FileStream             fs     = new FileStream("WakandaConMainOpeningScreen.xml", FileMode.Open);
            XmlDictionaryReader    reader =
                XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());

            OpeningMainScreen = (MainScreen)ds.ReadObject(reader);
            currentScreen     = OpeningMainScreen;



            /*
             * DataContractSerializer ds = new DataContractSerializer(typeof(OpeningTitleScreen));
             * FileStream fs = new FileStream("WakandaTitleScreen.xml", FileMode.Open);
             * XmlDictionaryReader reader =
             *  XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
             * levelTwoOpeningTitleScreen = (OpeningTitleScreen)ds.ReadObject(reader);
             * //  fs.Close();
             * currentScreen = levelTwoOpeningTitleScreen;
             */
            //ScreenManager.Instance.AddScreen(ScreenManager.Instance.currentTitleScreen);



            // currentScreen = new LevelSelectScreen();

            /*
             * var writer = new FileStream("DefaultEndScreen.xml", FileMode.Create);
             * DataContractSerializer ser = new DataContractSerializer(typeof(JobSkills));
             * ser.WriteObject(writer, jobskills);
             * writer.Close();
             */
            // levelTwoOpeningTitleScreen = new OpeningTitleScreen();



            // currentScreen = levelTwoOpeningTitleScreen;

            /*
             * currentScreen = new OpeningTitleScreen();
             *
             */
        }
        public override void Update(GameTime gameTime)
        {
            gamepadstate = GamePad.GetState(PlayerIndex.One);

            levelOneButton.Update(gameTime);
            levelTwoButton.Update(gameTime);
            levelThreeButton.Update(gameTime);
            levelFourButton.Update(gameTime);
            levelFiveButton.Update(gameTime);

            /*
             * if (levelOneButton.masterButtonEffect == true || (gamepadstate.IsButtonDown(Buttons.A)) || (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.A)))
             * {
             *
             *  displayLoading = true;
             *  MediaPlayer.Stop();
             *  DataContractSerializer ds = new DataContractSerializer(typeof(OpeningTitleScreen));
             *  FileStream fs = new FileStream("StrongTitleScreen.xml", FileMode.Open);
             *  XmlDictionaryReader reader =
             *      XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
             *  ScreenManager.Instance.currentTitleScreen = (OpeningTitleScreen)ds.ReadObject(reader);
             *  fs.Close();
             *  ScreenManager.Instance.AddScreen(ScreenManager.Instance.currentTitleScreen);
             * }*/

            if (levelTwoButton.masterButtonEffect == true || (gamepadstate.IsButtonDown(Buttons.B)) || (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.B)))
            {
                // this is for the hands gaame. uncomment this for hands game effects

                /*
                 * displayLoading = true;
                 * MediaPlayer.Stop();
                 * DataContractSerializer ds = new DataContractSerializer(typeof(OpeningTitleScreen));
                 * FileStream fs = new FileStream("HandsTitleScreen.xml", FileMode.Open);
                 * XmlDictionaryReader reader =
                 *  XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                 * ScreenManager.Instance.currentTitleScreen = (OpeningTitleScreen)ds.ReadObject(reader);
                 * fs.Close();
                 * ScreenManager.Instance.AddScreen(ScreenManager.Instance.currentTitleScreen);
                 */

                //this is for the wakanda con version of the game

                displayLoading = true;
                MediaPlayer.Stop();
                DataContractSerializer ds     = new DataContractSerializer(typeof(OpeningTitleScreen));
                FileStream             fs     = new FileStream("WakandaTitleScreen.xml", FileMode.Open);
                XmlDictionaryReader    reader =
                    XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                ScreenManager.Instance.currentTitleScreen = (OpeningTitleScreen)ds.ReadObject(reader);
                fs.Close();
                ScreenManager.Instance.AddScreen(ScreenManager.Instance.currentTitleScreen);
            }

            /*
             * if (levelThreeButton.masterButtonEffect == true || (gamepadstate.IsButtonDown(Buttons.X)) || (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.X)))
             * {
             *  displayLoading = true;
             *  MediaPlayer.Stop();
             *  DataContractSerializer ds = new DataContractSerializer(typeof(OpeningTitleScreen));
             *  FileStream fs = new FileStream("RopeTitleScreen.xml", FileMode.Open);
             *  XmlDictionaryReader reader =
             *      XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
             *  ScreenManager.Instance.currentTitleScreen = (OpeningTitleScreen)ds.ReadObject(reader);
             *  fs.Close();
             *  ScreenManager.Instance.AddScreen(ScreenManager.Instance.currentTitleScreen);
             * }
             */
            /*
             * if (levelFourButton.masterButtonEffect == true || (gamepadstate.IsButtonDown(Buttons.Y)) || (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Y)))
             * {
             *  displayLoading = true;
             *  MediaPlayer.Stop();
             *  DataContractSerializer ds = new DataContractSerializer(typeof(OpeningTitleScreen));
             *  FileStream fs = new FileStream("LevelTwoTitleScreen.xml", FileMode.Open);
             *  XmlDictionaryReader reader =
             *      XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
             *  ScreenManager.Instance.currentTitleScreen = (OpeningTitleScreen)ds.ReadObject(reader);
             *  fs.Close();
             *  ScreenManager.Instance.AddScreen(ScreenManager.Instance.currentTitleScreen);
             * }
             *
             * if (levelFiveButton.masterButtonEffect == true || (gamepadstate.IsButtonDown(Buttons.Start)) || (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Enter)))
             * {
             *  displayLoading = true;
             *  MediaPlayer.Stop();
             *  DataContractSerializer ds = new DataContractSerializer(typeof(OpeningTitleScreen));
             *  FileStream fs = new FileStream("DeceptionLevelTwoTitleScreen.xml", FileMode.Open);
             *  XmlDictionaryReader reader =
             *      XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
             *  ScreenManager.Instance.currentTitleScreen = (OpeningTitleScreen)ds.ReadObject(reader);
             *  fs.Close();
             *  ScreenManager.Instance.AddScreen(ScreenManager.Instance.currentTitleScreen);
             * }
             */
        }
예제 #13
0
        static void Main(string[] args)
        {
            List <Tyontekija> henkilot = new List <Tyontekija>();
            Funktiot          funktio  = new Funktiot();


            // Yritetään lukea tiedosto, johon tallennettu ohjelman käsittelemät tiedot
            // Tiedoston path ongelma? Mikä olisi optimaalinen? Muutenkin tiedostoon tallentamisen varmuus täysi mysteeri.

            try
            {
                deser();
            }
            catch (Exception)
            {
                Console.WriteLine("");
            }


            // Päävalikko

            while (true)
            {
                Console.WriteLine("\nValitse toiminto:");
                Console.WriteLine("1 - Luo tai poista työntekijä");
                Console.WriteLine("2 - Kirjaa työmatkoja ja tarkastele työntekijöiden matkatietoja");
                Console.WriteLine("3 - Kertyneiden korvausten tarkastelu");
                Console.WriteLine("4 - Poistu ohjelmasta");
                string valinta = Console.ReadLine();
                Console.WriteLine("\n");

                if (valinta == "1")
                {
                    henkilot = funktio.LuoPoistaTyontekija(henkilot);
                    ser();                      // Huom. ser-funktio tallentaa (potentiaalisesti) muuttuneet tiedot tiedostoon.
                                                // Jos teet muutoksia ohjelman rakenteeseen pidä huoli, että ser-tulee kutsuttua uusien tietojen tallennusta varten.
                }
                else if (valinta == "2")
                {
                    TyontekijoidenKasittely();
                    ser();
                }
                else if (valinta == "3")
                {
                    funktio.KorvaustenTarkastelu(henkilot);
                }
                else if (valinta == "4")
                {
                    break;
                }
            }



            // Funktio - Lisätään matkoja työntekijälle ja tulostetaan työntekijäkohtaista tietoa

            void TyontekijoidenKasittely()
            {
                if (henkilot.Count == 0)
                {
                    return;
                }

                Tyontekija valittu_tyontekija = funktio.TyontekijanValinta(henkilot);   // Tässä vaiheessa valitaan funktion avulla työntekijä, johon toiminnot kohdistuvat

                while (true)
                {
                    Console.WriteLine("\nValittu työntekijä: " + valittu_tyontekija.getName());
                    Console.WriteLine("\nMitä haluat tehdä?");
                    Console.WriteLine("1 - Kirjaa uusi matka");
                    Console.WriteLine("2 - Kuittaa korvauksia maksetuiksi");
                    Console.WriteLine("3 - Katso maksamattomat ja maksetut korvaukset");
                    Console.WriteLine("4 - Työntekijän työmatkat");
                    Console.WriteLine("5 - Poista tallennettu työmatka");
                    Console.WriteLine("6 - Palaa alkuvalikkoon");
                    Console.WriteLine("7 - Valitse uusi työntekijä");

                    string vastaus = Console.ReadLine();
                    Console.WriteLine("\n");


                    if (vastaus == "1")
                    {
                        funktio.MatkanTallennus(valittu_tyontekija);
                    }

                    else if (vastaus == "2")
                    {
                        funktio.KuittaaMaksetuiksi(valittu_tyontekija);
                    }

                    else if (vastaus == "3")
                    {
                        Console.WriteLine("\nHenkilölle " + valittu_tyontekija.getName() + " maksamattomat korvaukset: " + valittu_tyontekija.Maksamattomat);
                        Console.WriteLine("Henkilölle " + valittu_tyontekija.getName() + " maksetut korvaukset: " + valittu_tyontekija.Maksetut);
                    }

                    else if (vastaus == "4")
                    {
                        if (valittu_tyontekija.getMatkat().Count > 0)
                        {
                            var matkalista = valittu_tyontekija.getMatkat();    // Haetaan valitun työntekijän Matkat-listaan tallennetut Matka-objektit.
                            Console.WriteLine("Työmatkojen tiedot: ");
                            foreach (Matka x in matkalista)
                            {
                                Console.WriteLine(x.Tiedot());                  // Tulostetaan tallennettujen matkojen tiedot Matka-luokasta löytyvän Tiedot-metodin avulla.
                            }
                        }
                        else
                        {
                            Console.WriteLine("Henkilöllä ei ole tallennettuja matkoja");
                        }
                    }

                    else if (vastaus == "5")
                    {
                        funktio.PoistaMatka(valittu_tyontekija);
                    }

                    else if (vastaus == "6")
                    {
                        return;
                    }

                    else if (vastaus == "7")
                    {
                        valittu_tyontekija = funktio.TyontekijanValinta(henkilot);
                        continue;
                    }
                }
            }

            // Funktio - Kirjoitetaan henkilot-listan kaikki sisältö xml-tiedostoon. Täyttä voodoota, toimii lähinnä tuurilla.

            void ser()
            {
                // Alustaa tiedoston, muutoin voi tulla ongelmia esim. jos yritetään tallentaa tyhjää listaa työntekijätietojen poistamisen jälkeen.
                try
                {
                    FileStream fileStream = File.Open(Environment.CurrentDirectory + "\\mytext.xml", FileMode.Open);
                    fileStream.SetLength(0);
                    fileStream.Close();
                }
                catch (Exception)
                {
                    Console.WriteLine("");
                }


                Stream stream = File.OpenWrite(Environment.CurrentDirectory + "\\mytext.xml");
                DataContractSerializer DataSer = new DataContractSerializer(typeof(List <Tyontekija>));

                DataSer.WriteObject(stream, henkilot);
                stream.Close();
            }

            // Funktio - Puretaan xml-tiedoston sisältö, muunnetaan luettavaan muotoon ja luodaan henkilot-lista sen pohjalta.

            void deser()
            {
                Stream stream = File.OpenRead(Environment.CurrentDirectory + "\\mytext.xml");

                XmlDictionaryReader    reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
                DataContractSerializer seri   = new DataContractSerializer(typeof(List <Tyontekija>));

                henkilot = (List <Tyontekija>)seri.ReadObject(reader, true);

                reader.Close();
                stream.Close();
            }
        }
예제 #14
0
                /// <summary>
                /// Parsing response stream and fetch response mesage from it
                /// </summary>
                private void ParsingResponseThreadProc()
                {
                    try
                    {
                        using (WebResponse response = this.request.GetResponse())
                            using (Stream responseStream = response.GetResponseStream())
                                using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(responseStream, DefaultReaderQuotas))
                                {
                                    reader.ReadStartElement();

                                    // this.disposeFlag is marked volatile so that the compiler
                                    // won't cache the value here
                                    while (!this.disposeFlag)
                                    {
                                        // In case of network failure and hang,
                                        // this call should eventually timed out
                                        Message m = ReadMessage(reader);
                                        if (m == null)
                                        {
                                            return;
                                        }

                                        if (m.Headers.Action.Equals(BrokerInstanceUnavailable.Action, StringComparison.InvariantCultureIgnoreCase))
                                        {
                                            TypedMessageConverter     converter = TypedMessageConverter.Create(typeof(BrokerInstanceUnavailable), BrokerInstanceUnavailable.Action);
                                            BrokerInstanceUnavailable biu       = (BrokerInstanceUnavailable)converter.FromMessage(m);
                                            SessionBase.TraceSource.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "[WebResponseHandler] Received broker unavailable message, BrokerLauncherEpr = {0}, BrokerNodeDown= {1}", biu.BrokerLauncherEpr, biu.IsBrokerNodeDown);
                                            this.callback.SendBrokerDownSignal(biu.IsBrokerNodeDown);
                                            break;
                                        }
                                        else
                                        {
                                            SessionBase.TraceSource.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0, "[WebResponseHandler] Received response message:  MessageId = {0}, Action = {1}", m.Headers.MessageId, m.Headers.Action);
                                            this.callback.SendResponse(m);
                                        }
                                    }
                                }
                    }
                    catch (Exception e)
                    {
                        SessionBase.TraceSource.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "[WebBrokerFrontendForGetResponse] Failed to read response from the response stream: {0}", e);
                        if (this.disposeFlag)
                        {
                            // If it has already been disposed, do not
                            // pass the exception to the enumerator
                            return;
                        }

                        Exception    exceptionToThrow = e;
                        WebException we = e as WebException;
                        if (we != null)
                        {
                            exceptionToThrow = WebAPIUtility.ConvertWebException(we);
                            FaultException <SessionFault> faultException = exceptionToThrow as FaultException <SessionFault>;
                            if (faultException != null)
                            {
                                exceptionToThrow = Utility.TranslateFaultException(faultException);
                            }
                        }

                        //Bug #15946: throw exception instead of signaling broker down.
                        //Note: To pass the exception to AsyncResponseCallback, wrap it as a response message with special action field.
                        Message exceptionMessage = Message.CreateMessage(MessageVersion.Default, Constant.WebAPI_ClientSideException);
                        exceptionMessage.Headers.Add(MessageHeader.CreateHeader(Constant.ResponseCallbackIdHeaderName, Constant.ResponseCallbackIdHeaderNS, clientData));
                        exceptionMessage.Properties.Add(Constant.WebAPI_ClientSideException, exceptionToThrow);

                        this.callback.SendResponse(exceptionMessage);
                    }
                    finally
                    {
                        // Two threads are involved here:
                        // first thread: it is disposing BrokerClient, and now it is at WebBrokerFrontendForGetResponse.Dispose
                        // second thread: it is "ParsingResponseThreadProc" worker thread

                        // The first thread holds a lock "lockObjectToProtectHandlers" and calls WebResponseHandler.Dispose method,
                        // which attempts to abort second thread. But the second thread is in finally block here, it indefinitely
                        // delays the abort. So the first thread is blocked at "this.parsingResponseThread.Abort()".

                        // The second thread calls following "this.Completed" method, which waits for the same lock "lockObjectToProtectHandlers".
                        // So the second thread is blocked on that lock.

                        // In order to avoid deadlock, change the first thread. It should not hold a lock when aborts the second thread.

                        if (this.Completed != null)
                        {
                            this.Completed(this, EventArgs.Empty);
                        }
                    }
                }
예제 #15
0
        public virtual object?ReadObject(Stream stream)
        {
            ArgumentNullException.ThrowIfNull(stream);

            return(ReadObject(XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max)));
        }
예제 #16
0
        /// <summary>
        /// Called after an inbound message has been received but before the message is dispatched to the intended operation.
        /// </summary>
        /// <param name="request">The request message.</param>
        /// <param name="channel">The incoming channel.</param>
        /// <param name="instanceContext">The current service instance.</param>
        /// <returns>The object used to correlate state. This object is passed back in the <see cref="M:System.ServiceModel.Dispatcher.IDispatchMessageInspector.BeforeSendReply(System.ServiceModel.Channels.Message@,System.Object)" /> method.</returns>
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            if (!request.Properties.ContainsKey("Via"))
            {
                return(request);                                        // Nothing much we can do here
            }
            if (!request.Properties.ContainsKey("httpRequest"))
            {
                return(request);                                                // Same here
            }
            var httpRequest = request.Properties["httpRequest"] as HttpRequestMessageProperty;

            if (httpRequest == null)
            {
                return(request);
            }
            var httpMethod = httpRequest.Method.ToUpper();

            var uri = request.Properties["Via"] as Uri;

            if (uri == null)
            {
                return(request);             // Still nothing much we can do
            }
            var url         = uri.AbsoluteUri;
            var urlFragment = url;

            if (urlFragment.ToLower().StartsWith(_rootUrlLower))
            {
                urlFragment = urlFragment.Substring(_rootUrlLower.Length);
            }
            var operationInfo = RestHelper.GetMethodNameFromUrlFragmentAndContract(urlFragment, httpMethod, _contractType);
            var urlParameters = RestHelper.GetUrlParametersFromUrlFragmentAndContract(urlFragment, httpMethod, _contractType);

            if (httpMethod == "GET")
            {
                // TODO: Support GET if at all possible
                throw new Exception("REST-GET operations are not currently supported in the chosen hosting environment. Please use a different HTTP Verb, or host in a different environment (such as WebApi). We hope to add this feature in a future version.");

                // This is a REST GET operation. Therefore, there is no posted message. Instead, we have to decode the input parameters from the URL
                var parameters = operationInfo.GetParameters();
                if (parameters.Length != 1)
                {
                    throw new NotSupportedException("Only service methods/operations with a single input parameter can be mapped to REST-GET operations. Method " + operationInfo.Name + " has " + parameters.Length + " parameters. Consider changing the method to have a single object with multiple properties instead.");
                }
                var parameterType     = parameters[0].ParameterType;
                var parameterInstance = Activator.CreateInstance(parameterType);
                foreach (var propertyName in urlParameters.Keys)
                {
                    var urlProperty = parameterType.GetProperty(propertyName);
                    if (urlProperty == null)
                    {
                        continue;
                    }
                    urlProperty.SetValue(parameterInstance, urlParameters[propertyName], null);
                }

                // Seralize the object back into a new request message
                // TODO: We only need to do this for methods OTHER than GET
                var format = GetMessageContentFormat(request);
                switch (format)
                {
                case WebContentFormat.Xml:
                    var xmlStream     = new MemoryStream();
                    var xmlSerializer = new DataContractSerializer(parameterInstance.GetType());
                    xmlSerializer.WriteObject(xmlStream, parameterInstance);
                    var xmlReader     = XmlDictionaryReader.CreateTextReader(StreamHelper.ToArray(xmlStream), XmlDictionaryReaderQuotas.Max);
                    var newXmlMessage = Message.CreateMessage(xmlReader, int.MaxValue, request.Version);
                    newXmlMessage.Properties.CopyProperties(request.Properties);
                    newXmlMessage.Headers.CopyHeadersFrom(request.Headers);
                    if (format == WebContentFormat.Default)
                    {
                        if (newXmlMessage.Properties.ContainsKey(WebBodyFormatMessageProperty.Name))
                        {
                            newXmlMessage.Properties.Remove(WebBodyFormatMessageProperty.Name);
                        }
                        newXmlMessage.Properties.Add(WebBodyFormatMessageProperty.Name, WebContentFormat.Xml);
                    }
                    request = newXmlMessage;
                    break;

                case WebContentFormat.Default:
                case WebContentFormat.Json:
                    var jsonStream = new MemoryStream();
                    var serializer = new DataContractJsonSerializer(parameterInstance.GetType());
                    serializer.WriteObject(jsonStream, parameterInstance);
                    var jsonReader = JsonReaderWriterFactory.CreateJsonReader(StreamHelper.ToArray(jsonStream), XmlDictionaryReaderQuotas.Max);
                    var newMessage = Message.CreateMessage(jsonReader, int.MaxValue, request.Version);
                    newMessage.Properties.CopyProperties(request.Properties);
                    newMessage.Headers.CopyHeadersFrom(request.Headers);
                    if (format == WebContentFormat.Default)
                    {
                        if (newMessage.Properties.ContainsKey(WebBodyFormatMessageProperty.Name))
                        {
                            newMessage.Properties.Remove(WebBodyFormatMessageProperty.Name);
                        }
                        newMessage.Properties.Add(WebBodyFormatMessageProperty.Name, WebContentFormat.Json);
                    }
                    request = newMessage;
                    break;

                default:
                    throw new NotSupportedException("Mesage format " + format.ToString() + " is not supported form REST/JSON operations");
                }
            }

            return(null);
        }
예제 #17
0
 public XmlDictionaryReader CreateDictionaryReader()
 {
     return(XmlDictionaryReader.CreateTextReader(_buffer, XmlDictionaryReaderQuotas.Max));
 }
예제 #18
0
        static void Main(string[] args)
        {
            string catalogName = "thecatalog";
            string openingOption;
            int    choice;
            bool   keepGoing = true;
            string stringChoice;
            string bookTitle;
            string bookAuthor;
            string bookSubject;


            //  Book[] allBooks;

            CardCatalog MainCatalog = new CardCatalog();

            List <Book> BookList = new List <Book>();


            Console.WriteLine("Do you want to open a catalog or do you want to create a new one? (type 'new' or 'open')");
            openingOption = Console.ReadLine();

            if (openingOption == "new")
            {
                Console.WriteLine("Type the name of the Book Catalog:");
                catalogName = Console.ReadLine();


                // Program theProgram = new Program();
                //  theProgram.happyness = "Singing";
            }

            if (openingOption == "open")
            {
                Console.WriteLine("Enter the catalog name correctly: ");
                catalogName = Console.ReadLine();

                DataContractSerializer ds     = new DataContractSerializer(typeof(CardCatalog));
                FileStream             fs     = new FileStream(catalogName + ".xml", FileMode.Open);
                XmlDictionaryReader    reader =
                    XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                MainCatalog = (CardCatalog)ds.ReadObject(reader);
                reader.Close();



                //  currentScreen = OpeningMainScreen;
            }

            do
            {
                Console.WriteLine("1. List All Books");
                Console.WriteLine("2. Add A Book");
                Console.WriteLine("3. Save and Exit");

                Console.WriteLine("Choose One of these by pressing the number and enter:");
                stringChoice = Console.ReadLine();
                choice       = Convert.ToInt32(stringChoice);


                if (choice == 1)
                {
                    BookList = MainCatalog.BookListHolder;
                    int i = 1;
                    foreach (Book loopVar in BookList)
                    {
                        Console.WriteLine("Book {0}", i);
                        i++;
                        Console.WriteLine("Book Title: {0}", loopVar.title);
                        Console.WriteLine("Book Subject: {0}", loopVar.subject);
                        Console.WriteLine("Book Author: {0}", loopVar.author);
                    }
                }
                else if (choice == 2)
                {
                    Console.WriteLine("What is the book title?");
                    bookTitle = Console.ReadLine();

                    Console.WriteLine("Who is the author of the book?");
                    bookAuthor = Console.ReadLine();

                    Console.WriteLine("What is the subject of the book?");
                    bookSubject = Console.ReadLine();

                    BookList.Add(new Book()
                    {
                        title = bookTitle, author = bookAuthor, subject = bookSubject
                    });
                }
                else if (choice == 3)
                {
                    MainCatalog.BookListHolder = BookList;
                    MainCatalog.filename       = catalogName;

                    var writer = new FileStream(catalogName + ".xml", FileMode.Create);
                    DataContractSerializer ser = new DataContractSerializer(typeof(CardCatalog));
                    ser.WriteObject(writer, MainCatalog);
                    writer.Close();
                    keepGoing = false;
                }
            } while (keepGoing == true);

            //Program theProgram = new Program();
            //theProgram.happyness = "Singing";
            //var writer = new FileStream(theProgram.happyness + ".xml", FileMode.Create);
            //DataContractSerializer ser = new DataContractSerializer(typeof(Program));
            //ser.WriteObject(writer, theProgram);
            //writer.Close();
        }
예제 #19
0
 private XmlReader TakeStreamedReader(Stream stream, Encoding enc)
 {
     return(XmlDictionaryReader.CreateTextReader(stream, _readerQuotas));
 }
예제 #20
0
        /// <summary>
        /// Deserializing employees from xml file, select necessary, order them and serializing to new file
        /// </summary>
        /// <param name="fileName"></param>
        public static void Deserialize(string fileName)
        {
            const string _selectedObjectsDoc = "SelectedObjects.xml";

            Console.WriteLine("Deserializing objects...");
            FileStream             fs     = new FileStream(fileName, FileMode.Open);
            XmlDictionaryReader    reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
            DataContractSerializer ser    = new DataContractSerializer(typeof(List <Employee>), "Employees", String.Empty);

            List <Employee> employees = (List <Employee>)ser.ReadObject(reader, true);

            Console.WriteLine("All employees:");
            foreach (Employee emp in employees)
            {
                Type field = emp.GetType();

                //get value of private member EmployeeId
                string id = (string)field.InvokeMember("EmployeeId", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic, null, emp, null);

                //get info about public Address property and get it`s value
                PropertyInfo info    = field.GetProperty("Address");
                string       address = (string)info.GetValue(emp, null);

                Console.WriteLine(" Last name: {0} \n First name: {1} \n Age: {2} \n Department: {3} \n Address: {4} \n ID: {5}\n", emp.LastName, emp.FirstName, emp.Age, emp.Department, address, id);
            }

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

            var result = from temp in employees where temp.Age >= 25 && temp.Age <= 35 orderby temp.GetType().InvokeMember("EmployeeId", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic, null, temp, null) select temp;

            Console.WriteLine("Select employees from 25 years to 35 and sort them by ID...\nSelected employees are:\n");
            foreach (Employee emp in result)
            {
                Type field = emp.GetType();

                //get value of private member EmployeeId
                string id = (string)field.InvokeMember("EmployeeId", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic, null, emp, null);

                //get info about public Address property and get it`s value
                PropertyInfo info    = field.GetProperty("Address");
                string       address = (string)info.GetValue(emp, null);

                Console.WriteLine(" Last name: {0} \n First name: {1} \n Age: {2} \n Department: {3} \n Address: {4} \n ID: {5}\n", emp.LastName, emp.FirstName, emp.Age, emp.Department, address, id);
            }

            #region Serealize ordered and necessary employees to new file
            Console.WriteLine("Serializing selected objects...");
            try
            {
                FileStream             stream   = new FileStream(_selectedObjectsDoc, FileMode.Create);
                DataContractSerializer finalSer = new DataContractSerializer(typeof(List <Employee>), "Employees", String.Empty, new[] { result.GetType() });
                finalSer.WriteObject(stream, result.ToList());
                stream.Close();
            }
            catch (SerializationException serEx)
            {
                Console.WriteLine("Serialization Failed");
                Console.WriteLine(serEx.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("The serialization failed: {0} StackTrace is: {1}", ex.Message, ex.StackTrace);
            }

            Console.WriteLine("Your objects successfully serialized!\n");
            #endregion
        }
예제 #21
0
        protected override void GetHeadersFromMessage(Message message, MessageDescription messageDescription, object[] parameters, bool isRequest)
        {
            try
            {
                XmlSerializer serializer;
                MessageHeaderDescriptionTable headerDescriptionTable;
                MessageHeaderDescription      unknownHeaderDescription;
                if (isRequest)
                {
                    serializer               = _requestMessageInfo.HeaderSerializer;
                    headerDescriptionTable   = _requestMessageInfo.HeaderDescriptionTable;
                    unknownHeaderDescription = _requestMessageInfo.UnknownHeaderDescription;
                }
                else
                {
                    serializer               = _replyMessageInfo.HeaderSerializer;
                    headerDescriptionTable   = _replyMessageInfo.HeaderDescriptionTable;
                    unknownHeaderDescription = _replyMessageInfo.UnknownHeaderDescription;
                }
                MessageHeaders headers        = message.Headers;
                ArrayList      unknownHeaders = null;
                XmlDocument    xmlDoc         = null;
                if (unknownHeaderDescription != null)
                {
                    unknownHeaders = new ArrayList();
                    xmlDoc         = new XmlDocument();
                }
                if (serializer == null)
                {
                    if (unknownHeaderDescription != null)
                    {
                        for (int headerIndex = 0; headerIndex < headers.Count; headerIndex++)
                        {
                            AddUnknownHeader(unknownHeaderDescription, unknownHeaders, xmlDoc, null /*bufferWriter*/, headers[headerIndex], headers.GetReaderAtHeader(headerIndex));
                        }

                        parameters[unknownHeaderDescription.Index] = unknownHeaders.ToArray(unknownHeaderDescription.TypedHeader ? typeof(MessageHeader <XmlElement>) : typeof(XmlElement));
                    }
                    return;
                }


                MemoryStream        memoryStream = new MemoryStream();
                XmlDictionaryWriter bufferWriter = XmlDictionaryWriter.CreateTextWriter(memoryStream);
                message.WriteStartEnvelope(bufferWriter);
                message.WriteStartHeaders(bufferWriter);
                MessageHeaderOfTHelper messageHeaderOfTHelper = null;
                for (int headerIndex = 0; headerIndex < headers.Count; headerIndex++)
                {
                    MessageHeaderInfo        header       = headers[headerIndex];
                    XmlDictionaryReader      headerReader = headers.GetReaderAtHeader(headerIndex);
                    MessageHeaderDescription matchingHeaderDescription = headerDescriptionTable.Get(header.Name, header.Namespace);
                    if (matchingHeaderDescription != null)
                    {
                        if (header.MustUnderstand)
                        {
                            headers.UnderstoodHeaders.Add(header);
                        }

                        if (matchingHeaderDescription.TypedHeader)
                        {
                            if (messageHeaderOfTHelper == null)
                            {
                                messageHeaderOfTHelper = new MessageHeaderOfTHelper(parameters.Length);
                            }

                            messageHeaderOfTHelper.SetHeaderAttributes(matchingHeaderDescription, header.MustUnderstand, header.Relay, header.Actor);
                        }
                    }
                    if (matchingHeaderDescription == null && unknownHeaderDescription != null)
                    {
                        AddUnknownHeader(unknownHeaderDescription, unknownHeaders, xmlDoc, bufferWriter, header, headerReader);
                    }
                    else
                    {
                        bufferWriter.WriteNode(headerReader, false);
                    }

                    headerReader.Dispose();
                }
                bufferWriter.WriteEndElement();
                bufferWriter.WriteEndElement();
                bufferWriter.Flush();

                /*
                 * XmlDocument doc = new XmlDocument();
                 * memoryStream.Position = 0;
                 * doc.Load(memoryStream);
                 * doc.Save(Console.Out);
                 */

                memoryStream.Position = 0;
                ArraySegment <byte> memoryBuffer;
                memoryStream.TryGetBuffer(out memoryBuffer);
                XmlDictionaryReader bufferReader = XmlDictionaryReader.CreateTextReader(memoryBuffer.Array, 0, (int)memoryStream.Length, XmlDictionaryReaderQuotas.Max);

                bufferReader.ReadStartElement();
                bufferReader.MoveToContent();
                if (!bufferReader.IsEmptyElement)
                {
                    bufferReader.ReadStartElement();
                    object[] headerValues = (object[])serializer.Deserialize(bufferReader, _isEncoded ? GetEncoding(message.Version.Envelope) : null);
                    int      headerIndex  = 0;
                    foreach (MessageHeaderDescription headerDescription in messageDescription.Headers)
                    {
                        if (!headerDescription.IsUnknownHeaderCollection)
                        {
                            object parameterValue = headerValues[headerIndex++];
                            if (headerDescription.TypedHeader && parameterValue != null)
                            {
                                parameterValue = messageHeaderOfTHelper.CreateMessageHeader(headerDescription, parameterValue);
                            }

                            parameters[headerDescription.Index] = parameterValue;
                        }
                    }
                    bufferReader.Dispose();
                }
                if (unknownHeaderDescription != null)
                {
                    parameters[unknownHeaderDescription.Index] = unknownHeaders.ToArray(unknownHeaderDescription.TypedHeader ? typeof(MessageHeader <XmlElement>) : typeof(XmlElement));
                }
            }
            catch (InvalidOperationException e)
            {
                // all exceptions from XmlSerializer get wrapped in InvalidOperationException,
                // so we must be conservative and never turn this into a fault
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
                                                                              SR.Format(SR.SFxErrorDeserializingHeader, messageDescription.MessageName), e));
            }
        }
예제 #22
0
        //Reading from file

        public void readFromFile()
        {
            //Console.WriteLine("Deserializing an instance of the object.");
            FileStream fs;

            try
            {
                fs = new FileStream("D:\\Tweets.xml", FileMode.Open);
                //FileStream fs1 = new FileStream("object.json", FileMode.Open);

                XmlDictionaryReader reader =
                    XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());

                //JsonReaderWriterFactory reader1 =
                //    JsonReaderWriterFactory.CreateJsonReader(fs1, new XmlDictionaryReaderQuotas());
                List <Tweet>           myList = new List <Tweet>();
                DataContractSerializer ser    = new DataContractSerializer(typeof(List <Tweet>));
                //DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<Tweet>));

                // Deserialize the data and read it from the instance.

                List <Tweet> deserializedTweet =
                    (List <Tweet>)ser.ReadObject(reader);
                //hashTweet.Add(deserializedTweet.tweetId, deserializedTweet);
                //IEnumerator ie = deserializedTweet.GetEnumerator();
                Tweet[] tweets = deserializedTweet.ToArray();
                for (int i = 0; i < tweets.Length; i++)
                {
                    //Tweet tweet = (Tweet)ie;
                    Tweet newTweet = new Tweet(tweets[i].tweetId, tweets[i].tweetName, tweets[i].noOfMessages, tweets[i].userId, tweets[i].isOffensive);
                    if (tweets[i].tweetName == "")
                    {
                        hashTweet.Add(0, newTweet);
                        continue;
                    }
                    hashTweet.Add(tweets[i].tweetId, newTweet);
                }

                reader.Close();
                fs.Close();
            }
            catch (FileNotFoundException)
            {
                fs = new FileStream("D:\\Tweets.xml", FileMode.Create);
                Tweet        newObject = new Tweet(0, "", 0, "", false);
                List <Tweet> myList    = new List <Tweet>();
                myList.Add(newObject);
                DataContractSerializer ser =
                    new DataContractSerializer(typeof(List <Tweet>));
                DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List <Tweet>));
                ser.WriteObject(fs, myList);
                hashTweet.Add(0, newObject);
                fs.Close();
            }
            FileStream fs_msg;

            try
            {
                // To read Messages
                fs_msg = new FileStream("D:\\Message.xml", FileMode.Open);
                if (fs_msg.Length != 0)
                {
                    XmlDictionaryReader reader_msg =
                        XmlDictionaryReader.CreateTextReader(fs_msg, new XmlDictionaryReaderQuotas());

                    DataContractSerializer ser_msg = new DataContractSerializer(typeof(List <Message>));
                    //DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<Tweet>));
                    //List<Message>
                    List <Message> deserializedMessage =
                        (List <Message>)ser_msg.ReadObject(reader_msg);

                    Message[] message = deserializedMessage.ToArray();
                    for (int i = 0; i < message.Length; i++)
                    {
                        Message msg   = new Message(message[i].tweetId, message[i].messageId, message[i].message, message[i].userId, message[i].isReply, message[i].replyTo, message[i].likes, message[i].isOffensive);
                        Tweet   tweet = (Tweet)hashTweet[message[i].tweetId];
                        if (message[i].userId == "")
                        {
                            tweet.message.Add(0, msg);
                            continue;
                        }
                        string[] users = message[i].userList.ToArray();
                        for (int j = 0; j < users.Length; j++)
                        {
                            msg.userList.Add(users[j]);
                        }
                        tweet.message.Add(message[i].messageId, msg);
                    }
                    //FileStream fs1 = new FileStream("object.json", FileMode.Open);
                    fs_msg.Close();
                    reader_msg.Close();
                }
            }
            catch (FileNotFoundException)
            {
                fs_msg = new FileStream("D:\\Message.xml", FileMode.Create);
                fs_msg.Close();
            }
            FileStream fs_user;

            try
            {
                fs_user = new FileStream("D:\\Users.xml", FileMode.Open);
                if (fs_user.Length != 0)
                {
                    XmlDictionaryReader reader_user =
                        XmlDictionaryReader.CreateTextReader(fs_user, new XmlDictionaryReaderQuotas());
                    DataContractSerializer ser_user          = new DataContractSerializer(typeof(List <UserDetais>));
                    List <UserDetais>      deserializedUsers =
                        (List <UserDetais>)ser_user.ReadObject(reader_user);
                    UserDetais[] user = deserializedUsers.ToArray();
                    for (int i = 0; i < user.Length; i++)
                    {
                        UserDetais userObject = new UserDetais(user[i].userId, user[i].tweetCount, user[i].msgCount, user[i].likeCount, user[i].points);
                        hashUserDetails.Add(user[i].userId, userObject);
                    }
                }
                fs_user.Flush();
                fs_user.Close();
            }
            catch (FileNotFoundException)
            {
                fs_user = new FileStream("D:\\Users.xml", FileMode.Create);
                fs_user.Close();
            }
            //Tweet des = (Tweet)ser1.ReadObject(fs1);
            //Console.WriteLine(String.Format("{0} {1} {2} {3} {4}",
            //deserializedPerson.tweetId, deserializedPerson.tweetName,
            //deserializedPerson.noOfMessages, deserializedPerson.isOffensive, deserializedPerson.userId));
            //Console.WriteLine(String.Format("{0} {1}, ID: {2}", des.FirstName, des.LastName, des.ID));
        }
예제 #23
0
 /// <summary>
 /// Called during deserialization to get the <see cref="XmlReader"/>.
 /// </summary>
 /// <param name="readStream">The <see cref="Stream"/> from which to read.</param>
 /// <returns>The <see cref="XmlReader"/> used during deserialization.</returns>
 protected virtual XmlReader CreateXmlReader([NotNull] Stream readStream)
 {
     return(XmlDictionaryReader.CreateTextReader(
                readStream, _readerQuotas));
 }
예제 #24
0
        protected override void Seed(VocabularyModel _ctx)
        {
            string path = Path.GetTempPath();

            #region
            //CredentialExtn cred1 = new CredentialExtn
            //{
            //    Email = "*****@*****.**",
            //    Password = "******"
            //};
            //DictionaryExtn dict1 = new DictionaryExtn
            //{
            //    Name = "Animal",
            //    Credential = cred1
            //};
            //Word[] words = new Word[]
            //{
            //    new Word
            //    {
            //        WordEng = "cat",
            //        Transcription = "|kæt|",
            //        Translation = "кіт",
            //        Dictionary = dict1,
            //        Image = File.ReadAllBytes($@"{path}\Image\cat.jpg"),
            //        Sound = File.ReadAllBytes($@"{path}\Sound\cat.mp3"),
            //        IsLearnedWord = false,
            //    },
            //    new Word
            //    {
            //        WordEng = "dog",
            //        Transcription = "|dɔːɡ|",
            //        Translation = "пес",
            //        Dictionary = dict1,
            //        Image = File.ReadAllBytes($@"{path}\Image\dog.jpg"),
            //        Sound = File.ReadAllBytes($@"{path}\Sound\dog.mp3"),
            //        IsLearnedWord = false,
            //    },
            //    new Word
            //    {
            //        WordEng = "bear",
            //        Transcription = "|ber|",
            //        Translation = "ведмідь",
            //        Dictionary = dict1,
            //        Image = File.ReadAllBytes($@"{path}\Image\bear.jpeg"),
            //        Sound = File.ReadAllBytes($@"{path}\Sound\bear.mp3"),
            //        IsLearnedWord = false,
            //    },
            //    new Word
            //    {
            //        WordEng = "penguin",
            //        Transcription = "|ˈpeŋɡwɪn|",
            //        Translation = "пінгвін",
            //        Dictionary = dict1,
            //        Image = File.ReadAllBytes($@"{path}\Image\penguin.png"),
            //        Sound = File.ReadAllBytes($@"{path}\Sound\penguin.mp3"),
            //        IsLearnedWord = false,
            //    },
            //    new Word
            //    {
            //        WordEng = "parrot",
            //        Transcription = "|ˈpærət|",
            //        Translation = "папуга",
            //        Dictionary = dict1,
            //        Image = File.ReadAllBytes($@"{path}\Image\parrot.png"),
            //        Sound = File.ReadAllBytes($@"{path}\Sound\parrot.mp3"),
            //        IsLearnedWord = false,
            //    },
            //    new Word
            //    {
            //        WordEng = "donkey",
            //        Transcription = "|ˈdɔːŋki|",
            //        Translation = "осел",
            //        Dictionary = dict1,
            //        Image = File.ReadAllBytes($@"{path}\Image\donkey.jpg"),
            //        Sound = File.ReadAllBytes($@"{path}\Sound\donkey.mp3"),
            //        IsLearnedWord = false,
            //    },
            //    new Word
            //    {
            //        WordEng = "rat",
            //        Transcription = "|ræt|",
            //        Translation = "пацюк",
            //        Dictionary = dict1,
            //        Image = File.ReadAllBytes($@"{path}\Image\rat.png"),
            //        Sound = File.ReadAllBytes($@"{path}\Sound\rat.mp3"),
            //        IsLearnedWord = false,
            //    },
            //    new Word
            //    {
            //        WordEng = "mosquito",
            //        Transcription = "|məˈskiːtoʊ|",
            //        Translation = "комар",
            //        Dictionary = dict1,
            //        Image = File.ReadAllBytes($@"{path}\Image\mosquito.jpg"),
            //        Sound = File.ReadAllBytes($@"{path}\Sound\mosquito.mp3"),
            //        IsLearnedWord = false,
            //    },
            //    new Word
            //    {
            //        WordEng = "fox",
            //        Transcription = "|fɑːks|",
            //        Translation = "лисиця",
            //        Dictionary = dict1,
            //        Image = File.ReadAllBytes($@"{path}\Image\fox.png"),
            //        Sound = File.ReadAllBytes($@"{path}\Sound\fox.mp3"),
            //        IsLearnedWord = false,
            //    },
            //    new Word
            //    {
            //        WordEng = "ratel",
            //        Transcription = "|ˈreɪt(ə)l|",
            //        Translation = "медоїд",
            //        Dictionary = dict1,
            //        Image = File.ReadAllBytes($@"{path}\Image\ratel.jpg"),
            //        Sound = File.ReadAllBytes($@"{path}\Sound\ratel.mp3"),
            //        IsLearnedWord = false,
            //    }
            //};
            //var serializer = new DataContractSerializer(typeof(Word[]),
            //    null,
            //    0x7FFF,
            //    false,
            //    true,
            //    null);
            //using (FileStream fs = new FileStream($@"{path}\words.xml", FileMode.OpenOrCreate))
            //{
            //    serializer.WriteObject(fs, words);
            //}
            #endregion
            Word[] words      = null;
            var    serializer = new DataContractSerializer(typeof(Word[]), null,
                                                           0x7FFF,
                                                           false,
                                                           true,
                                                           null);
            using (FileStream fs = new FileStream($@"{path}\words.xml", FileMode.OpenOrCreate))
            {
                XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()
                {
                    MaxArrayLength = 2147483647
                });
                words = (Word[])serializer.ReadObject(reader);
                reader.Close();
            }
            _ctx.Words.AddRange(words);
            _ctx.SaveChanges();
        }
예제 #25
0
        public static bool TryGetExceptionDetails(CommunicationException exception, out ServiceManagementError errorDetails, out HttpStatusCode httpStatusCode, out string operationId)
        {
            errorDetails   = null;
            httpStatusCode = 0;
            operationId    = null;

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

            if (exception.Message == "Internal Server Error")
            {
                httpStatusCode = HttpStatusCode.InternalServerError;
                return(true);
            }

            WebException wex = exception.InnerException as WebException;

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

            HttpWebResponse response = wex.Response as HttpWebResponse;

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

            //httpStatusCode = response.StatusCode;
            //if (httpStatusCode == HttpStatusCode.Forbidden)
            //{
            //    return true;
            //}

            if (response.Headers != null)
            {
                operationId = response.Headers[ApiConstants.OperationTrackingIdHeader];
            }

            // Don't wrap responseStream in a using statement to prevent it
            // from being disposed twice (as it's disposed by reader if it is
            // successfully disposed).
            Stream responseStream = null;

            try
            {
                responseStream = response.GetResponseStream();
                if (responseStream.Length == 0)
                {
                    return(false);
                }

                try
                {
                    using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(responseStream, new XmlDictionaryReaderQuotas()))
                    {
                        // Release the reference to responseStream since it
                        // will be closed when the reader is diposed
                        responseStream = null;

                        DataContractSerializer ser = new DataContractSerializer(typeof(ServiceManagementError));
                        errorDetails = (ServiceManagementError)ser.ReadObject(reader, true);
                    }
                }
                catch (SerializationException)
                {
                    return(false);
                }
            }
            finally
            {
                if (responseStream != null)
                {
                    responseStream.Dispose();
                }
            }

            return(true);
        }
예제 #26
0
        public static bool TryGetExceptionDetails(CommunicationException exception, out ServiceManagementError errorDetails, out HttpStatusCode httpStatusCode, out string operationId)
        {
            bool flag;

            errorDetails   = null;
            httpStatusCode = 0;
            operationId    = null;
            if (exception != null)
            {
                if (exception.Message != "Internal Server Error")
                {
                    WebException innerException = exception.InnerException as WebException;
                    if (innerException != null)
                    {
                        HttpWebResponse response = innerException.Response as HttpWebResponse;
                        if (response != null)
                        {
                            if (response.Headers != null)
                            {
                                operationId = response.Headers["x-ms-request-id"];
                            }
                            Stream responseStream = response.GetResponseStream();
                            using (responseStream)
                            {
                                try
                                {
                                    if (responseStream == null || responseStream.Length == (long)0)
                                    {
                                        flag = false;
                                        return(flag);
                                    }
                                    else
                                    {
                                        XmlDictionaryReader    xmlDictionaryReader    = XmlDictionaryReader.CreateTextReader(responseStream, new XmlDictionaryReaderQuotas());
                                        DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(ServiceManagementError));
                                        errorDetails = (ServiceManagementError)dataContractSerializer.ReadObject(xmlDictionaryReader, true);
                                    }
                                }
                                catch (Exception exception1)
                                {
                                    flag = false;
                                    return(flag);
                                }
                                return(true);
                            }
                            return(flag);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    httpStatusCode = HttpStatusCode.InternalServerError;
                    return(true);
                }
            }
            else
            {
                return(false);
            }
        }
예제 #27
0
        public XmlDocument CreateInformationCardXML(InformationCard card)
        {
            MemoryStream stream = new MemoryStream();
            XmlWriter    writer = XmlWriter.Create(stream);

            writer.WriteStartElement("InformationCard", "http://schemas.xmlsoap.org/ws/2005/05/identity");


            writer.WriteAttributeString("lang", "http://www.w3.org/XML/1998/namespace", "en-US");
            writer.WriteStartElement("InformationCardReference", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            writer.WriteElementString("CardId", "http://schemas.xmlsoap.org/ws/2005/05/identity", card.CardReference.CardID);
            writer.WriteElementString("CardVersion", "http://schemas.xmlsoap.org/ws/2005/05/identity", card.CardReference.CardVersion.ToString());
            writer.WriteEndElement();

            if (card.CardName != null && card.CardName.Length > 0)
            {
                writer.WriteStartElement("CardName", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                writer.WriteString(card.CardName);
                writer.WriteEndElement();
            }



            if (card.CardImage != null && card.CardImage.ImageName.Length > 0)
            {
                writer.WriteStartElement("CardImage", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                if (card.CardImage != null && card.CardImage.ImageMimeType != null && card.CardImage.ImageMimeType.Length > 0)
                {
                    writer.WriteAttributeString("MimeType", card.CardImage.ImageMimeType);
                }

                FileInfo cardImage = new FileInfo(card.CardImage.ImageName);
                if (cardImage.Exists)
                {
                    byte[] cardImageBytes = new byte[cardImage.Length];
                    using (FileStream imageFS = cardImage.OpenRead())
                    {
                        imageFS.Read(cardImageBytes, 0, cardImageBytes.Length);
                    }


                    string imageBase64 = Convert.ToBase64String(cardImageBytes);
                    writer.WriteString(imageBase64);
                    writer.WriteEndElement();
                }
            }


            writer.WriteStartElement("Issuer", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            writer.WriteString(card.Issuer);
            writer.WriteEndElement();

            //writer.WriteStartElement("IssuerName", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            //writer.WriteString(card.IssuerName);
            //writer.WriteEndElement();

            writer.WriteStartElement("TimeIssued", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            writer.WriteString(XmlConvert.ToString(card.TimeIssued, XmlDateTimeSerializationMode.Utc));
            writer.WriteEndElement();


            writer.WriteStartElement("TimeExpires", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            writer.WriteString(XmlConvert.ToString(card.TimeExpires, XmlDateTimeSerializationMode.Utc));
            writer.WriteEndElement();


            writer.WriteStartElement("TokenServiceList", "http://schemas.xmlsoap.org/ws/2005/05/identity");


            foreach (TokenService ts in card.TokenServiceList)
            {
                EndpointAddressBuilder endpointBuilder = new EndpointAddressBuilder();

                endpointBuilder.Uri = new Uri(ts.EndpointReference.Address);

                endpointBuilder.Identity = new X509CertificateEndpointIdentity(RetrieveCertificate(ts.EndpointReference.Identity));

                if (null != ts.EndpointReference.Mex)
                {
                    MetadataReference mexReference = new MetadataReference();
                    mexReference.Address        = new EndpointAddress(ts.EndpointReference.Mex);
                    mexReference.AddressVersion = AddressingVersion.WSAddressing10;

                    MetadataSection mexSection = new MetadataSection();
                    mexSection.Metadata = mexReference;

                    MetadataSet mexSet = new MetadataSet();
                    mexSet.MetadataSections.Add(mexSection);


                    MemoryStream mexMemoryStream = new MemoryStream();

                    XmlTextWriter mexWriter = new XmlTextWriter(mexMemoryStream, System.Text.Encoding.UTF8);

                    mexSet.WriteTo(mexWriter);

                    mexWriter.Flush();

                    mexMemoryStream.Seek(0, SeekOrigin.Begin);

                    XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(mexMemoryStream, XmlDictionaryReaderQuotas.Max);

                    endpointBuilder.SetMetadataReader(reader);


                    writer.WriteStartElement("TokenService", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                    EndpointAddress endpoint = endpointBuilder.ToEndpointAddress();
                    endpoint.WriteTo(AddressingVersion.WSAddressing10, writer);

                    writer.WriteStartElement("UserCredential", "http://schemas.xmlsoap.org/ws/2005/05/identity");


                    if (ts.UserCredential.DisplayCredentialHint != null && ts.UserCredential.DisplayCredentialHint.Length > 0)
                    {
                        writer.WriteStartElement("DisplayCredentialHint", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                        writer.WriteString(ts.UserCredential.DisplayCredentialHint);
                        writer.WriteEndElement();
                    }

                    switch (ts.UserCredential.UserCredentialType)
                    {
                    case CredentialType.UsernameAndPassword:
                        writer.WriteStartElement("UsernamePasswordCredential", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                        if (ts.UserCredential.Value.GetType() == typeof(string) && !string.IsNullOrEmpty((string)ts.UserCredential.Value))
                        {
                            writer.WriteStartElement("Username", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                            writer.WriteString((string)ts.UserCredential.Value);
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement();
                        break;

                    case CredentialType.Kerberos:
                        writer.WriteStartElement("KerberosV5Credential", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                        writer.WriteEndElement();
                        break;

                    case CredentialType.SmartCard:
                        writer.WriteStartElement("X509V3Credential", "http://schemas.xmlsoap.org/ws/2005/05/identity");

                        writer.WriteStartElement("X509Data", "http://www.w3.org/2000/09/xmldsig#");
                        if ((ts.UserCredential.Value.GetType() == typeof(CertificateInfo) && ts.UserCredential.Value != null))
                        {
                            writer.WriteStartElement("KeyIdentifier", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
                            writer.WriteAttributeString("ValueType",
                                                        null,
                                                        "http://docs.oasis-open.org/wss/2004/xx/oasis-2004xx-wss-soap-message-security-1.1#ThumbprintSHA1");
                            writer.WriteString(RetrieveCertificate((CertificateInfo)ts.UserCredential.Value).Thumbprint);
                            writer.WriteEndElement();
                        }
                        else
                        {
                            throw new InvalidDataException("No thumbprint was specified");
                        }
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                        break;

                    default:
                        break;
                    }
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                }
            }
            writer.WriteEndElement(); //end of tokenservice list
            //
            // tokentypes
            //
            writer.WriteStartElement("SupportedTokenTypeList", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            foreach (TokenType tokenType in card.AcceptedTokenTypes)
            {
                writer.WriteElementString("TokenType",
                                          "http://schemas.xmlsoap.org/ws/2005/02/trust",
                                          tokenType.Uri);
            }
            writer.WriteEndElement();

            //
            // claims
            //
            writer.WriteStartElement("SupportedClaimTypeList", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            foreach (CardClaim claim in card.SupportedClaimTypeList)
            {
                writer.WriteStartElement("SupportedClaimType", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                writer.WriteAttributeString("Uri", claim.Uri);


                if (!String.IsNullOrEmpty(claim.DisplayTag))
                {
                    writer.WriteElementString("DisplayTag", "http://schemas.xmlsoap.org/ws/2005/05/identity",
                                              claim.DisplayTag);
                }

                if (!String.IsNullOrEmpty(claim.Description))
                {
                    writer.WriteElementString("Description", "http://schemas.xmlsoap.org/ws/2005/05/identity",
                                              claim.Description);
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();


            if (card.RequireRPIdentification)
            {
                writer.WriteElementString("RequireAppliesTo", "http://schemas.xmlsoap.org/ws/2005/05/identity", card.RequireRPIdentification.ToString());
            }


            if (!String.IsNullOrEmpty(card.PrivacyNotice))
            {
                writer.WriteStartElement("PrivacyNotice", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                writer.WriteString(card.PrivacyNotice);
                writer.WriteEndElement();
            }
            writer.WriteEndElement();

            writer.Close();



            stream.Position = 0;

            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = false;
            doc.Load(stream);

            return(doc);
        }
예제 #28
0
        static void Main(string[] args)
        {
            //iscitavam podatke iz baze
            Console.ReadLine();
            List <Automobil> iscitaniAutomobili = new List <Automobil>();

            DataContractSerializer dcs = new DataContractSerializer(typeof(List <Automobil>));

            using (Stream stream = new FileStream("Automobili.xml", FileMode.OpenOrCreate, FileAccess.Read))
            {
                using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
                {
                    reader.ReadContentAsObject();
                    iscitaniAutomobili = (List <Automobil>)dcs.ReadObject(reader);
                }
            }

            foreach (var item in iscitaniAutomobili)
            {
                Podaci.automobili[item.Registracija] = item;
            }

            List <Korisnik> iscitaniKorisnici = new List <Korisnik>();

            DataContractSerializer dcs1 = new DataContractSerializer(typeof(List <Korisnik>));

            using (Stream stream = new FileStream("Korisnici.xml", FileMode.OpenOrCreate, FileAccess.Read))
            {
                using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
                {
                    reader.ReadContentAsObject();
                    iscitaniKorisnici = (List <Korisnik>)dcs1.ReadObject(reader);
                }
            }

            foreach (var item in iscitaniKorisnici)
            {
                Podaci.korisnici[item.KorisnickoIme] = item;
            }

            List <Korisnik> iscitaniZahtjevi = new List <Korisnik>();

            DataContractSerializer dcs2 = new DataContractSerializer(typeof(List <Korisnik>));

            using (Stream stream = new FileStream("ZahtjeviZlCl.xml", FileMode.OpenOrCreate, FileAccess.Read))
            {
                using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
                {
                    reader.ReadContentAsObject();
                    iscitaniZahtjevi = (List <Korisnik>)dcs2.ReadObject(reader);
                }
            }
            foreach (var item in iscitaniKorisnici)
            {
                Podaci.ZahtjevZlClana.Add(item);
            }
            string servNameCrt = SecurityManager.Formatter.ParseName(WindowsIdentity.GetCurrent().Name);
            //string servNameCrt = "wcfservicem";
            //string OU1= "admin";
            //string OU2 = "clan";
            //string MachineName = Environment.MachineName;
            //string[] parts = MachineName.Split('-');
            //string MachineNameSplit = String.Format("{0}", parts[0]);
            //logName = String.Format("{0}LogFile", MachineNameSplit);
            //logSourceName = String.Format("{0}LogSourceName", "net.tcp://localhost:4000");
            NetTcpBinding binding = new NetTcpBinding();

            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;
            string address = "net.tcp://localhost:4000/WCFService";
            Audit  audit   = new Audit();

            ServiceHost host = new ServiceHost(typeof(Admin));

            //-----konfigurisanje ServiceHost obj da podrze zapisivanje bezbj.dogadjaja
            ServiceSecurityAuditBehavior newAuditBehavior = new ServiceSecurityAuditBehavior();

            host.Description.Behaviors.Remove <ServiceSecurityAuditBehavior>();
            host.Description.Behaviors.Add(newAuditBehavior);
            //-----

            host.AddServiceEndpoint(typeof(IAdmin), binding, address);
            //host.Authorization.ServiceAuthorizationManager = new ServiceAuthorizationManager(); //provjeriti !
            //host.Description.Behaviors.Remove(typeof(ServiceDebugBehavior));
            //host.Description.Behaviors.Add(new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });



            host.Credentials.ClientCertificate.Authentication.CertificateValidationMode  = X509CertificateValidationMode.Custom;
            host.Credentials.ClientCertificate.Authentication.CustomCertificateValidator = new ServiceCertificateValidator();
            host.Credentials.ClientCertificate.Authentication.RevocationMode             = X509RevocationMode.NoCheck;

            host.Credentials.ServiceCertificate.Certificate = CertificateManager.GetCertificateFromStorage(StoreName.My, StoreLocation.LocalMachine, servNameCrt /*servNameCrt,OU1,OU2*/);
            //host.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My,X509FindType.FindBySubjectName,servNameCrt);
            //host.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint,OU1);
            //host.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint,"");
            host.Open();

            Console.WriteLine("WCFService is opened. Press <enter> to finish...");
            Console.ReadLine();

            host.Close();
        }
예제 #29
0
        System.ServiceModel.Channels.Message IClientMessageFormatter.SerializeRequest(System.ServiceModel.Channels.MessageVersion messageVersion, object[] parameters)
        {
            MemoryStream        memStream = new MemoryStream();
            XmlDictionaryWriter writer    = XmlDictionaryWriter.CreateTextWriter(memStream);

            writer.WriteStartElement(XmlRpcProtocol.Params);
            foreach (object param in parameters)
            {
                writer.WriteStartElement(XmlRpcProtocol.Param);
                writer.WriteStartElement(XmlRpcProtocol.Value);
                XmlRpcDataContractSerializationHelper.Serialize(writer, param);
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            writer.Flush();

            memStream.Position = 0;
            XmlDictionaryReaderQuotas quotas        = new XmlDictionaryReaderQuotas();
            XmlRpcMessage             xmlRpcMessage = new XmlRpcMessage(_operationDescription.Messages[0].Action, XmlDictionaryReader.CreateTextReader(memStream, quotas));

            return(xmlRpcMessage);
        }
        public override void Update(GameTime gameTime)
        {
            gamepadstate = GamePad.GetState(PlayerIndex.One);

            if (videoplayer.State == MediaState.Stopped)
            {
                continueButton.Update(gameTime);
            }

            if (LevelChoice.LevelOne == levelChoice)
            {
                if (((Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Enter)) && (state == 0) && (MediaState.Stopped == videoplayer.State)) || ((continueButton.masterButtonEffect == true) && (state == 0) && (MediaState.Stopped == videoplayer.State)) || (gamepadstate.IsButtonDown(Buttons.Start)) && (state == 0) && (MediaState.Stopped == videoplayer.State))
                {
                    UnloadContent();


                    //   ScreenManager.resumevideogame = new ResumeVideoGame(1);
                    displayLoading = true;
                    MediaPlayer.Stop();

                    DataContractSerializer ds     = new DataContractSerializer(typeof(ResumeVideoGame));
                    FileStream             fs     = new FileStream("StateOneDefaultResumeGamePlay.xml", FileMode.Open);
                    XmlDictionaryReader    reader =
                        XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                    ScreenManager.Instance.resumevideogame = (ResumeVideoGame)ds.ReadObject(reader);

                    fs.Close();
                    ScreenManager.Instance.AddScreen(ScreenManager.Instance.resumevideogame);
                }

                if (((Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Enter)) && (state == 1) && (MediaState.Stopped == videoplayer.State)) || (continueButton.masterButtonEffect == true) && (state == 1) && (MediaState.Stopped == videoplayer.State) || (gamepadstate.IsButtonDown(Buttons.Start) && (state == 1) && (MediaState.Stopped == videoplayer.State)))
                {
                    UnloadContent();
                    // ScreenManager.resumevideogame = new ResumeVideoGame(2);
                    displayLoading = true;
                    MediaPlayer.Stop();
                    DataContractSerializer ds     = new DataContractSerializer(typeof(ResumeVideoGame));
                    FileStream             fs     = new FileStream("StateTwoDefaultResumeGamePlay.xml", FileMode.Open);
                    XmlDictionaryReader    reader =
                        XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                    ScreenManager.Instance.resumevideogame = (ResumeVideoGame)ds.ReadObject(reader);
                    fs.Close();
                    ScreenManager.Instance.AddScreen(ScreenManager.Instance.resumevideogame);
                }
            }

            else if (LevelChoice.LevelTwo == levelChoice)
            {
                if (((Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Enter)) && (state == 0) && (MediaState.Stopped == videoplayer.State)) || (continueButton.masterButtonEffect == true) && (state == 0) && (MediaState.Stopped == videoplayer.State) || (gamepadstate.IsButtonDown(Buttons.Start) && (state == 0) && (MediaState.Stopped == videoplayer.State)))
                {
                    UnloadContent();


                    //   ScreenManager.resumevideogame = new ResumeVideoGame(1);
                    displayLoading = true;
                    MediaPlayer.Stop();
                    DataContractSerializer ds     = new DataContractSerializer(typeof(ResumeVideoGame));
                    FileStream             fs     = new FileStream("StrongStateOneDefaultResumeGamePlay.xml", FileMode.Open);
                    XmlDictionaryReader    reader =
                        XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                    ScreenManager.Instance.resumevideogame = (ResumeVideoGame)ds.ReadObject(reader);
                    fs.Close();

                    ScreenManager.Instance.AddScreen(ScreenManager.Instance.resumevideogame);
                }

                if (((Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Enter)) && (state == 1) && (MediaState.Stopped == videoplayer.State)) || ((continueButton.masterButtonEffect == true) && (state == 1) && (MediaState.Stopped == videoplayer.State)) || (gamepadstate.IsButtonDown(Buttons.Start) && (state == 1)) && (MediaState.Stopped == videoplayer.State))
                {
                    UnloadContent();
                    // ScreenManager.resumevideogame = new ResumeVideoGame(2);
                    DataContractSerializer ds     = new DataContractSerializer(typeof(ResumeVideoGame));
                    FileStream             fs     = new FileStream("StrongStateTwoDefaultResumeGamePlay.xml", FileMode.Open);
                    XmlDictionaryReader    reader =
                        XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                    ScreenManager.Instance.resumevideogame = (ResumeVideoGame)ds.ReadObject(reader);
                    fs.Close();
                    ScreenManager.Instance.AddScreen(ScreenManager.Instance.resumevideogame);
                }
            }

            else if (LevelChoice.LevelThree == levelChoice)
            {
                if (((Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Enter)) && (state == 0) && (MediaState.Stopped == videoplayer.State)) || ((continueButton.masterButtonEffect == true) && (state == 0) && (MediaState.Stopped == videoplayer.State)) || (gamepadstate.IsButtonDown(Buttons.Start) && (state == 0) && (MediaState.Stopped == videoplayer.State)))
                {
                    UnloadContent();


                    //   ScreenManager.resumevideogame = new ResumeVideoGame(1);
                    displayLoading = true;
                    MediaPlayer.Stop();
                    DataContractSerializer ds = new DataContractSerializer(typeof(ResumeVideoGame));
                    //FileStream fs = new FileStream("HandStateOneDefaultResumeGamePlay.xml", FileMode.Open);
                    FileStream          fs     = new FileStream("WakandaStateOneDefaultResumeGamePlay.xml", FileMode.Open);
                    XmlDictionaryReader reader =
                        XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                    ScreenManager.Instance.resumevideogame = (ResumeVideoGame)ds.ReadObject(reader);
                    fs.Close();

                    ScreenManager.Instance.AddScreen(ScreenManager.Instance.resumevideogame);
                }

                if (((Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Enter)) && (state == 1) && (MediaState.Stopped == videoplayer.State)) || ((continueButton.masterButtonEffect == true) && (state == 1) && (MediaState.Stopped == videoplayer.State)) || (gamepadstate.IsButtonDown(Buttons.Start) && (state == 1) && (MediaState.Stopped == videoplayer.State)))
                {
                    UnloadContent();
                    // ScreenManager.resumevideogame = new ResumeVideoGame(2);
                    displayLoading = true;
                    MediaPlayer.Stop();
                    DataContractSerializer ds = new DataContractSerializer(typeof(ResumeVideoGame));
                    // FileStream fs = new FileStream("HandStateTwoDefaultResumeGamePlay.xml", FileMode.Open);
                    FileStream          fs     = new FileStream("WakandaStateTwoDefaultResumeGamePlay.xml", FileMode.Open);
                    XmlDictionaryReader reader =
                        XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                    ScreenManager.Instance.resumevideogame = (ResumeVideoGame)ds.ReadObject(reader);
                    fs.Close();
                    ScreenManager.Instance.AddScreen(ScreenManager.Instance.resumevideogame);
                }
            }

            else if (LevelChoice.LevelFour == levelChoice)
            {
                if (((Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Enter)) && (state == 0) && (MediaState.Stopped == videoplayer.State)) || ((continueButton.masterButtonEffect == true) && (state == 0) && (MediaState.Stopped == videoplayer.State)) || (gamepadstate.IsButtonDown(Buttons.Start) && (state == 0) && (MediaState.Stopped == videoplayer.State)))
                {
                    UnloadContent();


                    //   ScreenManager.resumevideogame = new ResumeVideoGame(1);
                    displayLoading = true;
                    MediaPlayer.Stop();
                    DataContractSerializer ds     = new DataContractSerializer(typeof(ResumeVideoGame));
                    FileStream             fs     = new FileStream("RopeStateOneDefaultResumeGamePlay.xml", FileMode.Open);
                    XmlDictionaryReader    reader =
                        XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                    ScreenManager.Instance.resumevideogame = (ResumeVideoGame)ds.ReadObject(reader);

                    fs.Close();
                    ScreenManager.Instance.AddScreen(ScreenManager.Instance.resumevideogame);
                }

                if (((Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Enter)) && (state == 1) && (MediaState.Stopped == videoplayer.State)) || ((continueButton.masterButtonEffect == true) && (state == 1) && (MediaState.Stopped == videoplayer.State)) || (gamepadstate.IsButtonDown(Buttons.Start) && (state == 1) && (MediaState.Stopped == videoplayer.State)))
                {
                    UnloadContent();
                    displayLoading = true;
                    MediaPlayer.Stop();
                    // ScreenManager.resumevideogame = new ResumeVideoGame(2);
                    DataContractSerializer ds     = new DataContractSerializer(typeof(ResumeVideoGame));
                    FileStream             fs     = new FileStream("RopeStateTwoDefaultResumeGamePlay.xml", FileMode.Open);
                    XmlDictionaryReader    reader =
                        XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                    ScreenManager.Instance.resumevideogame = (ResumeVideoGame)ds.ReadObject(reader);
                    fs.Close();
                    ScreenManager.Instance.AddScreen(ScreenManager.Instance.resumevideogame);
                }
            }

            else if (LevelChoice.LevelFive == levelChoice)
            {
                if (((Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Enter)) && (state == 0) && (MediaState.Stopped == videoplayer.State)) || ((continueButton.masterButtonEffect == true) && (state == 0) && (MediaState.Stopped == videoplayer.State)) || (gamepadstate.IsButtonDown(Buttons.Start) && (state == 0) && (MediaState.Stopped == videoplayer.State)))
                {
                    UnloadContent();


                    //   ScreenManager.resumevideogame = new ResumeVideoGame(1);
                    displayLoading = true;
                    MediaPlayer.Stop();
                    DataContractSerializer ds     = new DataContractSerializer(typeof(ResumeVideoGame));
                    FileStream             fs     = new FileStream("DeceptionStateOneDefaultResumeGamePlay.xml", FileMode.Open);
                    XmlDictionaryReader    reader =
                        XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                    ScreenManager.Instance.resumevideogame = (ResumeVideoGame)ds.ReadObject(reader);

                    fs.Close();
                    ScreenManager.Instance.AddScreen(ScreenManager.Instance.resumevideogame);
                }

                if (((Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Enter)) && (state == 1) && (MediaState.Stopped == videoplayer.State)) || ((continueButton.masterButtonEffect == true) && (state == 1) && (MediaState.Stopped == videoplayer.State)) || (gamepadstate.IsButtonDown(Buttons.Start) && (state == 1) && (MediaState.Stopped == videoplayer.State)))
                {
                    UnloadContent();
                    displayLoading = true;
                    MediaPlayer.Stop();
                    // ScreenManager.resumevideogame = new ResumeVideoGame(2);
                    DataContractSerializer ds     = new DataContractSerializer(typeof(ResumeVideoGame));
                    FileStream             fs     = new FileStream("DeceptionStateTwoDefaultResumeGamePlay.xml", FileMode.Open);
                    XmlDictionaryReader    reader =
                        XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                    ScreenManager.Instance.resumevideogame = (ResumeVideoGame)ds.ReadObject(reader);
                    fs.Close();
                    ScreenManager.Instance.AddScreen(ScreenManager.Instance.resumevideogame);
                }
            }
        }