internal Response(ReturnCode result,
                          string postcode,
                          SpatialInfo spatialInfo,
                          Request input,
                          Model.Link[] links)
        {
            if (links == null) throw new ArgumentNullException("links");

            Result = result;
            Postcode = postcode;
            SpatialInfo = spatialInfo;
            Input = input;
            
            var newLinks = new List<Model.Link>();

            foreach (Model.Link link in links)
            {
                Model.Link newLink;

                switch (link.Rel)
                {
                    case "self":
                        newLink = new Link(link.Rel, link.Href);
                        break;
                    default:
                        newLink = link;
                        break;
                }

                newLinks.Add(newLink);
            }

            Links = newLinks.ToArray();
        }
        internal Response(ReturnCode result,
                          int? ecadId,
                          string geoDirectoryId,
                          Request input,
                          Model.Link[] links)
        {
            if (links == null) throw new ArgumentNullException("links");

            Result = result;
            EcadId = ecadId;
            GeoDirectoryId = geoDirectoryId;
            Input = input;
            
            var newLinks = new List<Model.Link>();

            foreach (Model.Link link in links)
            {
                Model.Link newLink;

                switch (link.Rel)
                {
                    case "self":
                        newLink = new Model.MapId.Link(link.Rel, link.Href);
                        break;
                    default:
                        newLink = link;
                        break;
                }

                newLinks.Add(newLink);
            }

            Links = newLinks.ToArray();
        }
Пример #3
0
        /// <summary>
        /// Construct a Response object from the supplied byte array
        /// </summary>
        /// <param name="message">a byte array returned from a DNS server query</param>
        internal Response(byte[] message)
        {
            if (message == null) throw new ArgumentNullException("message");

            // the bit flags are in bytes 2 and 3
            byte flags1 = message[2];
            byte flags2 = message[3];

            // get return code from lowest 4 bits of byte 3
            int returnCode = flags2 & 15;

            // if its in the reserved section, set to other
            if (returnCode > 6) returnCode = 6;
            _returnCode = (ReturnCode) returnCode;

            // other bit flags
            _authoritativeAnswer = ((flags1 & 4) != 0);
            _recursionAvailable = ((flags2 & 128) != 0);
            _messageTruncated = ((flags1 & 2) != 0);

            // create the arrays of response objects
            _questions = new Question[GetShort(message, 4)];
            _answers = new Answer[GetShort(message, 6)];
            _nameServers = new NameServer[GetShort(message, 8)];
            _additionalRecords = new AdditionalRecord[GetShort(message, 10)];

            // need a pointer to do this, position just after the header
            var pointer = new Pointer(message, 12);

            ReadQuestions(pointer);
            ReadAnswers(pointer);
            ReadNameServers(pointer);
            ReadAdditionalRecords(pointer);
        }
        internal Response(ReturnCode result,
                          string postcode,
                          int? addressId,
                          AddressType? addressType,
                          MatchLevel matchLevel,
                          string[] postalAddress,
                          AddressElement[] postalAddressElements,
                          string[] geographicAddress,
                          AddressElement[] geographicAddressElements,
                          string[] vanityAddress,
                          AddressElement[] vanityAddressElements,
                          ReformattedAddressResult? reformattedAddressResult,
                          string[] reformattedAddress,
                          int totalOptions,
                          Option[] options,
                          Request input,
                          Model.Link[] links
            )
        {
            if (links == null) throw new ArgumentNullException("links");

            Result = result;
            Postcode = postcode;
            AddressId = addressId;
            AddressType = addressType;
            MatchLevel = matchLevel;
            PostalAddress = postalAddress;
            PostalAddressElements = postalAddressElements;
            GeographicAddress = geographicAddress;
            GeographicAddressElements = geographicAddressElements;
            VanityAddress = vanityAddress;
            VanityAddressElements = vanityAddressElements;
            ReformattedAddressResult = reformattedAddressResult;
            ReformattedAddress = reformattedAddress;
            TotalOptions = totalOptions;
            Options = options;
            Input = input;

            var newLinks = new List<Model.Link>();

            foreach (Model.Link link in links)
            {
                Model.Link newLink;

                switch (link.Rel)
                {
                    case "self":
                        newLink = new Model.PostcodeLookup.Link(link.Rel, link.Href);
                        break;
                    default:
                        newLink = link;
                        break;
                }

                newLinks.Add(newLink);
            }

            Links = newLinks.ToArray();
        }
Пример #5
0
 public Task SetMemberVariables(MemberVariables x)
 {
     myGrainBytes = (byte[])x.byteArray.Clone();
     myGrainString = x.stringVar;
     myCode = x.code;
     //RaiseStateUpdateEvent();
     return TaskDone.Done;
 }
Пример #6
0
 public static JobResult CreateSuccessResult(ReturnCode returnCode = ReturnCode.OK)
 {
     return new JobResult
     {
         Job = new ConcreteJob {JobState = ConcreteJobState.Completed},
         ReturnValue = returnCode
     };
 }
Пример #7
0
		private static int Cmd_Help(ReturnCode returncode,string error=null)
		{
			WriteLine($"RopPreBuild {Version}");
			if (error != null) Tab.Red(error).WriteLine();
			WriteLine("Usage:");
			Tab.Write("RopPreBuild <").Yellow("prefile").Write(">.pre.cs").WriteLine(" [--<flags>]");
			Tab.Write("RopPreBuild ").WriteLine(" --version");
			return (int)returncode;
		}
Пример #8
0
	/**
	 * Check the return status for errors. If there is an error,
     * then terminate.
	 **/
	public static void checkStatus(ReturnCode status, string info) {
        if (status != ReturnCode.Ok &&
             status != ReturnCode.NoData)
        {
            System.Console.WriteLine(
                "Error in " + info + ": " + getErrorName(status));
            System.Environment.Exit(-1);
        }
	}
Пример #9
0
        /// <summary>
        /// Initializes a new instance_ of the Response class by parsing the message reponse.
        /// </summary>
        /// <param name="message">A byte array that contains the response message.</param>
        internal Response(byte[] message) {
            if (message == null)
                throw new ArgumentException("message");

            // ID - 16 bits

            // QR - 1 bit
            // Opcode - 4 bits
            // AA, TC, RD - 3 bits
            byte flags1 = message[2];

            // RA, Z - 2 bits
            // RCODE - 4 bits
            byte flags2 = message[3];

            long counts = message[3];

            // adjust the return code
            int return_code = (flags2 & (byte)0x3c) >> 2;
            return_code_ = (return_code > 6) ? ReturnCode.Other : (ReturnCode)return_code;

            // other bit flags
            authoritative_answer_ = ((flags1 & 4) != 0);
            recursion_available_ = ((flags2 & 128) != 0);
            truncated_ = ((flags1 & 2) != 0);

            // create the arrays of response objects
            questions_ = new Question[GetShort(message, 4)];
            answers_ = new Answer[GetShort(message, 6)];
            name_servers_ = new NameServer[GetShort(message, 8)];
            additional_records_ = new AdditionalRecord[GetShort(message, 10)];

            // need a pointer to do this, position just after the header
            RecordPointer pointer = new RecordPointer(message, 12);

            // and now populate them, they always follow this order
            for (int i = 0; i < questions_.Length; i++) {
                try {
                    questions_[i] = new Question(pointer);
                } catch(Exception ex) {
                    throw new InvalidResponseException(ex);
                }
            }

            for (int i = 0; i < answers_.Length; i++) {
                answers_[i] = new Answer(pointer);
            }

            for (int i = 0; i < name_servers_.Length; i++) {
                name_servers_[i] = new NameServer(pointer);
            }

            for (int i = 0; i < additional_records_.Length; i++) {
                additional_records_[i] = new AdditionalRecord(pointer);
            }
        }
Пример #10
0
        /// <summary>
        /// Construct a Response object from the supplied byte array
        /// </summary>
        /// <param name="message">a byte array returned from a DNS server query</param>
        internal Response(byte[] message)
        {
            // the bit flags are in bytes 2 and 3
            byte flags1 = message[2];
            byte flags2 = message[3];

            // get return code from lowest 4 bits of byte 3
            int returnCode = flags2 & 15;

            // if its in the reserved section, set to other
            if (returnCode > 6) returnCode = 6;
            _returnCode = (ReturnCode)returnCode;

            // other bit flags
            _authoritativeAnswer = ((flags1 & 4) != 0);
            _recursionAvailable = ((flags2 & 128) != 0);
            _truncated = ((flags1 & 2) != 0);

            // create the arrays of response objects
            _questions = new Question[GetShort(message, 4)];
            _answers = new Answer[GetShort(message, 6)];
            _nameServers = new NameServer[GetShort(message, 8)];
            _additionalRecords = new AdditionalRecord[GetShort(message, 10)];

            // need a pointer to do this, position just after the header
            Pointer pointer = new Pointer(message, 12);

            // and now populate them, they always follow this order
            for (int index = 0; index < _questions.Length; index++)
            {
                try
                {
                    // try to build a quesion from the response
                    _questions[index] = new Question(pointer);
                }
                catch (Exception ex)
                {
                    Terminals.Logging.Error("DNS Response Question Failure", ex);
                    // something grim has happened, we can't continue
                    throw new InvalidResponseException(ex);
                }
            }
            for (int index = 0; index < _answers.Length; index++)
            {
                _answers[index] = new Answer(pointer);
            }
            for (int index = 0; index < _nameServers.Length; index++)
            {
                _nameServers[index] = new NameServer(pointer);
            }
            for (int index = 0; index < _additionalRecords.Length; index++)
            {
                _additionalRecords[index] = new AdditionalRecord(pointer);
            }
        }
Пример #11
0
		public TKeyRecord(string name, TSigAlgorithm algorithm, DateTime inception, DateTime expiration, TKeyMode mode, ReturnCode error, byte[] key, byte[] otherData)
			: base(name, RecordType.TKey, RecordClass.Any, 0)
		{
			Algorithm = algorithm;
			Inception = inception;
			Expiration = expiration;
			Mode = mode;
			Error = error;
			Key = key ?? new byte[] { };
			OtherData = otherData ?? new byte[] { };
		}
Пример #12
0
        public DataReaderMarshaler(object[] dataValues, SampleInfo[] sampleInfos, ref int maxSamples, ref ReturnCode result)
        {
            dataValueHandle = GCHandle.Alloc(dataValues, GCHandleType.Normal);
            dataValuesPtr = GCHandle.ToIntPtr(dataValueHandle);
            dataValuesPtrCache = dataValuesPtr;

            sampleInfoHandle = GCHandle.Alloc(sampleInfos, GCHandleType.Normal);
            sampleInfosPtr = GCHandle.ToIntPtr(sampleInfoHandle);
            sampleInfosPtrCache = sampleInfosPtr;

            result = validateParameters(dataValues, sampleInfos, ref maxSamples);
        }
Пример #13
0
		public TSigRecord(string name, TSigAlgorithm algorithm, DateTime timeSigned, TimeSpan fudge, ushort originalID, ReturnCode error, byte[] otherData, byte[] keyData)
			: base(name, RecordType.TSig, RecordClass.Any, 0)
		{
			Algorithm = algorithm;
			TimeSigned = timeSigned;
			Fudge = fudge;
			OriginalMac = new byte[] { };
			OriginalID = originalID;
			Error = error;
			OtherData = otherData ?? new byte[] { };
			KeyData = keyData;
		}
Пример #14
0
        private static string GetMessageText(ReturnCode returnCode)
        {
            string enumName = Enum.GetName(returnCode.GetType(), returnCode);
            string resourceName = string.Format("ReturnCode{0}", enumName);
            string message = Resources.ResourceManager.GetString(resourceName);

            if (string.IsNullOrEmpty(message)) {
                message = enumName;
            }

            return message;
        }
Пример #15
0
        internal Response(byte[] message)
        {
            byte flags1 = message[2];
            byte flags2 = message[3];

            int returnCode = flags2 & 15;

            if (returnCode > 6) returnCode = 6;
            _returnCode = (ReturnCode)returnCode;

            _authoritativeAnswer = ((flags1 & 4) != 0);
            _recursionAvailable = ((flags2 & 128) != 0);
            _truncated = ((flags1 & 2) != 0);

            int _questionsCount = GetShort(message, 4);
            _questions = new List<Query>();
            int _answersCount = GetShort(message, 6);
            _answers = new List<Answer>();
            int _nameServersCount = GetShort(message, 8);
            _nameServers = new List<NameServer>();
            int _additionalRecordsCount = GetShort(message, 10);
            _additionalRecords = new List<AdditionalRecord>();

            SmartPointer pointer = new SmartPointer(message, 12);

            for (int i = 0; i < _questionsCount; i++)
            {
                try
                {
                    _questions.Add(new Query(pointer));
                }
                catch
                {
                    throw new Exception("Invalid Response");
                }
            }

            for (int i = 0; i < _answersCount; i++)
            {
                _answers.Add(new Answer(pointer));
            }

            for (int i = 0; i < _nameServersCount; i++)
            {
                _nameServers.Add(new NameServer(pointer));
            }

            for (int i = 0; i < _additionalRecordsCount; i++)
            {
                _additionalRecords.Add(new AdditionalRecord(pointer));
            }
        }
Пример #16
0
     void reportResultCode(ReturnCode code)
     {
         string msg;
 
         switch ( code ) {
             case ReturnCode.Ok:
                 msg = "result is OK";
                 break;
             case ReturnCode.Error:
                 msg = "result is ERROR";
                 break;
             case ReturnCode.Unsupported:
                 msg = "result is UNSUPPORTED";
                 break;
             case ReturnCode.BadParameter:
                 msg = "result is BAD_PARAMETER";
                 break;
             case ReturnCode.PreconditionNotMet:
                 msg = "result is PRECONDITION_NOT_MET";
                 break;
             case ReturnCode.OutOfResources:
                 msg = "result is OUT_OF_RESOURCES";
                 break;
             case ReturnCode.NotEnabled:
                 msg = "result is NOT_ENABLED";
                 break;
             case ReturnCode.ImmutablePolicy:
                 msg = "result is IMMUTABLE_POLICY";
                 break;
             case ReturnCode.InconsistentPolicy:
                 msg = "result is INCONSISTENT_POLICY";
                 break;
             case ReturnCode.AlreadyDeleted:
                 msg = "result is ALREADY_DELETED";
                 break;
             case ReturnCode.Timeout:
                 msg = "result is TIMEOUT";
                 break;
             case ReturnCode.NoData:
                 msg = "result is NO_DATA";
                 break;
             default:
                 msg = "result is UNKNOWN";
                 break;
         }
 
         tfw.TestMessage(TestMessage.Note, msg);
     }
Пример #17
0
        /// <summary>
        /// Throws an <see cref="SpssException"/> if a prior call into SPSS failed.
        /// </summary>
        /// <param name="returnCode">The return code actually received from the SPSS function.</param>
        /// <param name="spssFunctionName">Name of the SPSS function invoked.</param>
        /// <param name="acceptableReturnCodes">The acceptable return codes that should not result in a thrown exception (SPSS_OK is always ok).</param>
        /// <returns>The value of <paramref name="returnCode"/>.</returns>
        internal static ReturnCode ThrowOnFailure(ReturnCode returnCode, string spssFunctionName, params ReturnCode[] acceptableReturnCodes)
        {
            if (returnCode == ReturnCode.SPSS_OK)
            {
                return returnCode;
            }

            if (acceptableReturnCodes != null)
            {
                if (Array.IndexOf(acceptableReturnCodes, returnCode) >= 0)
                {
                    return returnCode;
                }
            }
            throw new SpssException(returnCode, spssFunctionName);
        }
Пример #18
0
        /// <summary>
        /// Erstellt einen neuen Datensatz mit den übergebenen Eigenschaften.
        /// Wird ein Fehler zurückgegeben (ReturnCode != noError) so ist ein null Datensatz erstellt worden,
        /// welcher gelöscht werden sollte.
        /// </summary>
        /// <param name="benutzer">Benutzername</param>
        /// <param name="passw">Passwort</param>
        /// <param name="webs">Webseite der Zugangsdaten oder Pfad zur User-Datei</param>
        /// <param name="detail">Zusätzliche Infos (optional)</param>
        /// <param name="code">Rückgabe des ReturnCode</param>
        public Data(string benutzer, Passw passw, string webs, string detail, out ReturnCode code)
        {
            code = ReturnCode.noError;
            if (Benutzer.CheckBenutzername(benutzer) == true) code = ReturnCode.BenutzernameUngültig;
            Program.stopw.Restart();
            if (Passw.CheckPasswort(passw.Passwort, passw.PasswortEigenschaften) == true) code = ReturnCode.PasswortUngültig;
            Program.stopw.Stop();
            if (webs == null) code = ReturnCode.missingParameter;

            if (code == ReturnCode.noError)
            {
                this.benutzername = benutzer;
                this.passwort = passw;
                this.pfad = webs;
                this.details = detail;
            }
        }
Пример #19
0
		public AniDBResponse(byte[] responseData, Encoding encoding = null)
		{
			OriginalString = (encoding ?? Encoding.ASCII).GetString(responseData);

			string[] responseLines = OriginalString.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

			short returnCode;

			string[] response =
				responseLines[0].Split(new[] { ' ' }, short.TryParse(responseLines[0].Split(' ')[0], out returnCode) ? 2 : 3);

			Tag = response.Length == 3 ? response[0] : "";
			Code = (ReturnCode)(response.Length == 3 ? short.Parse(response[1]) : returnCode);
			ReturnString = response.Length == 3 ? response[2] : response[1];

			List<string[]> datafields = new List<string[]>();

			for (int i = 1; i < responseLines.Length; i++)
				datafields.Add(responseLines[i].Split('|'));

			DataFields = datafields.ToArray();
		}
Пример #20
0
        public void OnDataAvailable(IDataReader entityInterface)
        {
            Msg[] msgList = null ;
            SampleInfo[] infoSeq = null;
        
            status = msgDR.Read(ref msgList, ref infoSeq, Length.Unlimited, SampleStateKind.Any, ViewStateKind.New, InstanceStateKind.Any);
            ErrorHandler.checkStatus(status, "DataReader.Read");

            if (msgList != null && msgList.Length > 0)
            {
                Console.WriteLine("=== [ListenerDataListener::OnDataAvailable] - msgList.Length : {0}", msgList.Length);
                foreach (Msg msg in msgList)
                {
                    Console.WriteLine("    --- Message Received ---");
                    Console.WriteLine("    userId : {0}", msg.userID);
                    Console.WriteLine("    message : \\ {0}",msg.message);
                }
                status = msgDR.ReturnLoan(ref msgList, ref infoSeq);
                ErrorHandler.checkStatus(status, "DataReader.ReturnLoan");
            }
            guardCond.SetTriggerValue(true);
        }
Пример #21
0
        public static ReturnCode CorrectZipFile(RvFile fixZip, RvFile fixZippedFile, ref ICompress tempFixZip, int iRom, List <RvFile> fileProcessQueue, out string errorMessage)
        {
            if (!
                (
                    fixZippedFile.DatStatus == DatStatus.InDatCollect && fixZippedFile.GotStatus == GotStatus.Got ||
                    fixZippedFile.DatStatus == DatStatus.InDatMerged && fixZippedFile.GotStatus == GotStatus.Got ||
                    fixZippedFile.DatStatus == DatStatus.NotInDat && fixZippedFile.GotStatus == GotStatus.Got ||
                    fixZippedFile.DatStatus == DatStatus.InToSort && fixZippedFile.GotStatus == GotStatus.Got ||
                    fixZippedFile.DatStatus == DatStatus.InToSort && fixZippedFile.GotStatus == GotStatus.Corrupt
                )
                )
            {
                ReportError.SendAndShow("Error in Fix Rom Status " + fixZippedFile.RepStatus + " : " + fixZippedFile.DatStatus + " : " + fixZippedFile.GotStatus);
            }

            ReportError.LogOut("CorrectZipFile:");
            ReportError.LogOut(fixZippedFile);

            if (fixZippedFile.GotStatus == GotStatus.Corrupt && fixZippedFile.FileType == FileType.SevenZipFile)
            {
                fixZippedFile.GotStatus = GotStatus.NotGot; // Changes RepStatus to Deleted
                errorMessage            = "";
                return(ReturnCode.Good);
            }

            if (tempFixZip == null)
            {
                string     strPath         = fixZip.Parent.FullName;
                string     tempZipFilename = Path.Combine(strPath, "__RomVault.tmp");
                ReturnCode returnCode1     = OpenOutputZip(fixZip, tempZipFilename, out tempFixZip, out errorMessage);
                if (returnCode1 != ReturnCode.Good)
                {
                    ReportError.LogOut($"CorrectZipFile: OutputOutput {tempZipFilename} return {returnCode1}");
                    return(returnCode1);
                }
            }

            bool rawCopyForce = fixZippedFile.RepStatus == RepStatus.InToSort || fixZippedFile.RepStatus == RepStatus.Corrupt;

            RvFile        fileIn         = fixZip.Child(iRom);
            List <RvFile> lstFixRomTable = null;

            if (fileIn.FileType == FileType.SevenZipFile && fileIn.Size > 0)
            {
                lstFixRomTable = FindSourceFile.GetFixFileList(fixZippedFile);
                ReportError.LogOut("CorrectZipFile: picking from");
                ReportError.ReportList(lstFixRomTable);

                fileIn = FindSourceFile.FindSourceToUseForFix(fixZippedFile, lstFixRomTable);

                if (fileIn.FileType == FileType.SevenZipFile)
                {
                    ReturnCode returnCode1 = Decompress7ZipFile.DecompressSource7ZipFile(fixZip, true, out errorMessage);
                    if (returnCode1 != ReturnCode.Good)
                    {
                        ReportError.LogOut($"DecompressSource7Zip: OutputOutput {fixZip.FileName} return {returnCode1}");
                        return(returnCode1);
                    }

                    lstFixRomTable = FindSourceFile.GetFixFileList(fixZippedFile);
                    fileIn         = FindSourceFile.FindSourceToUseForFix(fixZippedFile, lstFixRomTable);
                }
            }

            ReportError.LogOut("Copying from");
            ReportError.LogOut(fileIn);

            GetSourceDir(fileIn, out string sourceDir, out string sourceFile);

            if (Settings.rvSettings.DetailedFixReporting)
            {
                string fixZipFullName = fixZip.TreeFullName;

                bool rawCopy = FixFileUtils.TestRawCopy(fileIn, fixZippedFile, rawCopyForce);
                Report.ReportProgress(new bgwShowFix(Path.GetDirectoryName(fixZipFullName), Path.GetFileName(fixZipFullName), fixZippedFile.Name, fixZippedFile.Size, rawCopy ? "<<--Raw" : "<<--Compress", sourceDir, sourceFile, fileIn.Name));
            }

            RepStatus  originalStatus = fixZippedFile.RepStatus;
            ReturnCode returnCode     = FixFileUtils.CopyFile(fileIn, tempFixZip, null, fixZippedFile, rawCopyForce, out errorMessage);

            switch (returnCode)
            {
            case ReturnCode.Good:     // correct reply to continue;
                if (originalStatus == RepStatus.NeededForFix)
                {
                    fixZippedFile.RepStatus = RepStatus.NeededForFix;
                }
                break;

            case ReturnCode.SourceDataStreamCorrupt:
            {
                ReportError.LogOut($"CorrectZipFile: Source Data Stream Corrupt /  CRC Error");
                Report.ReportProgress(new bgwShowFixError("CRC Error"));
                RvFile tFile = fixZip.Child(iRom);
                tFile.GotStatus = GotStatus.Corrupt;
                break;
            }

            case ReturnCode.SourceCheckSumMismatch:
            {
                ReportError.LogOut($"CorrectZipFile: Source Checksum Mismatch / Fix file CRC was not as expected");
                Report.ReportProgress(new bgwShowFixError("Fix file CRC was not as expected"));
                break;
            }

            case ReturnCode.Cancel:
                return(returnCode);

            default:
                throw new FixAZip.ZipFileException(returnCode, fixZippedFile.FullName + " " + fixZippedFile.RepStatus + " " + returnCode + " : " + errorMessage);
            }

            // This should not be done here, as you land up marking files that are being
            // copied that are still set to needed for fix to delete status
            //Check to see if the files used for fix, can now be set to delete
            //if (lstFixRomTable != null)
            //    FixFileUtils.CheckFilesUsedForFix(lstFixRomTable, fileProcessQueue, false);

            return(returnCode);
        }
Пример #22
0
        /// <summary>
        /// Fixed a missing file inside a .ZIP file.
        /// </summary>
        /// <param name="fixZip">The RvFile of the actual .ZIP file that is being fixed.</param>
        /// <param name="fixZippedFile">A temp copy of the RvFile record of the actual compressed file inside the fixZip .zip that is about to be fixed.</param>
        /// <param name="tempFixZip">Is the new output archive file that is being created to fix this zip, that will become the new zip once done</param>
        /// <param name="filesUserForFix"></param>
        /// <param name="totalFixed"></param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>

        public static ReturnCode CanBeFixed(RvFile fixZip, RvFile fixZippedFile, ref ICompress tempFixZip, Dictionary <string, RvFile> filesUserForFix, ref int totalFixed, out string errorMessage)
        {
            if (!(fixZippedFile.DatStatus == DatStatus.InDatCollect && (fixZippedFile.GotStatus == GotStatus.NotGot || fixZippedFile.GotStatus == GotStatus.Corrupt)))
            {
                ReportError.SendAndShow("Error in Fix Rom Status " + fixZippedFile.RepStatus + " : " + fixZippedFile.DatStatus + " : " + fixZippedFile.GotStatus);
            }

            ReportError.LogOut("CanBeFixed:");
            ReportError.LogOut(fixZippedFile);

            if (tempFixZip == null)
            {
                string     strPath         = fixZip.Parent.FullName;
                string     tempZipFilename = Path.Combine(strPath, "__RomVault.tmp");
                ReturnCode returnCode1     = OpenOutputZip(fixZip, tempZipFilename, out tempFixZip, out errorMessage);
                if (returnCode1 != ReturnCode.Good)
                {
                    ReportError.LogOut($"CanBeFixed: OutputOutput {tempZipFilename} return {returnCode1}");
                    return(returnCode1);
                }
            }

            List <RvFile> lstFixRomTable = FindSourceFile.GetFixFileList(fixZippedFile);

            ReportError.LogOut("CanBeFixed: picking from");
            ReportError.ReportList(lstFixRomTable);

            if (DBHelper.IsZeroLengthFile(fixZippedFile))
            {
                RvFile fileIn = new RvFile(FileType.ZipFile)
                {
                    Size = 0
                };
                ReturnCode returnCode = FixFileUtils.CopyFile(fileIn, tempFixZip, null, fixZippedFile, false, out errorMessage);

                switch (returnCode)
                {
                case ReturnCode.Good:     // correct reply to continue;
                    break;

                case ReturnCode.Cancel:
                    return(returnCode);

                default:
                    throw new FixAZip.ZipFileException(returnCode, fixZippedFile.FullName + " " + fixZippedFile.RepStatus + " " + returnCode + " : " + errorMessage);
                }

                //Check to see if the files used for fix, can now be set to delete
                //FixFileUtils.CheckFilesUsedForFix(lstFixRomTable, filesUserForFix, false);
                foreach (RvFile f in lstFixRomTable)
                {
                    string fn = f.TreeFullName;
                    if (!filesUserForFix.ContainsKey(fn))
                    {
                        filesUserForFix.Add(fn, f);
                    }
                }
                totalFixed++;

                return(ReturnCode.Good);
            }

            if (lstFixRomTable.Count > 0)
            {
                RvFile fileIn = FindSourceFile.FindSourceToUseForFix(fixZippedFile, lstFixRomTable);

                if (fileIn.FileType == FileType.SevenZipFile)
                {
                    ReturnCode returnCode1 = Decompress7ZipFile.DecompressSource7ZipFile(fileIn.Parent, false, out errorMessage);
                    if (returnCode1 != ReturnCode.Good)
                    {
                        ReportError.LogOut($"DecompressSource7Zip: OutputOutput {fixZip.FileName} return {returnCode1}");
                        return(returnCode1);
                    }
                    lstFixRomTable = FindSourceFile.GetFixFileList(fixZippedFile);
                    fileIn         = FindSourceFile.FindSourceToUseForFix(fixZippedFile, lstFixRomTable);
                }

                ReportError.LogOut("CanBeFixed: Copying from");
                ReportError.LogOut(fileIn);

                GetSourceDir(fileIn, out string sourceDir, out string sourceFile);

                string fixZipFullName = fixZip.TreeFullName;

                bool rawCopy = FixFileUtils.TestRawCopy(fileIn, fixZippedFile, false);
                Report.ReportProgress(new bgwShowFix(Path.GetDirectoryName(fixZipFullName), Path.GetFileName(fixZipFullName), fixZippedFile.Name, fixZippedFile.Size, rawCopy ? "<--Raw" : "<--Compress", sourceDir, sourceFile, fileIn.Name));

                fixZippedFile.FileTestFix(fileIn);

                ReturnCode returnCode = FixFileUtils.CopyFile(fileIn, tempFixZip, null, fixZippedFile, false, out errorMessage);
                switch (returnCode)
                {
                case ReturnCode.Good:     // correct reply so continue;
                    break;

                case ReturnCode.RescanNeeded:
                    ReportError.LogOut($"CanBeFixed: RescanNeeded");
                    return(returnCode);

                case ReturnCode.SourceDataStreamCorrupt:
                {
                    ReportError.LogOut($"CanBeFixed: Source Data Stream Corrupt /  CRC Error");
                    Report.ReportProgress(new bgwShowFixError("CRC Error"));
                    fileIn.GotStatus = GotStatus.Corrupt;
                    return(returnCode);
                }

                case ReturnCode.SourceCheckSumMismatch:
                {
                    ReportError.LogOut($"CanBeFixed: Source Checksum Mismatch / Fix file CRC was not as expected");
                    Report.ReportProgress(new bgwShowFixError("Fix file CRC was not as expected"));
                    return(returnCode);
                }

                case ReturnCode.DestinationCheckSumMismatch:
                {
                    ReportError.LogOut($"CanBeFixed: Destination Checksum Mismatch / Destination file CRC was not as expected");
                    Report.ReportProgress(new bgwShowFixError("Destination file CRC was not as expected"));
                    return(returnCode);
                }

                case ReturnCode.Cancel:
                    return(returnCode);

                default:
                    throw new FixAZip.ZipFileException(returnCode, fixZippedFile.FullName + " " + fixZippedFile.RepStatus + " " + returnCode + Environment.NewLine + errorMessage);
                }

                //Check to see if the files used for fix, can now be set to delete
                //FixFileUtils.CheckFilesUsedForFix(lstFixRomTable, filesUserForFix, false);
                foreach (RvFile f in lstFixRomTable)
                {
                    string fn = f.TreeFullName;
                    if (!filesUserForFix.ContainsKey(fn))
                    {
                        filesUserForFix.Add(fn, f);
                    }
                }
                totalFixed++;
            }
            else
            // thought we could fix it, turns out we cannot
            {
                fixZippedFile.GotStatus = GotStatus.NotGot;
            }
            errorMessage = "";
            return(ReturnCode.Good);
        }
Пример #23
0
        public static ReturnCode MovetoSort(RvFile fixZip, RvFile fixZippedFile, ref RvFile toSortGame, ref ICompress toSortZipOut, int iRom)
        {
            if (!(fixZippedFile.DatStatus == DatStatus.NotInDat && fixZippedFile.GotStatus == GotStatus.Got))
            {
                ReportError.SendAndShow("Error in Fix Rom Status " + fixZippedFile.RepStatus + " : " + fixZippedFile.DatStatus + " : " + fixZippedFile.GotStatus);
            }

            ReportError.LogOut("MovetoSort:");
            ReportError.LogOut(fixZippedFile);
            // move the rom out to the To Sort Directory

            string toSortFullName;

            if (toSortGame == null)
            {
                ReturnCode retCode = FixFileUtils.CreateToSortDirs(fixZip, out RvFile outDir, out string toSortFileName);
                if (retCode != ReturnCode.Good)
                {
                    return(retCode);
                }

                toSortGame = new RvFile(fixZip.FileType)
                {
                    Parent    = outDir,
                    Name      = toSortFileName,
                    DatStatus = DatStatus.InToSort,
                    GotStatus = GotStatus.Got
                };
                toSortFullName = Path.Combine(outDir.FullName, toSortGame.Name);
            }
            else
            {
                toSortFullName = toSortZipOut.ZipFilename;
            }

            // this needs header / alt info added.
            RvFile toSortRom = new RvFile(fixZippedFile.FileType)
            {
                Name           = fixZippedFile.Name,
                Size           = fixZippedFile.Size,
                CRC            = fixZippedFile.CRC,
                SHA1           = fixZippedFile.SHA1,
                MD5            = fixZippedFile.MD5,
                HeaderFileType = fixZippedFile.HeaderFileType,
                AltSize        = fixZippedFile.AltSize,
                AltCRC         = fixZippedFile.AltCRC,
                AltSHA1        = fixZippedFile.AltSHA1,
                AltMD5         = fixZippedFile.AltMD5,
                FileGroup      = fixZippedFile.FileGroup
            };

            toSortRom.SetStatus(DatStatus.InToSort, GotStatus.Got);
            toSortRom.FileStatusSet(
                FileStatus.HeaderFileTypeFromHeader |
                FileStatus.SizeFromHeader | FileStatus.SizeVerified |
                FileStatus.CRCFromHeader | FileStatus.CRCVerified |
                FileStatus.SHA1FromHeader | FileStatus.SHA1Verified |
                FileStatus.MD5FromHeader | FileStatus.MD5Verified |
                FileStatus.AltSizeFromHeader | FileStatus.AltSizeVerified |
                FileStatus.AltCRCFromHeader | FileStatus.AltCRCVerified |
                FileStatus.AltSHA1FromHeader | FileStatus.AltSHA1Verified |
                FileStatus.AltMD5FromHeader | FileStatus.AltMD5Verified
                , fixZippedFile);

            toSortGame.ChildAdd(toSortRom);

            ReturnCode returnCode;
            string     errorMessage;

            if (toSortZipOut == null)
            {
                returnCode = OpenOutputZip(toSortGame, toSortFullName, out toSortZipOut, out errorMessage);
                if (returnCode != ReturnCode.Good)
                {
                    throw new FixAZip.ZipFileException(returnCode, fixZippedFile.FullName + " " + fixZippedFile.RepStatus + " " + returnCode + Environment.NewLine + errorMessage);
                }
            }


            string fixZipFullName = fixZip.TreeFullName;

            Report.ReportProgress(new bgwShowFix(Path.GetDirectoryName(fixZipFullName), Path.GetFileName(fixZipFullName), fixZippedFile.Name, fixZippedFile.Size, "Raw-->", Path.GetDirectoryName(toSortFullName), Path.GetFileName(toSortFullName), toSortRom.Name));

            returnCode = FixFileUtils.CopyFile(fixZip.Child(iRom), toSortZipOut, null, toSortRom, true, out errorMessage);
            switch (returnCode)
            {
            case ReturnCode.Good:     // correct reply to continue;
                break;

            default:
                throw new FixAZip.ZipFileException(returnCode, fixZippedFile.FullName + " " + fixZippedFile.RepStatus + " " + returnCode + Environment.NewLine + errorMessage);
            }
            fixZippedFile.GotStatus = GotStatus.NotGot; // Changes RepStatus to Deleted

            return(ReturnCode.Good);
        }
Пример #24
0
        public IDataReader CreateDataReader(
            ITopicDescription topic,
            IDataReaderListener listener,
            StatusKind mask)
        {
            DataReader dataReader = null;

            if (topic != null)
            {
                SacsSuperClass superObj = (SacsSuperClass)topic;

                if (listener != null)
                {
                    OpenSplice.Gapi.gapi_dataReaderListener gapiListener;
                    DataReaderListenerHelper listenerHelper = new DataReaderListenerHelper();
                    listenerHelper.Listener = listener;
                    listenerHelper.CreateListener(out gapiListener);
                    using (DataReaderListenerMarshaler listenerMarshaler =
                               new DataReaderListenerMarshaler(ref gapiListener))
                    {
                        IntPtr gapiPtr = Gapi.Subscriber.create_datareader(
                            GapiPeer,
                            superObj.GapiPeer,
                            IntPtr.Zero,
                            listenerMarshaler.GapiPtr,
                            mask);
                        if (gapiPtr != IntPtr.Zero)
                        {
                            TypeSupport typeSupport = topic.Participant.GetTypeSupport(topic.TypeName)
                                                      as OpenSplice.TypeSupport;
                            dataReader = typeSupport.CreateDataReader(gapiPtr);
                            dataReader.SetListener(listenerHelper);
                        }
                    }
                }
                else
                {
                    IntPtr gapiPtr = Gapi.Subscriber.create_datareader(
                        GapiPeer,
                        superObj.GapiPeer,
                        IntPtr.Zero,
                        IntPtr.Zero,
                        StatusKind.Any);
                    if (gapiPtr != IntPtr.Zero)
                    {
                        TypeSupport typeSupport = topic.Participant.GetTypeSupport(topic.TypeName)
                                                  as OpenSplice.TypeSupport;
                        dataReader = typeSupport.CreateDataReader(gapiPtr);
                    }
                }
            }

            if (dataReader != null)
            {
                SubscriberQos subQos = null;
                ReturnCode    result = GetQos(ref subQos);
                if (result == ReturnCode.Ok)
                {
                    if (subQos.EntityFactory.AutoenableCreatedEntities)
                    {
                        dataReader.Enable();
                    }
                }
            }

            return(dataReader);
        }
Пример #25
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="strOperation">Requested operation that failed</param>
 /// <param name="theReturn">ANT-FS Library return code</param>
 internal ANTFS_RequestFailed_Exception(string strOperation, ReturnCode theReturn) : base(strOperation + " Request Failed: " + Print.AsString(theReturn))
 {
 }
        internal override bool CheckError(PlayerOperationCode operationCode, Dictionary <byte, object> parameters, ReturnCode returnCode, string operationMessage, out string errorMessage)
        {
            if (!base.CheckError(operationCode, parameters, returnCode, operationMessage, out errorMessage))
            {
                switch (returnCode)
                {
                case ReturnCode.InvalidOperation:
                    subject.ResponseManager.FindOpponentFailed();
                    return(true);

                default:
                    return(false);
                }
            }
            else
            {
                return(true);
            }
        }
Пример #27
0
 internal override void SendResponse(PlayerOperationCode operationCode, ReturnCode returnCode, string operationMessage, Dictionary <byte, object> parameter)
 {
     subject.ResponseManager.SendResponse(operationCode, returnCode, operationMessage, parameter);
 }
Пример #28
0
        public override void SampleCall(string[] args)
        {
            #region Parse Arguments
            ArgParser cmdLineParser = new ArgParser();
            if (!cmdLineParser.Parse(args))
            {
                // Parse failed.
                PrintUsage(INVALID_ARGUMENTS_ERROR);
                return;
            }
            if (!SampleParseArgs(cmdLineParser))
            {
                // Parse failed for sample's arguments.
                PrintUsage(INVALID_ARGUMENTS_ERROR);
                return;
            }
            #endregion

            #region Initialize properties from command line
            // Initialize the properties.
            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);
            // Uncomment the line below if you wish to send using a non-blocking mode
            // sessionProps.SendBlocking = false;
            #endregion

            // Define IContext and ISession.
            IContext context = null;
            ISession session = null;

            // Create the LinkedList.
            LinkedList <MessageRecord> msgRecords =
                new LinkedList <MessageRecord>();

            try
            {
                InitContext(cmdLineParser.LogLevel);
                Console.WriteLine("About to create the context ...");
                context = ContextFactory.Instance.CreateContext(contextProps, null);
                Console.WriteLine("Context successfully created. ");
                Console.WriteLine("About to create the session ...");
                session = context.CreateSession(sessionProps,
                                                SampleUtils.HandleMessageEvent,
                                                HandleSessionEvent);
                Console.WriteLine("Session successfully created.");

                // Connect the session.
                Console.WriteLine("About to connect the session ...");
                if (session.Connect() == ReturnCode.SOLCLIENT_OK)
                {
                    Console.WriteLine("Session successfully connected");
                    Console.WriteLine(GetRouterInfo(session));
                }

                // Validate required capabilities.
                if (!session.IsCapable(CapabilityType.PUB_GUARANTEED))
                {
                    Console.WriteLine(string.Format("This sample requires capability '{0}' to be supported", CapabilityType.PUB_GUARANTEED));
                    return;
                }

                // Send cmdLineParser.Config.NumberOfMessagesToPublish messages.
                for (int i = 0; i < cmdLineParser.Config.NumberOfMessagesToPublish; i++)
                {
                    // Allocate a new message.
                    IMessage message = SampleUtils.CreateMessage(cmdLineParser.Config, session);
                    message.DeliveryMode = MessageDeliveryMode.Persistent;
                    try
                    {
                        // Create a record, and set it as CorrelationKey.
                        MessageRecord msgRecord = new MessageRecord(message);
                        message.CorrelationKey = msgRecord;
                        ReturnCode rc = session.Send(message);
                        Console.WriteLine("Sending message " + i + ": " + rc);
                        if (rc == ReturnCode.SOLCLIENT_OK)
                        {
                            // Add it to the list of send message records and send it.
                            msgRecord.MessageId = i;
                            msgRecords.AddLast(msgRecord);
                        }
                        else
                        {
                            // The message was not sent, free it up
                            message.Dispose();
                        }
                    }
                    catch (OperationErrorException opex)
                    {
                        // Ignore OperationErrorException if you don't want the publisher
                        // to abort on transient send errors
                        Console.WriteLine("Got an excpetion " + opex.ReturnCode);
                        message.Dispose();
                        continue;
                    }
                    // Sleep for 500 msecs and check to see if the message was acknowledged (positively or negatively).
                    Thread.Sleep(100);
                    while (msgRecords.First != null && msgRecords.First.Value.Acked)
                    {
                        MessageRecord record = msgRecords.First.Value;
                        msgRecords.RemoveFirst();
                        Console.WriteLine(
                            string.Format("Freeing memory for message {0}, Result: Acked ({1}), Accepted ({2})\n",
                                          record.MessageId, record.Acked, record.Accepted));
                        record.Message.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                Thread.Sleep(3000);
                // There should not be any left in the list, but just in case.
                foreach (MessageRecord record in msgRecords)
                {
                    Console.WriteLine(
                        string.Format("Freeing memory for message {0}, Result: Acked ({1}), Accepted ({2})\n",
                                      record.MessageId, record.Acked, record.Accepted));
                    record.Message.Dispose();
                }
                if (session != null)
                {
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }
Пример #29
0
        internal static ReturnCode checkQos(DataReaderQos o)
        {
            ReturnCode result = DDS.ReturnCode.BadParameter;

            if (o != null)
            {
                int errorCount = 0;
                errorCount += countErrors(o.Durability);
                errorCount += countErrors(o.Deadline);
                errorCount += countErrors(o.LatencyBudget);
                errorCount += countErrors(o.Liveliness);
                errorCount += countErrors(o.Reliability);
                errorCount += countErrors(o.DestinationOrder);
                errorCount += countErrors(o.History);
                errorCount += countErrors(o.ResourceLimits);
                errorCount += countErrors(o.UserData);
                errorCount += countErrors(o.Ownership);
                errorCount += countErrors(o.TimeBasedFilter);
                errorCount += countErrors(o.ReaderDataLifecycle);
                errorCount += countErrors(o.SubscriptionKeys);
                errorCount += countErrors(o.ReaderLifespan);
                errorCount += countErrors(o.Share);
                if (errorCount == 0)
                {
                    result = DDS.ReturnCode.Ok;
                    if ((o.History.Kind == HistoryQosPolicyKind.KeepLastHistoryQos) &&
                        (o.ResourceLimits.MaxSamplesPerInstance != Length.Unlimited) &&
                        (o.History.Depth > o.ResourceLimits.MaxSamplesPerInstance))
                    {
                        ReportStack.Report(result,
                                           "HistoryQosPolicy.depth is greater than " +
                                           "ResourceLimitsQosPolicy.max_samples_per_instance.");
                        result = DDS.ReturnCode.InconsistentPolicy;
                    }
                    if ((o.Deadline.Period.Sec < o.TimeBasedFilter.MinimumSeparation.Sec) ||
                        ((o.Deadline.Period.Sec == o.TimeBasedFilter.MinimumSeparation.Sec) &&
                         (o.Deadline.Period.NanoSec < o.TimeBasedFilter.MinimumSeparation.NanoSec)))
                    {
                        ReportStack.Report(result,
                                           "DeadlineQosPolicy.period is less than " +
                                           "TimeBasedFilterQosPolicy.separation");
                        result = DDS.ReturnCode.InconsistentPolicy;
                    }
                    if (o.ReaderDataLifecycle.EnableInvalidSamples != true)
                    {
                        //TODO: add correct deprecated report
                        if (o.ReaderDataLifecycle.InvalidSampleVisibility.Kind != InvalidSampleVisibilityQosPolicyKind.MinimumInvalidSamples)
                        {
                            ReportStack.Report(result,
                                               "ReaderDataLifecycle.InvalidSampleVisibility.Kind inconsistent with " +
                                               "InvalidSampleVisibilityQosPolicyKind.invalid_sample_visibility.");
                            result = DDS.ReturnCode.InconsistentPolicy;
                        }
                    }
                    if (o.ReaderDataLifecycle.InvalidSampleVisibility.Kind == InvalidSampleVisibilityQosPolicyKind.AllInvalidSamples)
                    {
                        ReportStack.Report(result,
                                           "ReaderDataLifecycle.InvalidSampleVisibility.kind 'ALL_INVALID_SAMPLES' is unsupported.");
                        result = DDS.ReturnCode.Unsupported; // See OSPL-433
                    }
                }
            }
            else
            {
                ReportStack.Report(result,
                                   "DataReaderQos 'null' is invalid.");
            }
            return(result);
        }
Пример #30
0
        /// <summary>
        /// Creates a Subscriber
        /// </summary>
        public void createSubscriber()
        {
            status = participant.GetDefaultSubscriberQos(ref subQos);
            ErrorHandler.checkStatus(status, "DomainParticipant.GetDefaultSubscriberQos");

            subQos.Partition.Name = new String[1];
            subQos.Partition.Name[0] = partitionName;
            subscriber = participant.CreateSubscriber(
                    subQos, null, StatusKind.Any);
            ErrorHandler.checkHandle(subscriber, "DomainParticipant.CreateSubscriber");
        }
Пример #31
0
        /// <summary>
        /// Creates a DataReader
        /// </summary>
        /// <param name="exampleNameToCreateReaderFor">The example name to create the
        /// DataReader for. This param is used to define any specific Qos values the 
        /// example requires.</param>
        /// <param name="filtered">This param determines whether a reader will be created
        /// for a normal or filtered topic.</param>
        public void createReader(Boolean filtered)
        {
            status = subscriber.GetDefaultDataReaderQos(ref RQosH);
            ErrorHandler.checkStatus(status, "Subscriber.GetDefaultDataReaderQoS");
            status = subscriber.CopyFromTopicQos(ref RQosH, topicQos);
            ErrorHandler.checkStatus(status, "Subscriber.CopyFromTopicQoS");

            switch (exampleName)
            {                
                case "ContentFilteredTopic": 
                case "Listener":
                    RQosH.Durability.Kind = DurabilityQosPolicyKind.TransientDurabilityQos;                    
                    break;
                case "Durability":
                    if (durabilityKind.Equals("transient"))
                        RQosH.Durability.Kind = DurabilityQosPolicyKind.TransientDurabilityQos;
                    else
                        RQosH.Durability.Kind = DurabilityQosPolicyKind.PersistentDurabilityQos;

                    break;
                case "HelloWorld":
                case "Ownership":
                case "WaitSet":
                case "QueryCondition":
                case "Lifecycle":
                    break;
                default:
                    break;
            }
            if (filtered)
            {
                reader = subscriber.CreateDataReader(
                        filteredTopic,
                        RQosH,
                        null,
                        StatusKind.Any);
            }
            else
            {
                reader = subscriber.CreateDataReader(
                        topic,
                        RQosH,
                        null,
                        StatusKind.Any);
            }
            ErrorHandler.checkHandle(reader, "Subscriber.CreateDataReader");
        }
Пример #32
0
        /// <summary>
        /// WitFXMT4ServerBL.onMT4Response
        /// </summary>
        private async Task OnResponseAsync(
            ReturnCode errorcode, string errormessage, eMT4ServerType serverIndex, MT4REQ reqType,
            eOrderStatus trans_status, int masterLogin, /*int orderOrLogin,*/ Guid server_trans_id,
            eAccountType accType, MT4REQMODE reqMode, MT4Request request, CancellationToken cancellationToken)
        {
            Debug.Assert(masterLogin > 0);
            //m_ptrMySqlWrapper.insertLog(Utilities.LOG_INFO,masterLogin,orderOrLogin,"X",)
            if (reqType == MT4REQ.MT4REQ_NEW_ACCOUNT)
            {
                var mt4Login = request.User?.login ?? 0;

                if (trans_status == eOrderStatus.ORD_STAT_EXECUTED)
                {
                    Debug.Assert(mt4Login > 0);
                    m_ptrLogger.LogInfo($"EXECUTED : MT4 Account {mt4Login}, master Login {masterLogin}, AccountType: {accType}");
                    MT4Account acc = new MT4Account();
                    //memset(&acc, 0, sizeof(MT4Account));
                    acc._accountType    = accType;
                    acc._masterLogin    = masterLogin;
                    acc._mt4Login       = mt4Login;
                    acc._mt4ServerIndex = serverIndex;

                    //if (serverIndex == SRV_TYPE_DEMO)
                    //{
                    //    Demo.insertMT4Account(orderOrLogin);
                    //}
                    //else
                    //{
                    //    Live.insertMT4Account(orderOrLogin);
                    //}

                    lock (_mt4LoginsByServerIndex)
                        AddMt4LoginNoLock(serverIndex, mt4Login);

                    await _mt4AccountService.InsertMT4Account(acc, cancellationToken);

                    //if (!)
                    //{
                    //    m_ptrLogger.LogError("Unable to insert MT4 account for masterlogin: %d MT4 Login: %d in database", masterLogin, orderOrLogin);
                    //}
                    //else
                    //{

                    #region Rebate
                    //TODO: Claudia: rebate
                    //if (accType == ACC_TYPE_REBATE)
                    //{
                    //    Dictionary<int, int>.iterator it2;

                    //    //lock (m_SyncMapMt4Master)
                    //    //{

                    //    it2 = m_mapMasterRebateAcc.find(masterLogin);
                    //    if (it2 == m_mapMasterRebateAcc.end())
                    //    {
                    //        m_mapMasterRebateAcc.insert(new ValueTuple<int, int>(masterLogin, orderOrLogin));
                    //    }

                    //    //}
                    //}
                    #endregion

                    ////else //if (accType != ACC_TYPE_REBATE)
                    ////{
                    //Dictionary<bool, Dictionary<int, int>>.iterator it1;
                    ////Dictionary<int, int>.iterator it2;

                    ////lock (m_SyncMapMt4Master)
                    ////{

                    //bool isDemoServer = serverIndex == SRV_TYPE_DEMO ? true : false;
                    //it1 = m_mapMT4MasterLogin.find(isDemoServer);
                    //if (it1 == m_mapMT4MasterLogin.end())
                    //{
                    //    Dictionary<int, int> mp2 = new Dictionary<int, int>();
                    //    m_mapMT4MasterLogin.insert(new ValueTuple<bool, Dictionary<int, int>>(isDemoServer, mp2));
                    //    it1 = m_mapMT4MasterLogin.find(isDemoServer);
                    //}
                    //it1.second.insert(new ValueTuple<int, int>(orderOrLogin, masterLogin));



                    ////}
                    ////}
                    ////}


                    if (accType == eAccountType.ACC_TYPE_SSP)
                    {
                        await _signalService.UpdateSignalMT4Login(server_trans_id, mt4Login, cancellationToken);

                        await _signalService.UpdateSSPSignalMT4Login(server_trans_id, mt4Login, cancellationToken);

                        //fetchAllSignal();
                        //fetchAllSSPSignal();
                        //fetchAllSMSignal();
                        //insertDBTransmitData(masterLogin, FDMT_Signal_ID);
                        //insertDBTransmitData(masterLogin, FDMT_SSPSignal_ID);
                    }
                    else if (accType == eAccountType.ACC_TYPE_SM)
                    {
                        await _signalService.UpdateSignalMT4Login(server_trans_id, mt4Login, cancellationToken);

                        await _signalService.UpdateSMSignalMT4Login(server_trans_id, mt4Login, cancellationToken);

                        //fetchAllSignal();
                        //fetchAllSSPSignal();
                        //fetchAllSMSignal();

                        //insertDBTransmitData(masterLogin, FDMT_Signal_ID);
                        //insertDBTransmitData(masterLogin, FDMT_SMSignal_ID);
                    }

                    var m_masterUserSetting = await _masterSettingsService.GetCachedMasterSettingsAsync(cancellationToken);

                    if (accType == eAccountType.ACC_TYPE_FOLLOWER_DEMO || accType == eAccountType.ACC_TYPE_SSP || accType == eAccountType.ACC_TYPE_SM)
                    {
                        MT4Request ptrMT4Req4 = (MT4Request) new MT4Request();
                        //memset(ptrMT4Req4, 0, sizeof(MT4Request));
                        //ptrMT4Req4.newLoginOrOrderID = orderOrLogin; // Alexey
                        ptrMT4Req4.masterLogin = masterLogin;
                        ptrMT4Req4.reqType     = MT4REQ.MT4REQ_BALANCE;
                        //ptrMT4Req4.socketID = socketID;
                        ptrMT4Req4.status        = eOrderStatus.ORD_STAT_RECVD;
                        ptrMT4Req4.serverTransID = TransactionService.NewTransactionId();
                        ptrMT4Req4.ptrData       = new MT4OrderInfo();
                        //memset(ptrMT4Req4.ptrData, 0, sizeof(MT4OrderInfo));
                        MT4OrderInfo ptrOrd = (MT4OrderInfo)ptrMT4Req4.ptrData;
                        ptrOrd._accountType    = accType;
                        ptrOrd._masterLogin    = masterLogin;
                        ptrOrd._mt4Login       = mt4Login;
                        ptrOrd._mt4ServerIndex = serverIndex;
                        ptrOrd._orderTransMode = eMT4OrderTransMode.ORD_TRANS_CLOSE;
                        ptrOrd._orderType      = eMT4OrderType.ORD_TYPE_BALANCE;
                        ptrOrd._price          = request.deposit;
                        if (ptrOrd._price == 0)
                        {
                            if (accType == eAccountType.ACC_TYPE_FOLLOWER_DEMO)
                            {
                                ptrOrd._price = m_masterUserSetting._deposit_followerDemo;
                            }
                            else if (accType == eAccountType.ACC_TYPE_SSP)
                            {
                                ptrOrd._price = m_masterUserSetting._deposit_SSP;
                            }
                            else if (accType == eAccountType.ACC_TYPE_SM)
                            {
                                ptrOrd._price = m_masterUserSetting._deposit_SM;
                            }
                        }

                        Demo.insertMT4Request(ptrMT4Req4);
                    }
                    else if (accType == eAccountType.ACC_TYPE_FOLLOWER_LIVE)
                    {
                        MT4Request ptrMT4Req4 = (MT4Request) new MT4Request();
                        //memset(ptrMT4Req4, 0, sizeof(MT4Request));
                        //ptrMT4Req4.newLoginOrOrderID = orderOrLogin; // Alexey
                        ptrMT4Req4.masterLogin = masterLogin;
                        ptrMT4Req4.reqType     = MT4REQ.MT4REQ_BALANCE;
                        //ptrMT4Req4.socketID = socketID;
                        ptrMT4Req4.status        = eOrderStatus.ORD_STAT_RECVD;
                        ptrMT4Req4.serverTransID = TransactionService.NewTransactionId();
                        ptrMT4Req4.ptrData       = new MT4OrderInfo();
                        //memset(ptrMT4Req4.ptrData, 0, sizeof(MT4OrderInfo));
                        MT4OrderInfo ptrOrd = (MT4OrderInfo)ptrMT4Req4.ptrData;
                        ptrOrd._accountType    = accType;
                        ptrOrd._masterLogin    = masterLogin;
                        ptrOrd._mt4Login       = mt4Login;
                        ptrOrd._mt4ServerIndex = serverIndex;
                        ptrOrd._orderTransMode = eMT4OrderTransMode.ORD_TRANS_CLOSE;
                        ptrOrd._orderType      = eMT4OrderType.ORD_TYPE_BALANCE;
                        ptrOrd._price          = request.deposit;
                        if (ptrOrd._price == 0)
                        {
                            ptrOrd._price = m_masterUserSetting._deposit_followerLive;
                        }
                        Live.insertMT4Request(ptrMT4Req4);
                    }

                    var ptrResp = new MT4AccountResponse(); //MT_MT4AccountResponse_ID
                    CppHelper.memcpy(ref ptrResp._account, acc);
                    _connectionMgr.SentDataUsingLoginID(ptrResp, MessageTypeID.MT_MT4AccountResponse_ID, masterLogin);
                }
                else if (trans_status == eOrderStatus.ORD_STAT_PROCESSING)
                {
                    // Claudia: it's normal that orderOrLogin parameter is 0, because MT4 is still processing the request
                    Debug.Assert(masterLogin > 0);
                    m_ptrLogger.LogInfo("PROCESSING : MT4 Account %d master Login %d AccountType: %d", mt4Login, masterLogin, accType);
                    var ptrResp = new SocialOrderResponse(); //MT_SocialOrderResponse_ID
                    ptrResp._serverTransID = server_trans_id;
                    ptrResp._requestMode   = reqMode;
                    ptrResp._retCode       = (eReturnCode)trans_status;
                    //SentDataUsingSocketID(ptrResp, MT_SocialOrderResponse_ID, socketID);
                    _connectionMgr.SentDataUsingLoginID(ptrResp, MessageTypeID.MT_SocialOrderResponse_ID, masterLogin);
                }
                else if (trans_status == eOrderStatus.ORD_STAT_REJECTED)
                {
                    // Claudia: it's normal that orderOrLogin parameter is 0, because MT4 is still processing the request
                    Debug.Assert(masterLogin > 0);
                    m_ptrLogger.LogInfo("REJECTED : MT4 Account %d master Login %d AccountType: %d", mt4Login, masterLogin, accType);
                    if (accType == eAccountType.ACC_TYPE_SSP)
                    {
                        await _signalService.UpdateSignalMT4Login(server_trans_id, mt4Login, cancellationToken, isRemove : true);

                        await _signalService.UpdateSSPSignalMT4Login(server_trans_id, mt4Login, cancellationToken, isRemove : true);
                    }
                    if (accType == eAccountType.ACC_TYPE_SM)
                    {
                        await _signalService.UpdateSignalMT4Login(server_trans_id, mt4Login, cancellationToken, isRemove : true);

                        await _signalService.UpdateSMSignalMT4Login(server_trans_id, mt4Login, cancellationToken, isRemove : true);
                    }
                    var ptrResp = new SocialOrderResponse(); //MT_SocialOrderResponse_ID
                    ptrResp._serverTransID = server_trans_id;
                    ptrResp._requestMode   = reqMode;
                    ptrResp._retCode       = (eReturnCode)trans_status;
                    ptrResp._mt4errorcode  = errorcode;
                    CppHelper.strcpy(out ptrResp._mt4errormessage, errormessage);
                    //SentDataUsingSocketID(ptrResp, MT_SocialOrderResponse_ID, socketID);
                    _connectionMgr.SentDataUsingLoginID(ptrResp, MessageTypeID.MT_SocialOrderResponse_ID, masterLogin);
                }
                //insertDBTransmitData(masterLogin, FDMT_MasterUser_ID);
                //insertDBTransmitData(masterLogin, FDMT_MT4Account_ID);
                //insertDBTransmitData(masterLogin, FDMT_SSPSignal_ID);
                //insertDBTransmitData(masterLogin, FDMT_SSPSignal_ID);
            }
            else
            {
                var orderId = request.OrderInfo?._orderID ?? 0;

                if (trans_status == eOrderStatus.ORD_STAT_PROCESSING)
                {
                    // Alexey: it's normal that orderOrLogin parameter is 0, because MT4 is still processing the request
                    Debug.Assert(masterLogin > 0 && server_trans_id != Guid.Empty);
                    m_ptrLogger.LogInfo($"PROCESSING : Order {orderId}, master Login {masterLogin}, UID: {server_trans_id}");
                    var ptrResp = new SocialOrderResponse(); //MT_SocialOrderResponse_ID
                    ptrResp._serverTransID = server_trans_id;
                    ptrResp._requestMode   = reqMode;
                    ptrResp._retCode       = (eReturnCode)trans_status;
                    //SentDataUsingSocketID(ptrResp, MT_SocialOrderResponse_ID, socketID);
                    _connectionMgr.SentDataUsingLoginID(ptrResp, MessageTypeID.MT_SocialOrderResponse_ID, masterLogin);
                }
                else if (trans_status == eOrderStatus.ORD_STAT_REJECTED)
                {
                    // Alexey: it's normal that orderOrLogin parameter is 0, because MT4 is still processing the request
                    Debug.Assert(masterLogin > 0 && server_trans_id != Guid.Empty);
                    m_ptrLogger.LogInfo($"REJECTED : Order {orderId}, master Login {masterLogin}, UID: {server_trans_id}");
                    var ptrResp = new SocialOrderResponse(); //MT_SocialOrderResponse_ID
                    ptrResp._serverTransID = server_trans_id;
                    ptrResp._requestMode   = reqMode;
                    ptrResp._retCode       = (eReturnCode)trans_status;
                    ptrResp._mt4errorcode  = errorcode;
                    CppHelper.strcpy(out ptrResp._mt4errormessage, errormessage);
                    //SentDataUsingSocketID(ptrResp, MT_SocialOrderResponse_ID, socketID);
                    _connectionMgr.SentDataUsingLoginID(ptrResp, MessageTypeID.MT_SocialOrderResponse_ID, masterLogin);
                }
                else if (trans_status == eOrderStatus.ORD_STAT_EXECUTED)
                {
                    if (reqMode == MT4REQMODE.OPEN_TRADE)
                    {
                        Debug.Assert(server_trans_id != Guid.Empty && orderId > 0 && request.Order != null && request.Order.OrderId == 0);
                        request.Order.OrderId = orderId;
                        await _orderService.InsertAsync(request.Order, cancellationToken);

                        //    updateTransLinking(server_trans_id, orderOrLogin);
                    }
                    //if (reqMode == MT4REQMODE.CLOSE_TRADE || reqMode == MT4REQMODE.DELETE_TRADE)
                    //{
                    //    removeTransLinking(server_trans_id);
                    //}
                    Debug.Assert(masterLogin > 0 && server_trans_id != Guid.Empty);
                    m_ptrLogger.LogInfo($"EXECUTED : Order {orderId}, master Login {masterLogin}, UID: {server_trans_id}");
                    var ptrResp = new SocialOrderResponse(); //MT_SocialOrderResponse_ID
                    ptrResp._serverTransID = server_trans_id;
                    ptrResp._requestMode   = reqMode;
                    ptrResp._retCode       = (eReturnCode)trans_status;
                    //SentDataUsingSocketID(ptrResp, MT_SocialOrderResponse_ID, socketID);
                    _connectionMgr.SentDataUsingLoginID(ptrResp, MessageTypeID.MT_SocialOrderResponse_ID, masterLogin);
                }
            }
        }
Пример #33
0
    public override void OnResponse(string data)
    {
        ReturnCode returnCode = (ReturnCode)(int.Parse(data));

        registerPanel.OnRegisterResponse(returnCode);
    }
Пример #34
0
        ///////////////////////////////////////////////////////////////////////////////////////////////

        #region IExecuteArgument Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Argument value,
            ref Result error
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count == (this.Arguments + 1))
                    {
                        Variant variant1 = null;

                        code = Value.GetVariant(interpreter,
                                                (IGetValue)arguments[1], ValueFlags.AnyVariant,
                                                interpreter.CultureInfo, ref variant1, ref error);

                        if (code == ReturnCode.Ok)
                        {
                            try
                            {
                                if (variant1.IsDouble())
                                {
                                    value = Interpreter.FixIntermediatePrecision(
                                        Math.Abs((double)variant1.Value));
                                }
                                else if (variant1.IsDecimal())
                                {
                                    value = Interpreter.FixIntermediatePrecision(
                                        Math.Abs((decimal)variant1.Value));
                                }
                                else if (variant1.IsWideInteger())
                                {
                                    value = Math.Abs((long)variant1.Value);
                                }
                                else if (variant1.IsInteger())
                                {
                                    value = Math.Abs((int)variant1.Value);
                                }
                                else if (variant1.IsBoolean())
                                {
                                    value = Math.Abs(ConversionOps.ToInt((bool)variant1.Value));
                                }
                                else
                                {
                                    error = String.Format(
                                        "unsupported variant type for function \"{0}\"",
                                        base.Name);

                                    code = ReturnCode.Error;
                                }
                            }
                            catch (Exception e)
                            {
                                Engine.SetExceptionErrorCode(interpreter, e);

                                error = String.Format(
                                    "caught math exception: {0}",
                                    e);

                                code = ReturnCode.Error;
                            }
                        }
                    }
                    else
                    {
                        if (arguments.Count > (this.Arguments + 1))
                        {
                            error = String.Format(
                                "too many arguments for math function \"{0}\"",
                                base.Name);
                        }
                        else
                        {
                            error = String.Format(
                                "too few arguments for math function \"{0}\"",
                                base.Name);
                        }

                        code = ReturnCode.Error;
                    }
                }
                else
                {
                    error = "invalid argument list";
                    code  = ReturnCode.Error;
                }
            }
            else
            {
                error = "invalid interpreter";
                code  = ReturnCode.Error;
            }

            return(code);
        }
Пример #35
0
        static void Main(string[] args)
        {
            int    ownID         = 1;
            string chatterName   = null;
            int    domain        = DDS.DomainId.Default;
            string partitionName = "ChatRoom";

            /* Options: Chatter [ownID [name]] */
            if (args.Length > 0)
            {
                ownID = int.Parse(args[0]);
                if (args.Length > 1)
                {
                    chatterName = args[1];
                }
            }

            /* Create a DomainParticipantFactory and a DomainParticipant
             * (using Default QoS settings. */
            DomainParticipantFactory dpf = DomainParticipantFactory.Instance;

            ErrorHandler.checkHandle(dpf, "DDS.DomainParticipantFactory.Instance");

            IDomainParticipant participant = dpf.CreateParticipant(domain, null, StatusKind.Any);

            ErrorHandler.checkHandle(participant, "DDS.DomainParticipantFactory.CreateParticipant");

            /* Register the required datatype for ChatMessage. */
            ChatMessageTypeSupport chatMessageTS = new ChatMessageTypeSupport();
            string     chatMessageTypeName       = chatMessageTS.TypeName;
            ReturnCode status = chatMessageTS.RegisterType(
                participant, chatMessageTypeName);

            ErrorHandler.checkStatus(
                status, "Chat.ChatMessageTypeSupport.RegisterType");

            /* Register the required datatype for NameService. */
            NameServiceTypeSupport nameServiceTS = new NameServiceTypeSupport();
            string nameServiceTypeName           = nameServiceTS.TypeName;

            status = nameServiceTS.RegisterType(
                participant, nameServiceTypeName);
            ErrorHandler.checkStatus(
                status, "Chat.NameServiceTypeSupport.RegisterType");

            /* Initialise Qos variables */
            TopicQos      reliableTopicQos = new TopicQos();
            TopicQos      settingTopicQos  = new TopicQos();
            PublisherQos  pubQos           = new PublisherQos();
            DataWriterQos dwQos            = new DataWriterQos();
            DataWriterQos nsDwQos          = new DataWriterQos();

            /* Set the ReliabilityQosPolicy to RELIABLE. */
            status = participant.GetDefaultTopicQos(ref reliableTopicQos);
            ErrorHandler.checkStatus(
                status, "DDS.DomainParticipant.GetDefaultTopicQos");
            reliableTopicQos.Reliability.Kind = ReliabilityQosPolicyKind.ReliableReliabilityQos;

            /* Make the tailored QoS the new default. */
            status = participant.SetDefaultTopicQos(reliableTopicQos);
            ErrorHandler.checkStatus(
                status, "DDS.DomainParticipant.SetDefaultTopicQos");

            /* Use the changed policy when defining the ChatMessage topic */
            ITopic chatMessageTopic = participant.CreateTopic(
                "Chat_ChatMessage",
                chatMessageTypeName,
                reliableTopicQos);

            ErrorHandler.checkHandle(
                chatMessageTopic,
                "DDS.DomainParticipant.CreateTopic (ChatMessage)");

            /* Set the DurabilityQosPolicy to TRANSIENT. */
            status = participant.GetDefaultTopicQos(ref settingTopicQos);
            ErrorHandler.checkStatus(
                status, "DDS.DomainParticipant.GetDefaultTopicQos");
            settingTopicQos.Durability.Kind = DurabilityQosPolicyKind.TransientDurabilityQos;

            /* Create the NameService Topic. */
            ITopic nameServiceTopic = participant.CreateTopic(
                "Chat_NameService",
                nameServiceTypeName,
                settingTopicQos);

            ErrorHandler.checkHandle(
                nameServiceTopic,
                "DDS.DomainParticipant.CreateTopic (NameService)");

            /* Adapt the default PublisherQos to write into the
             * "ChatRoom" Partition. */
            status = participant.GetDefaultPublisherQos(ref pubQos);
            ErrorHandler.checkStatus(
                status, "DDS.DomainParticipant.GetDefaultPublisherQos");
            pubQos.Partition.Name    = new string[1];
            pubQos.Partition.Name[0] = partitionName;

            /* Create a Publisher for the chatter application. */
            IPublisher chatPublisher = participant.CreatePublisher(pubQos);

            ErrorHandler.checkHandle(
                chatPublisher, "DDS.DomainParticipant.CreatePublisher");

            /* Create a DataWriter for the ChatMessage Topic
             * (using the appropriate QoS). */
            chatPublisher.GetDefaultDataWriterQos(ref dwQos);
            status = chatPublisher.CopyFromTopicQos(ref dwQos, reliableTopicQos);
            ErrorHandler.checkStatus(status, "DDS.Publisher.CopyFromTopicQos");

            IDataWriter parentWriter = chatPublisher.CreateDataWriter(chatMessageTopic, dwQos);

            ErrorHandler.checkHandle(
                parentWriter, "DDS.Publisher.CreateDatawriter (chatMessage)");

            /* Narrow the abstract parent into its typed representative. */
            ChatMessageDataWriter talker = parentWriter as ChatMessageDataWriter;

            ErrorHandler.checkHandle(
                talker, "Chat.ChatMessageDataWriter");

            /* Create a DataWriter for the NameService Topic
             * (using the appropriate QoS). */
            status = chatPublisher.GetDefaultDataWriterQos(ref nsDwQos);
            ErrorHandler.checkStatus(
                status, "DDS.Publisher.GetDefaultDatawriterQos");
            status = chatPublisher.CopyFromTopicQos(ref nsDwQos, settingTopicQos);
            ErrorHandler.checkStatus(status, "DDS.Publisher.CopyFromTopicQos");

            WriterDataLifecycleQosPolicy writerDataLifecycle = nsDwQos.WriterDataLifecycle;

            writerDataLifecycle.AutodisposeUnregisteredInstances = false;
            IDataWriter nsParentWriter = chatPublisher.CreateDataWriter(nameServiceTopic, nsDwQos);

            ErrorHandler.checkHandle(
                nsParentWriter, "DDS.Publisher.CreateDatawriter (NameService)");

            /* Narrow the abstract parent into its typed representative. */
            NameServiceDataWriter nameServer = nsParentWriter as NameServiceDataWriter;

            ErrorHandler.checkHandle(
                nameServer, "Chat.NameServiceDataWriterHelper");

            /* Initialize the NameServer attributes. */
            NameService ns = new NameService();

            ns.userID = ownID;
            if (chatterName != null)
            {
                ns.name = chatterName;
            }
            else
            {
                ns.name = "Chatter " + ownID;
            }

            /* Write the user-information into the system
             * (registering the instance implicitly). */
            status = nameServer.Write(ns);
            ErrorHandler.checkStatus(status, "Chat.ChatMessageDataWriter.Write");

            /* Initialize the chat messages. */
            ChatMessage msg = new ChatMessage();

            msg.userID = ownID;
            msg.index  = 0;
            if (ownID == TERMINATION_MESSAGE)
            {
                msg.content = "Termination message.";
            }
            else
            {
                msg.content = "Hi there, I will send you " +
                              NUM_MSG + " more messages.";
            }
            System.Console.WriteLine("Writing message: \"" + msg.content + "\"");

            /* Register a chat message for this user
             * (pre-allocating resources for it!!) */
            InstanceHandle userHandle = talker.RegisterInstance(msg);

            /* Write a message using the pre-generated instance handle. */
            status = talker.Write(msg, userHandle);
            ErrorHandler.checkStatus(status, "Chat.ChatMessageDataWriter.Write");

            Thread.Sleep(1000);

            /* Write any number of messages . */
            for (int i = 1; i <= NUM_MSG && ownID != TERMINATION_MESSAGE; i++)
            {
                msg.index   = i;
                msg.content = "Message no. " + i;
                Console.WriteLine("Writing message: \"" + msg.content + "\"");
                status = talker.Write(msg, userHandle);
                ErrorHandler.checkStatus(status, "Chat.ChatMessageDataWriter.Write");

                Thread.Sleep(1000); /* do not run so fast! */
            }

            /* Leave the room by disposing and unregistering the message instance */
            status = talker.Dispose(msg, userHandle);
            ErrorHandler.checkStatus(
                status, "Chat.ChatMessageDataWriter.Dispose");
            status = talker.UnregisterInstance(msg, userHandle);
            ErrorHandler.checkStatus(
                status, "Chat.ChatMessageDataWriter.unregister_instance");

            /* Also unregister our name. */
            status = nameServer.UnregisterInstance(ns, InstanceHandle.Nil);
            ErrorHandler.checkStatus(
                status, "Chat.NameServiceDataWriter.unregister_instance");

            /* Remove the DataWriters */
            status = chatPublisher.DeleteDataWriter(talker);
            ErrorHandler.checkStatus(
                status, "DDS.Publisher.DeleteDatawriter (talker)");

            status = chatPublisher.DeleteDataWriter(nameServer);
            ErrorHandler.checkStatus(status,
                                     "DDS.Publisher.DeleteDatawriter (nameServer)");

            /* Remove the Publisher. */
            status = participant.DeletePublisher(chatPublisher);
            ErrorHandler.checkStatus(
                status, "DDS.DomainParticipant.DeletePublisher");

            /* Remove the Topics. */
            status = participant.DeleteTopic(nameServiceTopic);
            ErrorHandler.checkStatus(
                status, "DDS.DomainParticipant.DeleteTopic (nameServiceTopic)");

            status = participant.DeleteTopic(chatMessageTopic);
            ErrorHandler.checkStatus(
                status, "DDS.DomainParticipant.DeleteTopic (chatMessageTopic)");

            /* Remove the DomainParticipant. */
            status = dpf.DeleteParticipant(participant);
            ErrorHandler.checkStatus(
                status, "DDS.DomainParticipantFactory.DeleteParticipant");
        }
Пример #36
0
        public static ReturnCode FixZip(RvFile fixZip, List <RvFile> fileProcessQueue, ref int totalFixed, out string errorMessage)
        {
            errorMessage = "";

            //Check for error status
            if (fixZip.DirStatus.HasUnknown())
            {
                return(ReturnCode.FindFixes); // Error
            }
            bool needsTrrntzipped = fixZip.ZipStatus != ZipStatus.TrrntZip && fixZip.GotStatus == GotStatus.Got && fixZip.DatStatus == DatStatus.InDatCollect && (Settings.rvSettings.FixLevel == EFixLevel.TrrntZipLevel1 || Settings.rvSettings.FixLevel == EFixLevel.TrrntZipLevel2 || Settings.rvSettings.FixLevel == EFixLevel.TrrntZipLevel3);

            // file corrupt and not in tosort
            //      if file cannot be fully fixed copy to corrupt
            //      process zipfile

            if (fixZip.GotStatus == GotStatus.Corrupt && fixZip.DatStatus != DatStatus.InToSort && !fixZip.DirStatus.HasFixable())
            {
                ReturnCode moveReturnCode = FixAZipFunctions.MoveZipToCorrupt(fixZip, out errorMessage);
                if (moveReturnCode != ReturnCode.Good)
                {
                    return(moveReturnCode);
                }
            }

            // has fixable
            //      process zipfile

            else if (fixZip.DirStatus.HasFixable())
            {
                // do nothing here but continue on to process zip.
            }

            // need trrntzipped
            //      process zipfile

            else if (needsTrrntzipped)
            {
                // rv7Zip format is not finalized yet so do not use
                if (!Settings.rvSettings.ConvertToRV7Z && (fixZip.FileType == FileType.SevenZip))
                //if (fixZip.FileType == FileType.SevenZip)
                {
                    needsTrrntzipped = false;
                }
                // do nothing here but continue on to process zip.
            }


            // got empty zip that should be deleted
            //      process zipfile
            else if (fixZip.GotStatus == GotStatus.Got && fixZip.GotStatus != GotStatus.Corrupt && !fixZip.DirStatus.HasAnyFiles())
            {
                // do nothing here but continue on to process zip.
            }

            // else
            //      skip this zipfile
            else
            {
                // nothing can be done to return
                return(ReturnCode.Good);
            }

            if (!fixZip.DirStatus.HasFixable() && !needsTrrntzipped)
            {
                return(ReturnCode.Good);
            }

            string fixZipFullName = fixZip.TreeFullName;

            if (!fixZip.DirStatus.HasFixable() && needsTrrntzipped)
            {
                Report.ReportProgress(new bgwShowFix(Path.GetDirectoryName(fixZipFullName), Path.GetFileName(fixZipFullName), "", 0, "TrrntZipping", "", "", ""));
            }


            FixFileUtils.CheckCreateDirectories(fixZip.Parent);
            ReportError.LogOut("");
            ReportError.LogOut(fixZipFullName + " : " + fixZip.RepStatus);
            ReportError.LogOut("------------------------------------------------------------");
            Debug.WriteLine(fixZipFullName + " : " + fixZip.RepStatus);
            ReportError.LogOut("Zip File Status Before Fix:");
            for (int intLoop = 0; intLoop < fixZip.ChildCount; intLoop++)
            {
                ReportError.LogOut(fixZip.Child(intLoop));
            }
            ReportError.LogOut("");

            ReturnCode returnCode    = ReturnCode.Good;
            RepStatus  fileRepStatus = RepStatus.UnSet;

            ICompress tempFixZip       = null;
            ICompress toSortCorruptOut = null;
            ICompress toSortZipOut     = null;

            try
            {
                RvFile toSortGame        = null;
                RvFile toSortCorruptGame = null;

                List <RvFile> fixZipTemp = new List <RvFile>();

                FileType fixFileType = fixZip.FileType;

                for (int iRom = 0; iRom < fixZip.ChildCount; iRom++)
                {
                    RvFile fixZippedFile = new RvFile(DBTypeGet.FileFromDir(fixFileType));
                    fixZip.Child(iRom).CopyTo(fixZippedFile);

                    fixZipTemp.Add(fixZippedFile);

                    ReportError.LogOut(fixZippedFile.RepStatus + " : " + fixZip.Child(iRom).FullName);

                    fileRepStatus = fixZippedFile.RepStatus;
                    switch (fixZippedFile.RepStatus)
                    {
                        #region Nothing to copy

                    // any file we do not have or do not want in the destination zip
                    case RepStatus.Missing:
                    case RepStatus.NotCollected:
                    case RepStatus.Rename:
                    case RepStatus.Delete:
                        if (!
                            (
                                // got the file in the original zip but will be deleting it
                                fixZippedFile.DatStatus == DatStatus.NotInDat && fixZippedFile.GotStatus == GotStatus.Got ||
                                fixZippedFile.DatStatus == DatStatus.NotInDat && fixZippedFile.GotStatus == GotStatus.Corrupt ||
                                fixZippedFile.DatStatus == DatStatus.InDatMerged && fixZippedFile.GotStatus == GotStatus.Got ||
                                fixZippedFile.DatStatus == DatStatus.InToSort && fixZippedFile.GotStatus == GotStatus.Got ||
                                fixZippedFile.DatStatus == DatStatus.InToSort && fixZippedFile.GotStatus == GotStatus.Corrupt ||

                                // do not have this file and cannot fix it here
                                fixZippedFile.DatStatus == DatStatus.InDatCollect && fixZippedFile.GotStatus == GotStatus.NotGot ||
                                fixZippedFile.DatStatus == DatStatus.InDatBad && fixZippedFile.GotStatus == GotStatus.NotGot ||
                                fixZippedFile.DatStatus == DatStatus.InDatMerged && fixZippedFile.GotStatus == GotStatus.NotGot
                            )
                            )
                        {
                            ReportError.SendAndShow("Error in Fix Rom Status " + fixZippedFile.RepStatus + " : " +
                                                    fixZippedFile.DatStatus + " : " + fixZippedFile.GotStatus);
                        }

                        if (fixZippedFile.RepStatus == RepStatus.Delete)
                        {
                            if (Settings.rvSettings.DetailedFixReporting)
                            {
                                Report.ReportProgress(new bgwShowFix(Path.GetDirectoryName(fixZipFullName), Path.GetFileName(fixZipFullName), fixZippedFile.Name, fixZippedFile.Size, "Delete", "", "", ""));
                            }

                            returnCode = FixFileUtils.DoubleCheckDelete(fixZippedFile, out errorMessage);
                            if (returnCode != ReturnCode.Good)
                            {
                                CloseZipFile(ref tempFixZip);
                                CloseToSortGame(toSortGame, ref toSortZipOut);
                                CloseToSortCorruptGame(toSortGame, ref toSortZipOut);
                                return(returnCode);
                            }
                        }

                        fixZippedFile.GotStatus = GotStatus.NotGot;
                        break;

                        #endregion


                    // any files we are just moving from the original zip to the destination zip
                    case RepStatus.Correct:
                    case RepStatus.InToSort:
                    case RepStatus.NeededForFix:
                    case RepStatus.Corrupt:
                    {
                        returnCode = FixAZipFunctions.CorrectZipFile(fixZip, fixZippedFile, ref tempFixZip, iRom, out errorMessage);
                        if (returnCode != ReturnCode.Good)
                        {
                            CloseZipFile(ref tempFixZip);
                            CloseToSortGame(toSortGame, ref toSortZipOut);
                            CloseToSortCorruptGame(toSortGame, ref toSortZipOut);
                            return(returnCode);
                        }
                        break;
                    }

                    case RepStatus.CanBeFixed:
                    case RepStatus.CorruptCanBeFixed:
                    {
                        returnCode = FixAZipFunctions.CanBeFixed(fixZip, fixZippedFile, ref tempFixZip, fileProcessQueue, ref totalFixed, out errorMessage);
                        if (returnCode != ReturnCode.Good)
                        {
                            CloseZipFile(ref tempFixZip);
                            CloseToSortGame(toSortGame, ref toSortZipOut);
                            CloseToSortCorruptGame(toSortGame, ref toSortZipOut);
                            return(returnCode);
                        }
                        break;
                    }

                    case RepStatus.MoveToSort:
                    {
                        returnCode = FixAZipFunctions.MovetoSort(fixZip, fixZippedFile, ref toSortGame, ref toSortZipOut, iRom);
                        if (returnCode != ReturnCode.Good)
                        {
                            CloseZipFile(ref tempFixZip);
                            CloseToSortGame(toSortGame, ref toSortZipOut);
                            CloseToSortCorruptGame(toSortGame, ref toSortZipOut);
                            return(returnCode);
                        }
                        break;
                    }

                    case RepStatus.MoveToCorrupt:
                        FixAZipFunctions.MoveToCorrupt(fixZip, fixZippedFile, ref toSortCorruptGame, ref toSortCorruptOut, iRom);
                        break;

                    default:
                        ReportError.UnhandledExceptionHandler(
                            "Unknown file status found " + fixZippedFile.RepStatus + " while fixing file " +
                            fixZip.Name + " Dat Status = " + fixZippedFile.DatStatus + " GotStatus " +
                            fixZippedFile.GotStatus);
                        break;
                    }
                }

                //if ToSort Zip Made then close the zip and add this new zip to the Database
                CloseToSortGame(toSortGame, ref toSortZipOut);

                //if Corrupt Zip Made then close the zip and add this new zip to the Database
                CloseToSortCorruptGame(toSortCorruptGame, ref toSortCorruptOut);

                #region Process original Zip

                string filename = fixZip.FullName;
                if (File.Exists(filename))
                {
                    if (!File.SetAttributes(filename, FileAttributes.Normal))
                    {
                        int error = Error.GetLastError();
                        Report.ReportProgress(new bgwShowError(filename,
                                                               "Error Setting File Attributes to Normal. Deleting Original Fix File. Code " + error));
                    }

                    try
                    {
                        File.Delete(filename);
                    }
                    catch (Exception e)
                    {
                        errorMessage = "Error While trying to delete file " + filename + ". " + e.Message;

                        if (tempFixZip != null && tempFixZip.ZipOpen != ZipOpenType.Closed)
                        {
                            tempFixZip.ZipFileClose();
                            tempFixZip = null;
                        }

                        return(ReturnCode.RescanNeeded);
                    }
                }

                #endregion

                bool checkDelete = false;

                #region process the temp Zip rename it to the original Zip

                if (tempFixZip != null && tempFixZip.ZipOpen != ZipOpenType.Closed)
                {
                    string tempFilename = tempFixZip.ZipFilename;
                    tempFixZip.ZipFileClose();

                    if (tempFixZip.LocalFilesCount() > 0)
                    {
                        // now rename the temp fix file to the correct filename
                        File.Move(tempFilename, filename);
                        FileInfo nFile  = new FileInfo(filename);
                        RvFile   tmpZip = new RvFile(FileType.Zip)
                        {
                            Name             = Path.GetFileName(filename),
                            FileModTimeStamp = nFile.LastWriteTime
                        };
                        tmpZip.SetStatus(fixZip.DatStatus, GotStatus.Got);

                        fixZip.FileAdd(tmpZip, false);
                        fixZip.ZipStatus = tempFixZip.ZipStatus;
                    }
                    else
                    {
                        File.Delete(tempFilename);
                        checkDelete = true;
                    }

                    tempFixZip = null;
                }
                else
                {
                    checkDelete = true;
                }

                #endregion

                #region Now put the New Game Status information into the Database.

                int intLoopFix = 0;
                foreach (RvFile tmpZip in fixZipTemp)
                {
                    tmpZip.CopyTo(fixZip.Child(intLoopFix));

                    if (fixZip.Child(intLoopFix).RepStatus == RepStatus.Deleted)
                    {
                        if (fixZip.Child(intLoopFix).FileRemove() == EFile.Delete)
                        {
                            fixZip.ChildRemove(intLoopFix);
                            continue;
                        }
                    }

                    intLoopFix++;
                }

                #endregion

                if (checkDelete)
                {
                    FixFileUtils.CheckDeleteFile(fixZip);
                }

                ReportError.LogOut("");
                ReportError.LogOut("Zip File Status After Fix:");
                for (int intLoop = 0; intLoop < fixZip.ChildCount; intLoop++)
                {
                    ReportError.LogOut(fixZip.Child(intLoop));
                }

                ReportError.LogOut("");

                return(ReturnCode.Good);
            }
            catch (ZipFileException ex)
            {
                tempFixZip?.ZipFileCloseFailed();
                toSortZipOut?.ZipFileCloseFailed();
                toSortCorruptOut?.ZipFileCloseFailed();
                tempFixZip       = null;
                toSortZipOut     = null;
                toSortCorruptOut = null;

                errorMessage = ex.Message;
                return(ex.returnCode);
            }
            catch (Exception ex)
            {
                tempFixZip?.ZipFileCloseFailed();
                toSortZipOut?.ZipFileCloseFailed();
                toSortCorruptOut?.ZipFileCloseFailed();
                tempFixZip       = null;
                toSortZipOut     = null;
                toSortCorruptOut = null;

                errorMessage = ex.Message;
                return(ReturnCode.LogicError);
            }
            finally
            {
                if (tempFixZip != null)
                {
                    ReportError.UnhandledExceptionHandler($"{tempFixZip.ZipFilename} tempZipOut was left open, ZipFile= {fixZipFullName} , fileRepStatus= {fileRepStatus} , returnCode= {returnCode}");
                }
                if (toSortZipOut != null)
                {
                    ReportError.UnhandledExceptionHandler($"{toSortZipOut.ZipFilename} toSortZipOut was left open");
                }
                if (toSortCorruptOut != null)
                {
                    ReportError.UnhandledExceptionHandler($"{toSortCorruptOut.ZipFilename} toSortCorruptOut was left open");
                }
            }
        }
Пример #37
0
        static int Main(string[] args)
        {
            Logger.Logged += OnLogged;

            ReturnCode optionParsingResult = ParseOptions(args);

            if (optionParsingResult != ReturnCode.Success)
            {
                return((int)optionParsingResult);
            }

            // check if input path exists, and if it's a file or directory
            bool directoryMode;

            try {
                if (File.Exists(inputPath))
                {
                    directoryMode = false;
                    if (outputDirName == null)
                    {
                        outputDirName = Paths.GetDirectoryNameOrRoot(inputPath);
                    }
                }
                else if (Directory.Exists(inputPath))
                {
                    directoryMode = true;
                    if (outputDirName == null)
                    {
                        outputDirName = Paths.GetDirectoryNameOrRoot(inputPath);
                    }
                }
                else
                {
                    Console.Error.WriteLine("MapRenderer: Cannot locate \"{0}\"", inputPath);
                    return((int)ReturnCode.InputDirNotFound);
                }

                if (!Directory.Exists(outputDirName))
                {
                    Directory.CreateDirectory(outputDirName);
                }
            } catch (Exception ex) {
                Console.Error.WriteLine("MapRenderer: {0}: {1}",
                                        ex.GetType().Name,
                                        ex.Message);
                return((int)ReturnCode.PathError);
            }

            // check recursive flag
            if (recursive && !directoryMode)
            {
                Console.Error.WriteLine("MapRenderer: Recursive flag is given, but input is not a directory.");
            }

            // check input filter
            if (inputFilter != null && !directoryMode)
            {
                Console.Error.WriteLine("MapRenderer: Filter param is given, but input is not a directory.");
            }

            // initialize image encoder
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            imageEncoder = codecs.FirstOrDefault(codec => codec.FormatID == exportFormat.Guid);
            if (imageEncoder == null)
            {
                Console.Error.WriteLine("MapRenderer: Specified image encoder is not supported.");
                return((int)ReturnCode.UnsupportedSaveFormat);
            }

            // create and configure the renderer
            renderer = new IsoCat {
                SeeThroughLava  = seeThroughLava,
                SeeThroughWater = seeThroughWater,
                Mode            = mode,
                Gradient        = !noGradient,
                DrawShadows     = !noShadows
            };
            if (mode == IsoCatMode.Chunk)
            {
                renderer.ChunkCoords[0] = region.XMin;
                renderer.ChunkCoords[1] = region.YMin;
                renderer.ChunkCoords[2] = region.ZMin;
                renderer.ChunkCoords[3] = region.ZMax;
                renderer.ChunkCoords[4] = region.YMax;
                renderer.ChunkCoords[5] = region.XMax;
            }
            switch (angle)
            {
            case 90:
                renderer.Rotation = 1;
                break;

            case 180:
                renderer.Rotation = 2;
                break;

            case 270:
            case -90:
                renderer.Rotation = 3;
                break;
            }

            if (!recursive && mapImporter != null && mapImporter.StorageType == MapStorageType.Directory)
            {
                // single-directory map
                RenderOneMap(new DirectoryInfo(inputPath));
            }
            else if (!directoryMode)
            {
                // single-file map
                RenderOneMap(new FileInfo(inputPath));
            }
            else
            {
                // possible single-directory conversion
                if (!recursive && RenderOneMap(new DirectoryInfo(inputPath)))
                {
                    return((int)ReturnCode.Success);
                }

                // go through all files inside the given directory
                SearchOption  recursiveOption = (recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                DirectoryInfo inputDirInfo    = new DirectoryInfo(inputPath);
                if (inputFilter == null)
                {
                    inputFilter = "*";
                }
                foreach (var dir in inputDirInfo.GetDirectories(inputFilter, recursiveOption))
                {
                    RenderOneMap(dir);
                }
                foreach (var file in inputDirInfo.GetFiles(inputFilter, recursiveOption))
                {
                    RenderOneMap(file);
                }
            }

            return((int)ReturnCode.Success);
        }
Пример #38
0
 /**
  * Returns the name of an error code.
  **/
 public static string getErrorName(ReturnCode status)
 {
     return(RetCodeName[(int)status]);
 }
Пример #39
0
 /// <summary>
 /// Register the type we are interested with the DDS Infrastructure
 /// </summary>
 /// <param name="ts">The TypeSupport class</param>
 public void registerType(ITypeSupport ts)
 {
     typeName = ts.TypeName;
     status = ts.RegisterType(participant, typeName);
     ErrorHandler.checkStatus(status, "ITypeSupport.RegisterType");
 }
Пример #40
0
 public CashDBException(string message, ReturnCode code) : base(message)
 {
     ReturnCode = code;
 }
    public override void OnResponse(string data)
    {
        ReturnCode returnCode = (ReturnCode)int.Parse(data);

        gamePanel.OnGameOverResponse(returnCode);
    }
Пример #42
0
 public MemberVariables(byte[] bytes, string str, ReturnCode codeInput)
 {
     byteArray = bytes;
     stringVar = str;
     code = codeInput;
 }
Пример #43
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Argument value,
            ref Result error
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    try
                    {
                        string  name     = null;
                        Variant operand1 = null;
                        Variant operand2 = null;

                        code = Value.GetOperandsFromArguments(interpreter,
                                                              this, arguments, ValueFlags.AnyVariant,
                                                              interpreter.CultureInfo, ref name,
                                                              ref operand1, ref operand2, ref error);

                        if (code == ReturnCode.Ok)
                        {
                            //
                            // NOTE: Fine, try to treat the operands as strings.
                            //
                            code = Value.FixupStringVariants(
                                this, operand1, operand2, ref error);

                            if (code == ReturnCode.Ok)
                            {
                                if (operand1.IsString())
                                {
                                    string str1  = (string)operand1.Value;
                                    string str2  = (string)operand2.Value;
                                    var    regex = new Regex(str2);

                                    value = regex.IsMatch(str1);
                                }
                                else
                                {
                                    error = String.Format(
                                        "unsupported operand type for operator {0}",
                                        FormatOps.OperatorName(name, this.Lexeme));

                                    code = ReturnCode.Error;
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Engine.SetExceptionErrorCode(interpreter, e);

                        error = String.Format(
                            "caught math exception: {0}",
                            e);

                        code = ReturnCode.Error;
                    }
                }
                else
                {
                    error = "invalid argument list";
                    code  = ReturnCode.Error;
                }
            }
            else
            {
                error = "invalid interpreter";
                code  = ReturnCode.Error;
            }

            return(code);
        }
Пример #44
0
        private static int Main(string[] args)
        {
            Console.WriteLine("Community TFS Build Manager Console - {0}\n", GetFileVersion(Assembly.GetExecutingAssembly()));

            try
            {
                // ---------------------------------------------------
                // Process the arguments
                // ---------------------------------------------------
                int retval = ProcessArguments(args);
                if (retval != 0)
                {
                    return retval;
                }

                switch (action)
                {
                    case ConsoleAction.ExportBuildDefinitions:
                        // ---------------------------------------------------
                        // Export the specified builds
                        // ---------------------------------------------------
                        retval = ExportBuilds();
                        if (retval != 0)
                        {
                            return retval;
                        }

                        break;
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += string.Format("Inner Exception: {0}", ex.InnerException.Message);
                }

                rc = ReturnCode.UnhandledException;
                LogMessage(message);
                return (int)rc;
            }

            return (int)rc;
        }
Пример #45
0
 public ZipFileException(ReturnCode rc, string message) : base(message)
 {
     returnCode = rc;
 }
Пример #46
0
 public TSigRecord(string name, TSigAlgorithm algorithm, DateTime timeSigned, TimeSpan fudge, ushort originalID, ReturnCode error, byte[] otherData, byte[] keyData)
     : base(name, RecordType.TSig, RecordClass.Any, 0)
 {
     Algorithm   = algorithm;
     TimeSigned  = timeSigned;
     Fudge       = fudge;
     OriginalMac = new byte[] { };
     OriginalID  = originalID;
     Error       = error;
     OtherData   = otherData ?? new byte[] { };
     KeyData     = keyData;
 }
Пример #47
0
        public void TestOnSampleRejected()
        {
            // Attach to the event
            int count = 0;

            _listener.SampleRejected += (r, s) =>
            {
                Assert.AreEqual(_reader, r);
                Assert.AreEqual(1, s.TotalCount);
                Assert.AreEqual(1, s.TotalCountChange);
                Assert.AreNotEqual(InstanceHandle.HandleNil, s.LastInstanceHandle);
                Assert.AreEqual(SampleRejectedStatusKind.RejectedBySamplesPerInstanceLimit, s.LastReason);

                count++;
            };

            // Prepare QoS for the test
            DataReaderQos drQos = new DataReaderQos();

            drQos.Reliability.Kind                     = ReliabilityQosPolicyKind.ReliableReliabilityQos;
            drQos.ResourceLimits.MaxInstances          = 1;
            drQos.ResourceLimits.MaxSamples            = 1;
            drQos.ResourceLimits.MaxSamplesPerInstance = 1;
            ReturnCode result = _reader.SetQos(drQos);

            Assert.AreEqual(ReturnCode.Ok, result);

            // Enable entities
            result = _writer.Enable();
            Assert.AreEqual(ReturnCode.Ok, result);

            result = _reader.Enable();
            Assert.AreEqual(ReturnCode.Ok, result);

            // Wait for discovery
            bool found = _writer.WaitForSubscriptions(1, 1000);

            Assert.IsTrue(found);

            // Write two samples of the same instances
            for (int i = 1; i <= 2; i++)
            {
                result = _dataWriter.Write(new TestStruct
                {
                    Id = 1
                });
                Assert.AreEqual(ReturnCode.Ok, result);

                result = _dataWriter.WaitForAcknowledgments(new Duration {
                    Seconds = 5
                });
                Assert.AreEqual(ReturnCode.Ok, result);
            }

            System.Threading.Thread.Sleep(100);
            Assert.AreEqual(1, count);

            // Remove the listener to avoid extra messages
            result = _reader.SetListener(null);
            Assert.AreEqual(ReturnCode.Ok, result);
        }
Пример #48
0
        public static ReturnCode MoveToCorrupt(RvFile fixZip, RvFile fixZippedFile, ref RvFile toSortCorruptGame, ref ICompress toSortCorruptOut, int iRom)
        {
            if (!((fixZippedFile.DatStatus == DatStatus.InDatCollect || fixZippedFile.DatStatus == DatStatus.NotInDat) && fixZippedFile.GotStatus == GotStatus.Corrupt))
            {
                ReportError.SendAndShow("Error in Fix Rom Status " + fixZippedFile.RepStatus + " : " + fixZippedFile.DatStatus + " : " + fixZippedFile.GotStatus);
            }

            ReportError.LogOut("Moving File to Corrupt");
            ReportError.LogOut(fixZippedFile);

            if (fixZippedFile.FileType == FileType.SevenZipFile)
            {
                fixZippedFile.GotStatus = GotStatus.NotGot; // Changes RepStatus to Deleted
                return(ReturnCode.Good);
            }

            string toSortFullName;

            if (toSortCorruptGame == null)
            {
                string corruptDir = Path.Combine(DB.ToSort(), "Corrupt");
                if (!Directory.Exists(corruptDir))
                {
                    Directory.CreateDirectory(corruptDir);
                }

                toSortFullName = Path.Combine(corruptDir, fixZip.Name);
                string toSortFileName = fixZip.Name;
                int    fileC          = 0;
                while (File.Exists(toSortFullName))
                {
                    fileC++;
                    string fName = Path.GetFileNameWithoutExtension(fixZip.Name);
                    string fExt  = Path.GetExtension(fixZip.Name);
                    toSortFullName = Path.Combine(corruptDir, fName + fileC + fExt);
                    toSortFileName = fixZip.Name + fileC;
                }

                toSortCorruptGame = new RvFile(FileType.Zip)
                {
                    Name      = toSortFileName,
                    DatStatus = DatStatus.InToSort,
                    GotStatus = GotStatus.Got
                };
            }
            else
            {
                string corruptDir = Path.Combine(DB.ToSort(), "Corrupt");
                toSortFullName = Path.Combine(corruptDir, toSortCorruptGame.Name);
            }

            RvFile toSortCorruptRom = new RvFile(FileType.ZipFile)
            {
                Name = fixZippedFile.Name,
                Size = fixZippedFile.Size,
                CRC  = fixZippedFile.CRC
            };

            toSortCorruptRom.SetStatus(DatStatus.InToSort, GotStatus.Corrupt);
            toSortCorruptGame.ChildAdd(toSortCorruptRom);

            if (toSortCorruptOut == null)
            {
                ReturnCode returnCode1 = OpenOutputZip(toSortCorruptGame, toSortFullName, out toSortCorruptOut, out string errorMessage1);
                if (returnCode1 != ReturnCode.Good)
                {
                    throw new FixAZip.ZipFileException(returnCode1, fixZippedFile.FullName + " " + fixZippedFile.RepStatus + " " + returnCode1 + Environment.NewLine + errorMessage1);
                }
            }


            string fixZipFullName = fixZip.TreeFullName;

            Report.ReportProgress(new bgwShowFix(Path.GetDirectoryName(fixZipFullName), Path.GetFileName(fixZipFullName), fixZippedFile.Name, fixZippedFile.Size, "Raw-->", "Corrupt", Path.GetFileName(toSortFullName), fixZippedFile.Name));

            ReturnCode returnCode = FixFileUtils.CopyFile(fixZip.Child(iRom), toSortCorruptOut, null, toSortCorruptRom, true, out string errorMessage);

            switch (returnCode)
            {
            case ReturnCode.Good:     // correct reply to continue;
                break;

            case ReturnCode.Cancel:
                return(returnCode);

            // doing a raw copy so not needed
            // case ReturnCode.SourceCRCCheckSumError:
            // case ReturnCode.SourceCheckSumError:
            // case ReturnCode.DestinationCheckSumError:
            default:
                throw new FixAZip.ZipFileException(returnCode, fixZippedFile.FullName + " " + fixZippedFile.RepStatus + " " + returnCode + Environment.NewLine + errorMessage);
            }

            fixZippedFile.GotStatus = GotStatus.NotGot; // Changes RepStatus to Deleted
            return(ReturnCode.Good);
        }
Пример #49
0
 /// <summary>
 /// Method to delete a data writer.
 /// </summary>
 /// <param name="dataWriter">The DataWriter instance to delete.</param>
 public void deleteWriter(IDataWriter dataWriter)
 {
     status = publisher.DeleteDataWriter(dataWriter);
     ErrorHandler.checkStatus(status, "Publisher.DeleteDataWriter");
 }
Пример #50
0
 public override void FromPacket(EnOceanPacket packet)
 {
     ReturnCode = (ReturnCode)packet.Data.Span[0];
 }
Пример #51
0
 /// <summary>
 /// Deletes the class's Subscriber
 /// </summary>
 public void deleteSubscriber()
 {
     status = participant.DeleteSubscriber(subscriber);
     ErrorHandler.checkStatus(status, "Participant.DeleteSubscriber");
 }
Пример #52
0
 private void RaiseEvaluateCompletedEvent(ReturnCode returnCode, Result result, int errorLine = 0) =>
 EvaluateCompleted?.Invoke(this, new EvaluteResultEventArgs(result, returnCode, errorLine));
Пример #53
0
 /// <summary>
 /// Delete the DomainParticipant.
 /// </summary>
 public void deleteParticipant()
 {
     status = dpf.DeleteParticipant(participant);
     ErrorHandler.checkStatus(status, "DomainParticipantFactory.DeleteParticipant");
 }
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Bad args number");
                Console.WriteLine("*** [QueryConditionDataQuerySubscriber] Query string not specified");
                Console.WriteLine("*** usage : QueryConditionDataQuerySubscriber <query_string>");
            }
            else
            {
                ITopic           topic;
                DDSEntityManager mgr           = new DDSEntityManager("QueryCondition");
                String           partitionName = "QueryCondition example";
                String           QueryConditionDataToSubscribe = args[0];

                // Create DomainParticipant
                mgr.createParticipant(partitionName);

                // Create Type
                StockTypeSupport msgTS = new StockTypeSupport();
                mgr.registerType(msgTS);

                // Create Topic
                topic = mgr.createTopic("StockTrackerExclusive");

                // create Subscriber
                mgr.createSubscriber();

                // create DataReader
                mgr.createReader(false);

                // Read Events
                IDataReader     dreader = mgr.getReader();
                StockDataReader QueryConditionDataReader = dreader as StockDataReader;

                String[] queryStr = { QueryConditionDataToSubscribe };

                Console.WriteLine("=== [QueryConditionDataQuerySubscriber] Query : ticker = {0}", QueryConditionDataToSubscribe);
                IQueryCondition qc = QueryConditionDataReader.CreateQueryCondition(
                    SampleStateKind.Any, ViewStateKind.Any, InstanceStateKind.Any, "ticker=%0", queryStr);

                Console.WriteLine("=== [QueryConditionDataQuerySubscriber] Ready ...");

                DDS.SampleInfo[] infoSeq  = null;
                Stock[]          stockSeq = null;

                ReturnCode status    = ReturnCode.Error;
                bool       terminate = false;
                int        count     = 0;
                Console.WriteLine("=== [QueryConditionDataQuerySubscriber] Ready ...");
                while (!terminate && count < 1500)
                {
                    // Take Sample with Condition
                    status = QueryConditionDataReader.TakeWithCondition(ref stockSeq, ref infoSeq,
                                                                        Length.Unlimited, qc);
                    ErrorHandler.checkStatus(status, "DataReader.TakeWithCondition");

                    /**
                     * Display Data
                     */
                    for (int i = 0; i < stockSeq.Length; i++)
                    {
                        if (infoSeq[i].ValidData)
                        {
                            if (stockSeq[i].price == -1.0f)
                            {
                                terminate = true;
                                break;
                            }
                            Console.WriteLine("{0} : {1}", stockSeq[i].ticker, String.Format("{0:0.#}", stockSeq[i].price));
                        }
                    }
                    status = QueryConditionDataReader.ReturnLoan(ref stockSeq, ref infoSeq);
                    ErrorHandler.checkStatus(status, "DataReader.ReturnLoan");
                    Thread.Sleep(200);
                    ++count;
                }

                Console.WriteLine("=== [QueryConditionDataQuerySubscriber] Market Closed");

                // clean up
                QueryConditionDataReader.DeleteReadCondition(qc);
                mgr.getSubscriber().DeleteDataReader(QueryConditionDataReader);
                mgr.deleteSubscriber();
                mgr.deleteTopic();
                mgr.deleteParticipant();
            }
        }
Пример #55
0
        [STAThread()] /* WinForms */
        private static int Main(string[] args)
        {
            #region Shell Debugging Support (Optional)
            //
            // NOTE: Pause for them to attach a debugger, if requested.
            //       This cannot be done inside the Interpreter class
            //       because they may want to debug its initializers.
            //
            if (Environment.GetEnvironmentVariable(EnvVars.Break) != null)
            {
                //
                // NOTE: Prevent further breaks into the debugger.
                //
                Environment.SetEnvironmentVariable(EnvVars.Break, null);

#if CONSOLE
                //
                // NOTE: Display the prompt and then wait for the user to
                //       press a key.
                //
                Console.WriteLine(String.Format(
                                      _Constants.Prompt.Debugger, GetProcessId()));

                try
                {
                    Console.ReadKey(true);        /* throw */
                }
                catch (InvalidOperationException) // Console.ReadKey
                {
                    // do nothing.
                }
#endif

                Debugger.Break(); /* throw */
            }
            #endregion

            ///////////////////////////////////////////////////////////////////

            #region Interpreter Creation Flags (Optional)
            //
            // NOTE: Start with default shell flags.
            //
            CreateFlags flags = CreateFlags.ShellUse;

#if CONSOLE
            //
            // NOTE: The console is enabled and we are going to use our custom
            //       host which inherits from it; therefore, prevent a default
            //       host from being created for the interpreter.
            //
            flags |= CreateFlags.NoHost;
#endif

            //
            // NOTE: Get the effective interpreter creation flags for the shell
            //       from the environment, etc.
            //
            flags = Interpreter.GetStartupCreateFlags(
                args, flags, OptionOriginFlags.Shell, true, true);
            #endregion

            ///////////////////////////////////////////////////////////////////

            //
            // NOTE: We need a return code and result variable now (in case
            //       querying the interpreter library path fails).
            //
            ReturnCode code   = ReturnCode.Ok;
            Result     result = null;

            ///////////////////////////////////////////////////////////////////

            #region Interpreter Pre-Initialize Text (Optional)
            //
            // NOTE: Start with the default pre-initialize text.
            //
            string text = null;

            //
            // NOTE: Get the effective interpreter pre-initialize text for the
            //       shell from the environment, etc.
            //
            if (code == ReturnCode.Ok)
            {
                code = Interpreter.GetStartupPreInitializeText(
                    args, flags, OptionOriginFlags.Shell, true,
                    true, ref text, ref result);
            }
            #endregion

            ///////////////////////////////////////////////////////////////////

            #region Interpreter Library Path (Optional)
            //
            // NOTE: Start with the default library path.
            //
            string libraryPath = null;

            //
            // NOTE: Get the effective interpreter library path for the shell
            //       from the environment, etc.
            //
            if (code == ReturnCode.Ok)
            {
                code = Interpreter.GetStartupLibraryPath(
                    args, flags, OptionOriginFlags.Shell, true,
                    true, ref libraryPath, ref result);
            }
            #endregion

            ///////////////////////////////////////////////////////////////////

            if (code == ReturnCode.Ok)
            {
                //
                // NOTE: Create an interpreter now inside of a using block so
                //       that we can be relatively sure it will be finalized
                //       on this thread.
                //
                using (interpreter = Interpreter.Create(
                           args, flags, text, libraryPath, ref result))
                {
                    //
                    // NOTE: Make sure the interpreter was actually created.
                    //       This can, in theory, be a problem if the
                    //       ThrowOnError flag ends up getting removed somehow
                    //       prior to the call to create the interpreter.
                    //
                    if (interpreter != null)
                    {
                        //
                        // NOTE: Fetch the interpreter host now for error
                        //       reporting purposes.
                        //
                        IHost host = interpreter.Host;

                        ///////////////////////////////////////////////////////

                        #region Interpreter Startup Options (Optional)
                        //
                        // NOTE: By default, initialize the script library for
                        //       the interpreter.
                        //
                        bool initialize = true;

                        //
                        // NOTE: Process all the remaining startup options
                        //       (i.e. the ones that do not modify the
                        //       interpreter creation flags) now.
                        //
                        code = Interpreter.ProcessStartupOptions(
                            interpreter, args, flags, OptionOriginFlags.Shell,
                            true, true, ref initialize, ref result);
                        #endregion

                        ///////////////////////////////////////////////////////

                        if (code == ReturnCode.Ok)
                        {
                            #region Command Line Arguments (Optional)
#if CONSOLE
                            //
                            // NOTE: In debug mode, show the command line
                            //       arguments just as we received them.
                            //
                            if (interpreter.Debug)
                            {
                                Console.WriteLine("The command line is: {0}",
                                                  Utility.BuildCommandLine(args, true));
                            }
#endif

                            //
                            // NOTE: Save the intial arguments for later use.
                            //
                            mainArguments = args;
                            #endregion

                            ///////////////////////////////////////////////////

                            #region Host - Window Preference (Optional)
                            //
                            // NOTE: By default, show the host window?
                            //
                            // TODO: Make this an argument?
                            //
                            bool console = DefaultConsole;

                            //
                            // NOTE: Do we want the initial (auto-created) host
                            //       window to be visible?
                            //
                            if (console)
                            {
                                if (Utility.GetEnvironmentVariable(
                                        EnvVars.NoConsole, true, false) != null)
                                {
#if CONSOLE
                                    Console.WriteLine(
                                        _Constants.Prompt.NoConsole);
#endif

                                    console = false;
                                }
                            }
                            else
                            {
                                if (Utility.GetEnvironmentVariable(
                                        EnvVars.Console, true, false) != null)
                                {
#if CONSOLE
                                    Console.WriteLine(
                                        _Constants.Prompt.Console);
#endif

                                    console = true;
                                }
                            }
                            #endregion

                            ///////////////////////////////////////////////////

                            #region Resource Manager Creation
                            //
                            // NOTE: Create our resource manager (the host and
                            //       the form will both use this).
                            //
                            ResourceManager resourceManager =
                                new ResourceManager(resourceBaseName,
                                                    packageAssembly);
                            #endregion

                            ///////////////////////////////////////////////////

                            #region Host - Custom Creation (Optional)
#if CONSOLE
                            //
                            // NOTE: Create a custom IHost bound to the
                            //       interpreter.
                            //
                            host = new _Hosts.Custom(new HostData(null, null,
                                                                  null, ClientData.Empty, typeof(_Hosts.Custom).Name,
                                                                  interpreter, resourceManager, null,
                                                                  Utility.HasFlags(flags, CreateFlags.UseAttach, true),
                                                                  Utility.HasFlags(flags, CreateFlags.NoColor, true),
                                                                  Utility.HasFlags(flags, CreateFlags.NoTitle, true),
                                                                  Utility.HasFlags(flags, CreateFlags.NoIcon, true),
                                                                  Utility.HasFlags(flags, CreateFlags.NoProfile, true),
                                                                  Utility.HasFlags(flags, CreateFlags.NoCancel, true)));

                            ///////////////////////////////////////////////////

                            interpreter.Host = host;
#endif
                            #endregion

                            ///////////////////////////////////////////////////

                            #region Interpreter Initialization
                            //
                            // NOTE: Attempt to initialize the interpreter.
                            //
                            if (initialize)
                            {
                                code = interpreter.Initialize(false, ref result);
                            }
                            else
                            {
                                code = ReturnCode.Ok;
                            }
                            #endregion

                            ///////////////////////////////////////////////////

                            #region Application-Specific Startup
                            //
                            // NOTE: If initialization failed, no point in
                            //       continuing.
                            //
                            if (code == ReturnCode.Ok)
                            {
                                Application.EnableVisualStyles();
                                Application.SetCompatibleTextRenderingDefault(false);

                                mainForm = new _Forms.TestForm(interpreter, args);

#if NOTIFY || NOTIFY_OBJECT
                                Assembly     assembly     = Assembly.GetExecutingAssembly();
                                AssemblyName assemblyName = assembly.GetName();
                                string       fileName     = assembly.Location;
                                string       typeName     = typeof(_Plugins.TestForm).FullName;
                                Uri          uri          = Utility.GetAssemblyUri(assembly);

                                IPlugin plugin = new _Plugins.TestForm(mainForm,
                                                                       new PluginData(Utility.FormatPluginName(
                                                                                          assemblyName.FullName, typeName), null, null,
                                                                                      ClientData.Empty, PluginFlags.None,
                                                                                      assemblyName.Version, uri,
                                                                                      interpreter.GetAppDomain(), assembly,
                                                                                      assemblyName, fileName, typeName, null, null,
                                                                                      null, null, null, null, resourceManager, null,
                                                                                      0));

                                code = Utility.PrepareStaticPlugin(
                                    plugin, ref result);

                                if (code == ReturnCode.Ok)
                                {
                                    code = interpreter.AddPlugin(
                                        plugin, null, ref pluginToken, ref result);
                                }
#endif
                            }
                            #endregion

                            ///////////////////////////////////////////////////

                            #region Host - Window Startup
                            if (code == ReturnCode.Ok)
                            {
                                if (console)
                                {
                                    //
                                    // NOTE: Create and start the interpreter
                                    //       loop thread.
                                    //
                                    code = StartupInteractiveLoopThread(
                                        ref result);
                                }
                                else if (host.IsOpen())
                                {
                                    //
                                    // NOTE: Close the initial host window.
                                    //
                                    code = host.Close(ref result);
                                }
                            }
                            #endregion

                            ///////////////////////////////////////////////////

                            if (code == ReturnCode.Ok)
                            {
                                #region WinForms Specific
                                //
                                // NOTE: Show the primary user interface form
                                //       for the application.
                                //
                                Application.Run(mainForm);
                                #endregion

                                ///////////////////////////////////////////////

                                #region Host - Window Shutdown
                                //
                                // NOTE: If there is an interactive loop thread,
                                //       we do not want to exit until it is no
                                //       longer running.
                                //
                                if (interactiveLoopThread != null)
                                {
                                    interactiveLoopThread.Join();
                                }
                                #endregion
                            }

                            ///////////////////////////////////////////////////

                            #region Startup Error Handling
                            //
                            // NOTE: Was there any kind of failure above?
                            //
                            if (code != ReturnCode.Ok)
                            {
                                #region WinForms Specific Code
                                if (mainForm != null)
                                {
                                    mainForm.Dispose();
                                    mainForm = null;
                                }
                                #endregion

                                ///////////////////////////////////////////////

                                if (host != null)
                                {
                                    host.WriteResultLine(
                                        code, result, interpreter.ErrorLine);
                                }

                                CommonOps.Complain(code, result);

                                exitCode = Utility.ReturnCodeToExitCode(
                                    code, true);
                            }
                            #endregion
                        }
                        else
                        {
                            if (host != null)
                            {
                                host.WriteResultLine(code, result);
                            }

                            exitCode = Utility.ReturnCodeToExitCode(
                                code, true);
                        }
                    }
                    else
                    {
#if CONSOLE
                        //
                        // NOTE: Creation of the interpreter failed.
                        //
                        Console.WriteLine(Utility.FormatResult(
                                              ReturnCode.Error, result));
#endif

                        exitCode = Utility.FailureExitCode();
                    }
                }
            }
            else
            {
#if CONSOLE
                //
                // NOTE: Querying the interpreter library path failed.
                //
                Console.WriteLine(Utility.FormatResult(code, result));
#endif

                exitCode = Utility.ReturnCodeToExitCode(code, true);
            }

            return((int)exitCode);
        }
Пример #56
0
        public void TestTakeInstance()
        {
            List <PublicationBuiltinTopicData> data = new List <PublicationBuiltinTopicData>();
            List <SampleInfo> infos = new List <SampleInfo>();
            ReturnCode        ret   = _dr.Read(data, infos);

            Assert.AreEqual(ReturnCode.NoData, ret);
            Assert.AreEqual(0, data.Count);
            Assert.AreEqual(0, infos.Count);

            DomainParticipant otherParticipant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.RTPS_DOMAIN);

            Assert.IsNotNull(otherParticipant);
            otherParticipant.BindRtpsUdpTransportConfig();

            Assert.IsTrue(_participant.WaitForParticipants(1, 20_000));

            TestStructTypeSupport support = new TestStructTypeSupport();
            string     typeName           = support.GetTypeName();
            ReturnCode result             = support.RegisterType(otherParticipant, typeName);

            Assert.AreEqual(ReturnCode.Ok, result);

            var topic = otherParticipant.CreateTopic(TestContext.TestName, typeName);

            Assert.IsNotNull(topic);

            var publisher = otherParticipant.CreatePublisher();

            Assert.IsNotNull(publisher);

            DataWriterQos dwQos = TestHelper.CreateNonDefaultDataWriterQos();

            dwQos.Ownership.Kind = OwnershipQosPolicyKind.SharedOwnershipQos;
            DataWriter dataWriter = publisher.CreateDataWriter(topic, dwQos);

            Assert.IsNotNull(dataWriter);

            int count = 200;

            ret = ReturnCode.NoData;
            while (ret != ReturnCode.Ok && count > 0)
            {
                Thread.Sleep(100);
                ret = _dr.ReadNextInstance(data, infos, InstanceHandle.HandleNil);
                count--;
            }

            Assert.AreEqual(ReturnCode.Ok, ret);
            Assert.AreEqual(1, data.Count);
            Assert.AreEqual(1, infos.Count);
            TestHelper.TestNonDefaultPublicationData(data.First());

            var handle = infos.First().InstanceHandle;

            data  = new List <PublicationBuiltinTopicData>();
            infos = new List <SampleInfo>();

            ret = _dr.TakeInstance(data, infos, handle);
            Assert.AreEqual(ReturnCode.Ok, ret);
            Assert.AreEqual(1, data.Count);
            Assert.AreEqual(1, infos.Count);
            TestHelper.TestNonDefaultPublicationData(data.First());

            ret = otherParticipant.DeleteContainedEntities();
            Assert.AreEqual(ReturnCode.Ok, ret);

            ret = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
            Assert.AreEqual(ReturnCode.Ok, ret);
        }
Пример #57
0
        public DnsAnswer(byte[] response)
        {
            _questions = new List<Question>();
            _answers = new List<Answer>();
            _servers = new List<Server>();
            _additional = new List<Record>();
            _exceptions = new List<Exception>();
            DataBuffer buffer = new DataBuffer(response, 2);
            byte bits1 = buffer.ReadByte();
            byte bits2 = buffer.ReadByte();
            //Mask off return code
            int returnCode = bits2 & 15;
            if (returnCode > 6) returnCode = 6;
            this._returnCode = (ReturnCode)returnCode;
            //Get Additional Flags
            _authoritative = TestBit(bits1, 2);
            _recursive = TestBit(bits2, 8);
            _truncated = TestBit(bits1, 1);

            int nQuestions = buffer.ReadBEShortInt();
            int nAnswers = buffer.ReadBEShortInt();
            int nServers = buffer.ReadBEShortInt();
            int nAdditional = buffer.ReadBEShortInt();

            //read in questions
            for (int i = 0; i < nQuestions; i++)
            {
                try
                {
                    _questions.Add(new Question(buffer));
                }
                catch (Exception ex)
                {
                    _exceptions.Add(ex);
                }
            }
            //read in answers
            for (int i = 0; i < nAnswers; i++)
            {
                try
                {
                    _answers.Add(new Answer(buffer));
                }
                catch (Exception ex)
                {
                    _exceptions.Add(ex);
                }
            }
            //read in servers
            for (int i = 0; i < nServers; i++)
            {
                try
                {
                    _servers.Add(new Server(buffer));
                }
                catch (Exception ex)
                {
                    _exceptions.Add(ex);
                }
            }
            //read in additional records
            for (int i = 0; i < nAdditional; i++)
            {
                try
                {
                    _additional.Add(new Record(buffer));
                }
                catch (Exception ex)
                {
                    _exceptions.Add(ex);
                }
            }
        }
Пример #58
0
        public void TestGetKeyValue()
        {
            // Call GetKeyValue with HandleNil
            PublicationBuiltinTopicData data = default;
            SampleInfo info = new SampleInfo();
            ReturnCode ret  = _dr.GetKeyValue(ref data, InstanceHandle.HandleNil);

            Assert.AreEqual(ReturnCode.BadParameter, ret);

            DomainParticipant otherParticipant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.RTPS_DOMAIN);

            Assert.IsNotNull(otherParticipant);
            otherParticipant.BindRtpsUdpTransportConfig();

            Assert.IsTrue(_participant.WaitForParticipants(1, 20_000));

            TestStructTypeSupport support = new TestStructTypeSupport();
            string     typeName           = support.GetTypeName();
            ReturnCode result             = support.RegisterType(otherParticipant, typeName);

            Assert.AreEqual(ReturnCode.Ok, result);

            var topic = otherParticipant.CreateTopic(TestContext.TestName, typeName);

            Assert.IsNotNull(topic);

            var publisher = otherParticipant.CreatePublisher();

            Assert.IsNotNull(publisher);

            DataWriterQos dwQos = TestHelper.CreateNonDefaultDataWriterQos();

            dwQos.Ownership.Kind = OwnershipQosPolicyKind.SharedOwnershipQos;
            DataWriter dataWriter = publisher.CreateDataWriter(topic, dwQos);

            Assert.IsNotNull(dataWriter);

            int count = 200;

            ret = ReturnCode.NoData;
            while (ret != ReturnCode.Ok && count > 0)
            {
                Thread.Sleep(100);
                // Get an existing instance
                ret = _dr.ReadNextSample(ref data, info);
                count--;
            }
            Assert.AreEqual(ReturnCode.Ok, ret);
            TestHelper.TestNonDefaultPublicationData(data);

            PublicationBuiltinTopicData aux = default;

            ret = _dr.GetKeyValue(ref aux, info.InstanceHandle);
            Assert.AreEqual(ReturnCode.Ok, ret);
            for (int i = 0; i < 16; i++)
            {
                Assert.AreEqual(data.Key.Value[i], aux.Key.Value[i]);
            }

            ret = otherParticipant.DeleteContainedEntities();
            Assert.AreEqual(ReturnCode.Ok, ret);

            ret = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
            Assert.AreEqual(ReturnCode.Ok, ret);
        }
Пример #59
0
        private static int ProcessArguments(string[] args)
        {
            if (args.Contains("/?") || args.Contains("/help"))
            {
                Console.WriteLine(@"Syntax:\t\ctfsbm.exe /f:<files> | /auto [switches]\n");
                Console.WriteLine("Optional Switches:\t\t\n");
                Console.WriteLine("Samples:\t\t\n");

                return (int)ReturnCode.UsageRequested;
            }

            Console.Write("Processing Arguments");
            if (args.Length == 0)
            {
                rc = ReturnCode.ArgumentsNotSupplied;
                LogMessage();
                return (int)rc;
            }

            Regex searchTerm = new Regex(@"/p:.*", RegexOptions.IgnoreCase);
            bool propertiesargumentfound = args.Select(arg => searchTerm.Match(arg)).Any(m => m.Success);
            if (propertiesargumentfound)
            {
                // properties = args.First(item => item.Contains("/p:")).Replace("/p:", string.Empty).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            }

            Console.Write("...Success\n");
            return 0;
        }
Пример #60
0
        public override void Execute()
        {
            int exitCode = 0;

            this.ValidatePathParameter(this.EnlistmentRootPathParameter);
            this.ValidatePathParameter(this.LocalCacheRoot);

            string fullEnlistmentRootPathParameter;
            string normalizedEnlistmentRootPath = this.GetCloneRoot(out fullEnlistmentRootPathParameter);

            if (!string.IsNullOrWhiteSpace(this.LocalCacheRoot))
            {
                string fullLocalCacheRootPath = Path.GetFullPath(this.LocalCacheRoot);

                string errorMessage;
                string normalizedLocalCacheRootPath;
                if (!GVFSPlatform.Instance.FileSystem.TryGetNormalizedPath(fullLocalCacheRootPath, out normalizedLocalCacheRootPath, out errorMessage))
                {
                    this.ReportErrorAndExit($"Failed to determine normalized path for '--local-cache-path' path {fullLocalCacheRootPath}: {errorMessage}");
                }

                if (normalizedLocalCacheRootPath.StartsWith(
                        Path.Combine(normalizedEnlistmentRootPath, GVFSConstants.WorkingDirectoryRootName),
                        StringComparison.OrdinalIgnoreCase))
                {
                    this.ReportErrorAndExit("'--local-cache-path' cannot be inside the src folder");
                }
            }

            this.CheckKernelDriverSupported(normalizedEnlistmentRootPath);
            this.CheckNotInsideExistingRepo(normalizedEnlistmentRootPath);
            this.BlockEmptyCacheServerUrl(this.CacheServerUrl);

            try
            {
                GVFSEnlistment enlistment;
                Result         cloneResult = new Result(false);

                CacheServerInfo  cacheServer      = null;
                ServerGVFSConfig serverGVFSConfig = null;

                using (JsonTracer tracer = new JsonTracer(GVFSConstants.GVFSEtwProviderName, "GVFSClone"))
                {
                    cloneResult = this.TryCreateEnlistment(fullEnlistmentRootPathParameter, normalizedEnlistmentRootPath, out enlistment);
                    if (cloneResult.Success)
                    {
                        tracer.AddLogFileEventListener(
                            GVFSEnlistment.GetNewGVFSLogFileName(enlistment.GVFSLogsRoot, GVFSConstants.LogFileTypes.Clone),
                            EventLevel.Informational,
                            Keywords.Any);
                        tracer.WriteStartEvent(
                            enlistment.EnlistmentRoot,
                            enlistment.RepoUrl,
                            this.CacheServerUrl,
                            new EventMetadata
                        {
                            { "Branch", this.Branch },
                            { "LocalCacheRoot", this.LocalCacheRoot },
                            { "SingleBranch", this.SingleBranch },
                            { "NoMount", this.NoMount },
                            { "NoPrefetch", this.NoPrefetch },
                            { "Unattended", this.Unattended },
                            { "IsElevated", GVFSPlatform.Instance.IsElevated() },
                            { "NamedPipeName", enlistment.NamedPipeName },
                            { nameof(this.EnlistmentRootPathParameter), this.EnlistmentRootPathParameter },
                            { nameof(fullEnlistmentRootPathParameter), fullEnlistmentRootPathParameter },
                        });

                        CacheServerResolver cacheServerResolver = new CacheServerResolver(tracer, enlistment);
                        cacheServer = cacheServerResolver.ParseUrlOrFriendlyName(this.CacheServerUrl);

                        string resolvedLocalCacheRoot;
                        if (string.IsNullOrWhiteSpace(this.LocalCacheRoot))
                        {
                            resolvedLocalCacheRoot = LocalCacheResolver.GetDefaultLocalCacheRoot(enlistment);
                        }
                        else
                        {
                            resolvedLocalCacheRoot = Path.GetFullPath(this.LocalCacheRoot);
                        }

                        this.Output.WriteLine("Clone parameters:");
                        this.Output.WriteLine("  Repo URL:     " + enlistment.RepoUrl);
                        this.Output.WriteLine("  Branch:       " + (string.IsNullOrWhiteSpace(this.Branch) ? "Default" : this.Branch));
                        this.Output.WriteLine("  Cache Server: " + cacheServer);
                        this.Output.WriteLine("  Local Cache:  " + resolvedLocalCacheRoot);
                        this.Output.WriteLine("  Destination:  " + enlistment.EnlistmentRoot);

                        string authErrorMessage;
                        if (!this.TryAuthenticate(tracer, enlistment, out authErrorMessage))
                        {
                            this.ReportErrorAndExit(tracer, "Cannot clone because authentication failed: " + authErrorMessage);
                        }

                        RetryConfig retryConfig = this.GetRetryConfig(tracer, enlistment, TimeSpan.FromMinutes(RetryConfig.FetchAndCloneTimeoutMinutes));
                        serverGVFSConfig = this.QueryGVFSConfig(tracer, enlistment, retryConfig);

                        cacheServer = this.ResolveCacheServer(tracer, cacheServer, cacheServerResolver, serverGVFSConfig);

                        this.ValidateClientVersions(tracer, enlistment, serverGVFSConfig, showWarnings: true);

                        this.ShowStatusWhileRunning(
                            () =>
                        {
                            cloneResult = this.TryClone(tracer, enlistment, cacheServer, retryConfig, serverGVFSConfig, resolvedLocalCacheRoot);
                            return(cloneResult.Success);
                        },
                            "Cloning",
                            normalizedEnlistmentRootPath);
                    }

                    if (!cloneResult.Success)
                    {
                        tracer.RelatedError(cloneResult.ErrorMessage);
                    }
                }

                if (cloneResult.Success)
                {
                    if (!this.NoPrefetch)
                    {
                        ReturnCode result = this.Execute <PrefetchVerb>(
                            enlistment,
                            verb =>
                        {
                            verb.Commits             = true;
                            verb.SkipVersionCheck    = true;
                            verb.ResolvedCacheServer = cacheServer;
                            verb.ServerGVFSConfig    = serverGVFSConfig;
                        });

                        if (result != ReturnCode.Success)
                        {
                            this.Output.WriteLine("\r\nError during prefetch @ {0}", fullEnlistmentRootPathParameter);
                            exitCode = (int)result;
                        }
                    }

                    if (this.NoMount)
                    {
                        this.Output.WriteLine("\r\nIn order to mount, first cd to within your enlistment, then call: ");
                        this.Output.WriteLine("gvfs mount");
                    }
                    else
                    {
                        this.Execute <MountVerb>(
                            enlistment,
                            verb =>
                        {
                            verb.SkipMountedCheck     = true;
                            verb.SkipVersionCheck     = true;
                            verb.ResolvedCacheServer  = cacheServer;
                            verb.DownloadedGVFSConfig = serverGVFSConfig;
                        });
                    }
                }
                else
                {
                    this.Output.WriteLine("\r\nCannot clone @ {0}", fullEnlistmentRootPathParameter);
                    this.Output.WriteLine("Error: {0}", cloneResult.ErrorMessage);
                    exitCode = (int)ReturnCode.GenericError;
                }
            }
            catch (AggregateException e)
            {
                this.Output.WriteLine("Cannot clone @ {0}:", fullEnlistmentRootPathParameter);
                foreach (Exception ex in e.Flatten().InnerExceptions)
                {
                    this.Output.WriteLine("Exception: {0}", ex.ToString());
                }

                exitCode = (int)ReturnCode.GenericError;
            }
            catch (VerbAbortedException)
            {
                throw;
            }
            catch (Exception e)
            {
                this.ReportErrorAndExit("Cannot clone @ {0}: {1}", fullEnlistmentRootPathParameter, e.ToString());
            }

            Environment.Exit(exitCode);
        }