public static CommandResultsWriter GetExportWriter(CLIExportTagsCmdOptions options)
        {
            CommandResultsWriter?writer;

            switch (options.OutputFileFormat.ToLower())
            {
            case "_dummy":
                writer = new ExportDummyWriter();
                break;

            case "json":
                writer = new JsonWriter();
                break;

            case "text":
                writer = new ExportTextWriter();
                break;

            default:
                WriteOnce.Error(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f"));
                throw new OpException((MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f")));
            }

            //assign the stream as a file or console
            writer.OutputFileName = options.OutputFilePath;
            writer.TextWriter     = GetTextWriter(writer.OutputFileName);

            return(writer);
        }
Esempio n. 2
0
        /// <summary>
        /// Constructor for the class, it initializes various objects
        /// </summary>
        /// <param name="node">Takes in a structured node</param>
        public ManagedAddressResolverAndDns(StructuredNode node, DhcpServer dhcp,
                                            MemBlock local_ip, string name_server, bool forward_queries) :
            base(MemBlock.Reference(dhcp.BaseIP), MemBlock.Reference(dhcp.Netmask),
                 name_server, forward_queries)
        {
            _node          = node;
            _dns_a         = new Dictionary <string, string>();
            _dns_ptr       = new Dictionary <string, string>();
            _ip_addr       = new Dictionary <MemBlock, Address>();
            _addr_ip       = new Dictionary <Address, MemBlock>();
            _blocked_addrs = new Dictionary <Address, MemBlock>();
            mcast_addr     = new List <Address>();
            _tx_counters   = new Dictionary <Address, int>();
            _rx_counters   = new Dictionary <Address, int>();

            _dhcp            = dhcp;
            _local_ip        = local_ip;
            _sync            = new object();
            _udp_translators = new IProtocolTranslator <UdpPacket>[] {
                new MDnsTranslator(local_ip),
                new SipTranslator(local_ip),
                new SsdpTranslator(local_ip)
            };
            _resolver = new WriteOnce <IDnsResolver>();
        }
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            AnalyzeResult analyzeResult = (AnalyzeResult)result;

            //For console output, update write once for same results to console or file
            WriteOnce.TextWriter = TextWriter;

            if (string.IsNullOrEmpty(commandOptions.OutputFilePath))
            {
                WriteOnce.Result("Results");
            }

            JsonSerializer jsonSerializer = new();

            jsonSerializer.Formatting = Formatting.Indented;
            if (TextWriter != null)
            {
                jsonSerializer.Serialize(TextWriter, analyzeResult);
            }

            WriteOnce.NewLine();

            if (autoClose)
            {
                FlushAndClose();
            }
        }
Esempio n. 4
0
        public void SetValue_ShouldThrowIfTheValueIsAlreadySet()
        {
            var wo = new WriteOnce();

            Assert.DoesNotThrow(() => wo.Value = new object());
            Assert.Throws <InvalidOperationException>(() => wo.Value = new object(), Resources.VALUE_ALREADY_SET);
        }
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            ExportTagsResult exportTagsResult = (ExportTagsResult)result;

            //For console output, update write once for same results to console or file
            WriteOnce.TextWriter = TextWriter;

            if (exportTagsResult.TagsList.Count > 0)
            {
                WriteOnce.Result("Results");

                foreach (string tag in exportTagsResult.TagsList)
                {
                    WriteOnce.General(tag);
                }
            }
            else
            {
                WriteOnce.General("No tags found");
            }

            if (autoClose)
            {
                FlushAndClose();
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Only AnalyzeResultsWriter supports an html option
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        private static CommandResultsWriter GetAnalyzeWriter(CLIAnalyzeCmdOptions options)
        {
            CommandResultsWriter?writer;

            switch (options.OutputFileFormat.ToLower())
            {
            case "json":
                writer = new AnalyzeJsonWriter();
                break;

            case "text":
                writer = new AnalyzeTextWriter(options.TextOutputFormat);
                break;

            case "html":
                writer = new AnalyzeHtmlWriter();
                break;

            case "sarif":
                writer = new AnalyzeSarifWriter();
                break;

            default:
                WriteOnce.Error(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f"));
                throw new OpException((MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f")));
            }

            //assign the stream as a file or console
            writer.OutputFileName = options.OutputFilePath;
            writer.TextWriter     = GetTextWriter(writer.OutputFileName);

            return(writer);
        }
Esempio n. 7
0
        private static int VerifyOutputArgsRun(CLIAnalyzeCmdOptions options)
        {
            Logger logger = Utils.SetupLogging(options, true);

            WriteOnce.Log = logger;
            options.Log   = logger;

            //analyze with html format limit checks
            if (options.OutputFileFormat == "html")
            {
                if (!string.IsNullOrEmpty(options.OutputFilePath)) //dependent local files won't be there; TODO look into dir copy to target!
                {
                    WriteOnce.Info("-o output file argument ignored for html format");
                }

                options.OutputFilePath = "output.html";

                if (options.AllowDupTags) //fix #183; duplicates results for html format is not supported which causes filedialog issues

                {
                    WriteOnce.Error(MsgHelp.GetString(MsgHelp.ID.ANALYZE_NODUPLICATES_HTML_FORMAT));
                    throw new OpException(MsgHelp.GetString(MsgHelp.ID.ANALYZE_NODUPLICATES_HTML_FORMAT));
                }

                if (options.SimpleTagsOnly) //won't work for html that expects full data for UI
                {
                    WriteOnce.Error(MsgHelp.GetString(MsgHelp.ID.ANALYZE_SIMPLETAGS_HTML_FORMAT));
                    throw new Exception(MsgHelp.GetString(MsgHelp.ID.ANALYZE_SIMPLETAGS_HTML_FORMAT));
                }
            }

            CommonOutputChecks((CLICommandOptions)options);
            return(RunAnalyzeCommand(options));
        }
Esempio n. 8
0
        private static int VerifyOutputArgsRun(CLIAnalyzeCmdOptions options)
        {
            Logger logger = Utils.SetupLogging(options, true);

            WriteOnce.Log = logger;
            options.Log   = logger;

            //analyze with html format limit checks
            if (options.OutputFileFormat == "html")
            {
                options.OutputFilePath = options.OutputFilePath ?? "output.html";
                string extensionCheck = Path.GetExtension(options.OutputFilePath);
                if (extensionCheck != ".html" && extensionCheck != ".htm")
                {
                    WriteOnce.Info(MsgHelp.GetString(MsgHelp.ID.ANALYZE_HTML_EXTENSION));
                }

                if (options.AllowDupTags) //fix #183; duplicates results for html format is not supported which causes filedialog issues
                {
                    WriteOnce.Error(MsgHelp.GetString(MsgHelp.ID.ANALYZE_NODUPLICATES_HTML_FORMAT));
                    throw new OpException(MsgHelp.GetString(MsgHelp.ID.ANALYZE_NODUPLICATES_HTML_FORMAT));
                }

                if (options.SimpleTagsOnly) //won't work for html that expects full data for UI
                {
                    WriteOnce.Error(MsgHelp.GetString(MsgHelp.ID.ANALYZE_SIMPLETAGS_HTML_FORMAT));
                    throw new Exception(MsgHelp.GetString(MsgHelp.ID.ANALYZE_SIMPLETAGS_HTML_FORMAT));
                }
            }

            CommonOutputChecks((CLICommandOptions)options);
            return(RunAnalyzeCommand(options));
        }
Esempio n. 9
0
        private static int VerifyOutputArgsRun(CLIPackRulesCmdOptions options)
        {
            Logger logger = Utils.SetupLogging(options, true);

            WriteOnce.Log = logger;
            options.Log   = logger;

            if (options.RepackDefaultRules && !string.IsNullOrEmpty(options.OutputFilePath))
            {
                WriteOnce.Info("output file argument ignored for -d option");
            }

            options.OutputFilePath = options.RepackDefaultRules ? Utils.GetPath(Utils.AppPath.defaultRulesPackedFile) : options.OutputFilePath;
            if (string.IsNullOrEmpty(options.OutputFilePath))
            {
                WriteOnce.Error(MsgHelp.GetString(MsgHelp.ID.PACK_MISSING_OUTPUT_ARG));
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.PACK_MISSING_OUTPUT_ARG));
            }
            else
            {
                CommonOutputChecks(options);
            }

            return(RunPackRulesCommand(options));
        }
Esempio n. 10
0
            public TrialState(Node n, TrialState.TrialFinishedCallback cb)
            {
                _node     = n;
                _callback = cb;
                ArrayList con_list = new ArrayList();

                foreach (Connection con in _node.ConnectionTable.GetConnections(ConnectionType.Structured))
                {
                    if (con.Edge is Tunnel.TunnelEdge)
                    {
                        continue;
                    }
                    con_list.Add(con);
                }

                if (con_list.Count == 0)
                {
                    throw new Exception("Cannot initialize a trial state (No usable structured connections).");
                }

                Connection target = (Connection)con_list[_rand.Next(con_list.Count)];

                _target_address = target.Address;
                _target_edge    = target.Edge;
                _state_result   = new WriteOnce <Hashtable>();
                _num_samples    = 0;
                _started        = 0;
            }
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            CLIAnalyzeCmdOptions cLIAnalyzeCmdOptions = (CLIAnalyzeCmdOptions)commandOptions;
            AnalyzeResult        analyzeResult        = (AnalyzeResult)result;

            //For console output, update write once for same results to console or file
            WriteOnce.TextWriter = TextWriter;

            if (string.IsNullOrEmpty(commandOptions.OutputFilePath))
            {
                WriteOnce.Result("Results");
            }

            if (cLIAnalyzeCmdOptions.SimpleTagsOnly)
            {
                List <string> keys = new List <string>(analyzeResult.Metadata.UniqueTags);
                keys.Sort();
                TagsFile tags = new TagsFile();
                tags.Tags = keys.ToArray();
                TextWriter.Write(JsonConvert.SerializeObject(tags, Formatting.Indented));
            }
            else
            {
                JsonSerializer jsonSerializer = new JsonSerializer();
                jsonSerializer.Formatting = Formatting.Indented;
                jsonSerializer.Serialize(TextWriter, analyzeResult);
            }

            WriteOnce.NewLine();

            if (autoClose)
            {
                FlushAndClose();
            }
        }
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            VerifyRulesResult verifyRulesResult = (VerifyRulesResult)result;

            //For console output, update write once for same results to console or file
            WriteOnce.TextWriter = TextWriter;

            if (string.IsNullOrEmpty(commandOptions.OutputFilePath))
            {
                WriteOnce.Result("Results");
            }

            if (verifyRulesResult.ResultCode != VerifyRulesResult.ExitCode.Verified)
            {
                WriteOnce.Any(MsgHelp.GetString(MsgHelp.ID.TAGTEST_RESULTS_FAIL), true, ConsoleColor.Red, WriteOnce.ConsoleVerbosity.Low);
            }
            else
            {
                WriteOnce.Any(MsgHelp.GetString(MsgHelp.ID.TAGTEST_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
            }

            if (verifyRulesResult.RuleStatusList.Count > 0)
            {
                WriteOnce.Result("Rule status");
                foreach (RuleStatus ruleStatus in verifyRulesResult.RuleStatusList)
                {
                    WriteOnce.General(String.Format("Ruleid: {0}, Rulename: {1}, Status: {2}", ruleStatus.RulesId, ruleStatus.RulesName, ruleStatus.Verified));
                }
            }

            if (autoClose)
            {
                FlushAndClose();
            }
        }
Esempio n. 13
0
        public void Value_MayBeNull()
        {
            var wo = new WriteOnce(strict: true);

            Assert.DoesNotThrow(() => wo.Value = null);
            Assert.That(wo.Value, Is.Null);
        }
Esempio n. 14
0
 public BuddyList()
 {
   _node = new WriteOnce<Node>();
   buddyArrayList = new ArrayList();
   _email_to_buddy = new Hashtable();
   _add_to_buddy = new Hashtable(); 
 }
        public static void Write(Result result, CLICommandOptions options)
        {
            CommandResultsWriter?writer = WriterFactory.GetWriter(options);
            string commandCompletedMsg;

            //perform type checking and assign final msg string
            if (result is TagTestResult)
            {
                commandCompletedMsg = "Tag Test";
            }
            else if (result is TagDiffResult)
            {
                commandCompletedMsg = "Tag Diff";
            }
            else if (result is ExportTagsResult)
            {
                commandCompletedMsg = "Export Tags";
            }
            else if (result is VerifyRulesResult)
            {
                commandCompletedMsg = "Verify Rules";
            }
            else if (result is PackRulesResult)
            {
                commandCompletedMsg = "Pack Rules";
            }
            else if (result is AnalyzeResult analyzeResult && options is CLIAnalyzeCmdOptions cLIAnalyzeCmdOptions) //special handling for html format
            {
                commandCompletedMsg = "Analyze";

                //additional prechecks required for analyze html format
                if (cLIAnalyzeCmdOptions.OutputFileFormat == "html")
                {
                    int MAX_HTML_REPORT_FILE_SIZE = 1024 * 1000 * 3;  //warn about potential slow rendering

                    //prechecks
                    if (analyzeResult.ResultCode != AnalyzeResult.ExitCode.Success)
                    {
                        Finalize(writer, commandCompletedMsg);
                        return;
                    }

                    writer?.WriteResults(analyzeResult, cLIAnalyzeCmdOptions);

                    //post checks
                    if (File.Exists(options.OutputFilePath) && new FileInfo(options.OutputFilePath).Length > MAX_HTML_REPORT_FILE_SIZE)
                    {
                        WriteOnce.Info(MsgHelp.GetString(MsgHelp.ID.ANALYZE_REPORTSIZE_WARN));
                    }

                    if (!cLIAnalyzeCmdOptions.SuppressBrowserOpen)
                    {
                        Utils.OpenBrowser(cLIAnalyzeCmdOptions.OutputFilePath);
                    }

                    Finalize(writer, "Analyze");
                    return;
                }
            }
Esempio n. 16
0
 public RelayEdgeCallbackAction(RelayTransportAddress tta, EdgeCreationCallback ecb)
 {
     RelayTA   = tta;
     Ecb       = ecb;
     Exception = new WriteOnce <Exception>();
     Success   = new WriteOnce <bool>();
     Edge      = new WriteOnce <Edge>();
 }
Esempio n. 17
0
 public TunnelEdgeCallbackAction(TunnelTransportAddress tta, EdgeCreationCallback ecb)
 {
     TunnelTA  = tta;
     Ecb       = ecb;
     Exception = new WriteOnce <Exception>();
     Success   = new WriteOnce <bool>();
     Edge      = new WriteOnce <Edge>();
 }
Esempio n. 18
0
 public ReplyState(PType prefix, RequestKey rk)
 {
     _prefix         = prefix;
     RequestKey      = rk;
     RequestDate     = DateTime.UtcNow;
     _reply_timeouts = 0;
     _uri            = new WriteOnce <string>();
     _lid            = 0;
 }
            public void ShouldThrowExceptionWithNameOfVariable()
            {
                var localVariable = new WriteOnce <int>();

                new Action(() => localVariable.Should().HaveValue())
                .Should()
                .Throw <Exception>()
                .And.Message.Should().ContainAll(nameof(localVariable));
            }
        private void WriteDependencies(MetaData metaData)
        {
            WriteOnce.General(MakeHeading("Dependencies"));

            foreach (string s in metaData.UniqueDependencies ?? new List <string>())
            {
                WriteOnce.General(s);
            }
        }
Esempio n. 21
0
 public SocialDnsManager(SocialNode node)
 {
     _node      = node;
     _mappings  = ImmutableDictionary <string, DnsMapping> .Empty;
     _tmappings = ImmutableDictionary <string, DnsMapping> .Empty;
     _sender    = new WriteOnce <IRpcSender>();
     LoadState();
     AddDnsMapping(System.Net.Dns.GetHostName());
 }
Esempio n. 22
0
        /// <summary>
        /// CLI program entry point which defines command verbs and options to running
        /// </summary>
        /// <param name="args"></param>
        static int Main(string[] args)
        {
            int finalResult = (int)Utils.ExitCode.CriticalError;

            Utils.CLIExecutionContext = true;//set manually at start from CLI

            WriteOnce.Verbosity = WriteOnce.ConsoleVerbosity.Medium;
            try
            {
                var argsResult = Parser.Default.ParseArguments <AnalyzeCommandOptions,
                                                                TagDiffCommandOptions,
                                                                TagTestCommandOptions,
                                                                ExportTagsCommandOptions,
                                                                VerifyRulesCommandOptions,
                                                                PackRulesCommandOptions>(args)
                                 .MapResult(
                    (AnalyzeCommandOptions opts) => RunAnalyzeCommand(opts),
                    (TagDiffCommandOptions opts) => RunTagDiffCommand(opts),
                    (TagTestCommandOptions opts) => RunTagTestCommand(opts),
                    (ExportTagsCommandOptions opts) => RunExportTagsCommand(opts),
                    (VerifyRulesCommandOptions opts) => RunVerifyRulesCommand(opts),
                    (PackRulesCommandOptions opts) => RunPackRulesCommand(opts),
                    errs => 1
                    );

                finalResult = argsResult;
            }
            catch (Exception) //a controlled exit; details not req but written out in command to ensure NuGet+CLI both can console write and log the error
            {
                if (!String.IsNullOrEmpty(Utils.LogFilePath))
                {
                    WriteOnce.Info(ErrMsg.FormatString(ErrMsg.ID.RUNTIME_ERROR_NAMED, Utils.LogFilePath), true, WriteOnce.ConsoleVerbosity.Low, false);
                }
                else
                {
                    WriteOnce.Info(ErrMsg.GetString(ErrMsg.ID.RUNTIME_ERROR_PRELOG), true, WriteOnce.ConsoleVerbosity.Medium, false);
                }

                return(finalResult);//avoid double reporting
            }

            if (finalResult == (int)Utils.ExitCode.CriticalError) //case where exception not thrown but result was still a failure; Run() vs constructor exception etc.
            {
                if (!String.IsNullOrEmpty(Utils.LogFilePath))
                {
                    WriteOnce.Info(ErrMsg.FormatString(ErrMsg.ID.RUNTIME_ERROR_UNNAMED, Utils.LogFilePath), true, WriteOnce.ConsoleVerbosity.Low, false);
                }
                else
                {
                    WriteOnce.Info(ErrMsg.GetString(ErrMsg.ID.RUNTIME_ERROR_PRELOG), true, WriteOnce.ConsoleVerbosity.Medium, false);
                }
            }


            return(finalResult);
        }
Esempio n. 23
0
        public SupportedFeaturesProfile(SupportedFeaturesProfile other)
        {
            m_supportedFeatureMapping = new WriteOnce <Dictionary <string, int> >();
            if (other.m_supportedFeatureMapping.Value == null)
            {
                return;
            }

            m_supportedFeatureMapping.Value = new Dictionary <string, int>(other.m_supportedFeatureMapping.Value);
        }
Esempio n. 24
0
        public void WriteOnce_SetsTwice_ReturnsOriginal()
        {
            WriteOnce <string> txt = new WriteOnce <string> {
                Value = "Hello world"
            };

            txt.Value = "Hello again";

            Assert.True(txt.Value == "Hello world");
        }
Esempio n. 25
0
 public CreationState(EdgeCreationCallback ecb,
                      Queue ipq, int port,
                      TcpEdgeListener tel)
 {
     ECB            = ecb;
     IPAddressQueue = ipq;
     Port           = port;
     TEL            = tel;
     Result         = new WriteOnce <object>();
 }
Esempio n. 26
0
        /// <summary>
        /// Checks that either output filepath is valid or console verbosity is not visible to ensure
        /// some output can be achieved...other command specific inputs that are relevant to both CLI
        /// and NuGet callers are checked by the commands themselves
        /// </summary>
        /// <param name="options"></param>
        private static void CommonOutputChecks(CLICommandOptions options)
        {
            //validate requested format
            string fileFormatArg = options.OutputFileFormat;

            string[] validFormats =
            {
                "html",
                "text",
                "json",
                "sarif"
            };

            string[] checkFormats;
            if (options is CLIAnalyzeCmdOptions cliAnalyzeOptions)
            {
                checkFormats  = validFormats;
                fileFormatArg = cliAnalyzeOptions.OutputFileFormat;
            }
            else if (options is CLIPackRulesCmdOptions cliPackRulesOptions)
            {
                checkFormats  = validFormats.Skip(2).Take(1).ToArray();
                fileFormatArg = cliPackRulesOptions.OutputFileFormat;
            }
            else
            {
                checkFormats = validFormats.Skip(1).Take(2).ToArray();
            }

            bool isValidFormat = checkFormats.Any(v => v.Equals(fileFormatArg.ToLower()));

            if (!isValidFormat)
            {
                WriteOnce.Error(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f"));
                throw new OpException(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f"));
            }

            //validate output is not empty if no file output specified
            if (string.IsNullOrEmpty(options.OutputFilePath))
            {
                if (string.Equals(options.ConsoleVerbosityLevel, "none", StringComparison.OrdinalIgnoreCase))
                {
                    WriteOnce.Error(MsgHelp.GetString(MsgHelp.ID.CMD_NO_OUTPUT));
                    throw new Exception(MsgHelp.GetString(MsgHelp.ID.CMD_NO_OUTPUT));
                }
                else if (string.Equals(options.ConsoleVerbosityLevel, "low", StringComparison.OrdinalIgnoreCase))
                {
                    WriteOnce.SafeLog("Verbosity set low.  Detailed output limited.", NLog.LogLevel.Info);
                }
            }
            else
            {
                ValidFileWritePath(options.OutputFilePath);
            }
        }
Esempio n. 27
0
        public void WriteOnce_SetsAndGets_ReturnsInstance()
        {
            WriteOnce <string> txt = new WriteOnce <string> {
                Value = "Hello world"
            };

            Assert.True(txt.Value == "Hello world");
            Assert.True(txt.ToString() == "Hello world");
            Assert.True(txt.ValueOrDefault == "Hello world");
            Assert.True((string)txt == "Hello world");
        }
Esempio n. 28
0
 public SocialNode(NodeConfig brunetConfig, IpopConfig ipopConfig,
                   RSACryptoServiceProvider rsa)
     : base(brunetConfig, ipopConfig)
 {
     _friends = ImmutableDictionary <string, SocialUser> .Empty;
     _rsa     = rsa;
     _address = AppNode.Node.Address.ToString();
     _user    = new WriteOnce <SocialUser>();
     _mco     = new ManagedConnectionOverlord(AppNode.Node);
     AppNode.Node.AddConnectionOverlord(_mco);
 }
Esempio n. 29
0
        public void GetValue_ShouldThrowIfTheValueIsNotSet()
        {
            var wo = new WriteOnce();

            object val;

            Assert.Throws <InvalidOperationException>(() => val = wo.Value, Resources.NO_VALUE);

            wo.Value = new object();
            Assert.DoesNotThrow(() => val = wo.Value);
        }
		public void EqualityTestCase()
		{
			Assert.AreEqual(wo, wo, "#1");
			wo.Value = 1;
			Assert.AreEqual(wo, wo, "#2");
			
			WriteOnce<object> wObj = new WriteOnce<object>();
			Assert.AreEqual(wObj, wObj, "#3");
			wObj.Value = new object();
			Assert.AreEqual(wObj, wObj, "#4");
		}
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            JsonSerializer jsonSerializer = new JsonSerializer();

            jsonSerializer.Formatting = Formatting.Indented;

            //For console output, update write once for same results to console or file
            WriteOnce.TextWriter = TextWriter;

            if (string.IsNullOrEmpty(commandOptions.OutputFilePath))
            {
                WriteOnce.Result("Results");
            }

            if (TextWriter != null)
            {
                if (result is TagTestResult)
                {
                    jsonSerializer.Serialize(TextWriter, (TagTestResult)result);
                }
                else if (result is TagDiffResult)
                {
                    jsonSerializer.Serialize(TextWriter, (TagDiffResult)result);
                }
                else if (result is VerifyRulesResult)
                {
                    jsonSerializer.Serialize(TextWriter, (VerifyRulesResult)result);
                }
                else if (result is ExportTagsResult)
                {
                    jsonSerializer.Serialize(TextWriter, (ExportTagsResult)result);
                }
                else if (result is PackRulesResult packRulesResult)
                {
                    jsonSerializer.Serialize(TextWriter, packRulesResult.Rules);//write rules array only to disk
                }
                else
                {
                    throw new System.Exception("Unexpected object type for json writer");
                }
            }
            else
            {
                WriteOnce.Log?.Error("Unexpected null TextWriter");
            }

            WriteOnce.NewLine();

            if (autoClose)
            {
                FlushAndClose();
            }
        }
Esempio n. 32
0
 /// <summary>
 /// Ensure output file path can be written to
 /// </summary>
 /// <param name="filePath"></param>
 private static void ValidFileWritePath(string filePath)
 {
     try
     {
         File.WriteAllText(filePath, "");//verify ability to write to location
     }
     catch (Exception)
     {
         WriteOnce.Error(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_FILE_OR_DIR, filePath));
         throw new OpException(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_FILE_OR_DIR, filePath));
     }
 }
Esempio n. 33
0
    /**
     * Prefered constructor for a Connection
     */
    public Connection(Edge e, Address a,
		      string connectiontype,
		      StatusMessage sm, LinkMessage peerlm)
    {
      _e = e;
      _a = a;
      _ct = String.Intern(connectiontype);
      _stat = sm;
      _lm = peerlm;
      _creation_time = DateTime.UtcNow;
      MainType = StringToMainType(_ct);
      _as_dict = new WriteOnce<ListDictionary>();
      _sub_type = new WriteOnce<string>();
    }
    /// <summary>
    /// Constructor for the class, it initializes various objects
    /// </summary>
    /// <param name="node">Takes in a structured node</param>
    public ManagedAddressResolverAndDns(StructuredNode node, DhcpServer dhcp,
        MemBlock local_ip, string name_server, bool forward_queries) :
      base(MemBlock.Reference(dhcp.BaseIP), MemBlock.Reference(dhcp.Netmask),
          name_server, forward_queries)
    {
      _node = node;
      _dns_a = new Dictionary<string, string>();
      _dns_ptr = new Dictionary<string, string>();
      _ip_addr = new Dictionary<MemBlock, Address>();
      _addr_ip = new Dictionary<Address, MemBlock>();
      _blocked_addrs = new Dictionary<Address, MemBlock>();
      mcast_addr = new List<Address>();
      _tx_counters = new Dictionary<Address, int>();
      _rx_counters = new Dictionary<Address, int>();

      _dhcp = dhcp;
      _local_ip = local_ip;
      _sync = new object();
      _udp_translators = new IProtocolTranslator<UdpPacket>[] {
        new MDnsTranslator(local_ip),
        new SipTranslator(local_ip),
        new SsdpTranslator(local_ip)
      };
      _resolver = new WriteOnce<IDnsResolver>();
    }
 public LinkProtocolState(Linker l, TransportAddress ta, Edge e) {
   _linker = l;
   _node = l.LocalNode;
   _contype = l.ConType;
   _target_lock = null;
   _lm_reply = new WriteOnce<LinkMessage>();
   _x = new WriteOnce<Exception>();
   _con = new WriteOnce<Connection>();
   _ta = ta;
   _is_finished = 0;
   //Setup the edge:
   _e = e;
   _result = Result.None;
 }
Esempio n. 36
0
 public SocialNode(NodeConfig brunetConfig, IpopConfig ipopConfig,
                   string certificate) : base(brunetConfig, ipopConfig) {
   _friends = new Dictionary<string, SocialUser>();
   _bfriends = new List<string>();
   _sync = new object();
   _status = StatusTypes.Offline.ToString();
   _global_block = new WriteOnce<bool>();
   _local_user = new SocialUser();
   _local_user.Certificate = certificate;
   _local_user.IP = _marad.LocalIP;
   _marad.AddDnsMapping(_local_user.Alias, _local_user.IP, true);
   _bso = AppNode.SecurityOverlord;
   _bso.CertificateHandler.AddCACertificate(_local_user.GetCert().X509);
   _bso.CertificateHandler.AddSignedCertificate(_local_user.GetCert().X509);
 }
Esempio n. 37
0
 public TunnelEdgeCallbackAction(TunnelTransportAddress tta, EdgeCreationCallback ecb)
 {
   TunnelTA = tta;
   Ecb = ecb;
   Exception = new WriteOnce<Exception>();
   Success = new WriteOnce<bool>();
   Edge = new WriteOnce<Edge>();
 }
Esempio n. 38
0
      public TrialState(Node n, TrialState.TrialFinishedCallback cb) {
        _node = n;
        _callback = cb;
        ArrayList con_list = new ArrayList();
        foreach (Connection con in _node.ConnectionTable.GetConnections(ConnectionType.Structured))
        {
          if (con.Edge is Tunnel.TunnelEdge) {
            continue;
          }
          con_list.Add(con);
        }

        if (con_list.Count == 0) {
          throw new Exception("Cannot initialize a trial state (No usable structured connections).");
        }
        
        Connection target = (Connection) con_list[_rand.Next(con_list.Count)];
        _target_address = target.Address;
        _target_edge = target.Edge;
        _state_result = new WriteOnce<Hashtable>();
        _num_samples = 0;
        _started = 0;
      }
Esempio n. 39
0
 public RelayEdgeCallbackAction(RelayTransportAddress tta, EdgeCreationCallback ecb)
 {
   RelayTA = tta;
   Ecb = ecb;
   Exception = new WriteOnce<Exception>();
   Success = new WriteOnce<bool>();
   Edge = new WriteOnce<Edge>();
 }
		public void Setup()
		{
			wo = new WriteOnce<int>();
		}
Esempio n. 41
0
 public SocialNode(NodeConfig brunetConfig, IpopConfig ipopConfig,
   RSACryptoServiceProvider rsa) 
   : base(brunetConfig, ipopConfig) {
   _friends = ImmutableDictionary<string, SocialUser>.Empty;
   _rsa = rsa;
   _address = AppNode.Node.Address.ToString();
   _user = new WriteOnce<SocialUser>();
   _mco = new ManagedConnectionOverlord(AppNode.Node);
   AppNode.Node.AddConnectionOverlord(_mco);
 }
Esempio n. 42
0
 public Connector(Node local, ISender ps, ConnectToMessage ctm, ConnectionOverlord co, object state)
 {
   _sync = new Object();
   _local_node = local;
   _is_finished = 0;
   _got_ctms = new ArrayList();
   _sender = ps;
   _ctm = ctm;
   _co = co;
   _task = new ConnectorTask(ps);
   _abort = new WriteOnce<AbortCheck>();
   State = state;
 }
Esempio n. 43
0
 /**
  * Constructor.
  * @param n local node
  */
 protected MapReduceTask(Node n) {
   _node = n;
   _task_name = new WriteOnce<string>();
 }
Esempio n. 44
0
 public ReplyState(PType prefix, RequestKey rk) {
   _prefix = prefix;
   RequestKey = rk;
   RequestDate = DateTime.UtcNow;
   _reply_timeouts = 0;
   _uri = new WriteOnce<string>();
   _lid = 0;
 }
Esempio n. 45
0
 public CreationState(EdgeCreationCallback ecb,
                      Queue ipq, int port,
                      TcpEdgeListener tel)
 {
   ECB = ecb;
   IPAddressQueue = ipq;
   Port = port;
   TEL = tel;
   Result = new WriteOnce<object>();
 }
Esempio n. 46
0
 public EdgeWorker(Node n, TransportAddress ta) {
   _n = n;
   _ta = ta;
   _result = new WriteOnce<EWResult>();
 }
Esempio n. 47
0
 public ReplyState(RequestKey rk) {
   RequestKey = rk;
   RequestDate = DateTime.UtcNow;
   _reply_timeouts = 0;
   _uri = new WriteOnce<string>();
   _lid = 0;
 }