Ejemplo n.º 1
0
 public static string ToJSON(this Exception ex)
 {
     Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
     settings.Formatting = Newtonsoft.Json.Formatting.Indented;
     var text = Newtonsoft.Json.JsonConvert.SerializeObject(ex, settings);
     return text;
 }
Ejemplo n.º 2
0
 /// <summary>
 /// 將object資料轉成Json字串
 /// </summary>
 /// <param name="ob">待轉換的object</param>
 /// <returns>對應的Json字串</returns>
 public string ObjectToJsonString(object ob)
 {
     Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
     settings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
     settings.CheckAdditionalContent = false;
     return Newtonsoft.Json.JsonConvert.SerializeObject(ob, settings);
 }
Ejemplo n.º 3
0
 public JsonFormatter()
 {
     bodyType = 0x350;
     _settings = new Newtonsoft.Json.JsonSerializerSettings();
     _settings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects;
     _settings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
     _settings.Formatting = Newtonsoft.Json.Formatting.Indented;
     _settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;
     _settings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
 }
Ejemplo n.º 4
0
 public Response()
 {
     ContentType = "application/json";
     Contents = s =>
     {
         var settings = new Newtonsoft.Json.JsonSerializerSettings()
         {
             Formatting = Newtonsoft.Json.Formatting.Indented,
             ContractResolver = new CamelCasePropertyNamesContractResolver()
         };
         var json = Newtonsoft.Json.JsonConvert.SerializeObject(GetResponseBodyObject(), settings);
         var jsonBytes = Encoding.UTF8.GetBytes(json);
         s.Write(jsonBytes, 0, jsonBytes.Length);
     };
 }
Ejemplo n.º 5
0
        public SDKResult transaction(TransactionConfig config)
        {
            Newtonsoft.Json.JsonSerializerSettings jss = new Newtonsoft.Json.JsonSerializerSettings();
            Newtonsoft.Json.Serialization.DefaultContractResolver dcr = new Newtonsoft.Json.Serialization.DefaultContractResolver();
            dcr.DefaultMembersSearchFlags |= System.Reflection.BindingFlags.NonPublic;
            jss.ContractResolver = dcr;
            string configJson = Newtonsoft.Json.JsonConvert.SerializeObject(config, jss);

            JObject jo = JObject.Parse(configJson);
            jo.Add("merchant_id", this.merchant_id);
            string paramsJson = jo.ToString();

            try {
                var cli = new WebClient();
                cli.Headers[HttpRequestHeader.ContentType] = "application/json";
                String response = cli.UploadString("http://pierup.asuscomm.com:8686/merchant_api/v1/transaction/pay_by_pier", paramsJson);
                JObject responseJSON = JObject.Parse(response);
                return new SDKResult(
                    (int)responseJSON.GetValue ("code")==200,
                    (string)responseJSON.GetValue ("message"),
                    (string)responseJSON.GetValue ("code"),
                    responseJSON.GetValue ("result").ToObject<Dictionary<string,string>>()
                );
            } catch (WebException e) {
                string responseText = null;
                if (e.Response != null) {
                    var responseStream = e.Response.GetResponseStream();

                    if (responseStream != null) {
                        var reader = new StreamReader (responseStream);
                        responseText = reader.ReadToEnd();
                    }
                }

                if (responseText != null) {
                    JObject responseJSON = JObject.Parse(responseText);
                    return new SDKResult(
                        (int)responseJSON.GetValue ("code")==200,
                        (string)responseJSON.GetValue ("message"),
                        (string)responseJSON.GetValue ("code"),
                        responseJSON.GetValue ("result").ToObject<Dictionary<string,string>>()
                    );
                } else {
                    return new SDKResult(false, e.ToString(), null, null);
                }
            }
        }
Ejemplo n.º 6
0
        public void Start()
        {
            var nodeConfigString = File.ReadAllText("config.json");
            var settings = new Newtonsoft.Json.JsonSerializerSettings
            {
                TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto,
            };
            var config = Newtonsoft.Json.JsonConvert.DeserializeObject<JSONConfig>(nodeConfigString, settings);

            // config Syslog listener
            if (config.syslog.listenerEnabled)
            {
                var listener = new SyslogListener();
                Action<int> startListener = listener.Start;
                startListener.BeginInvoke(config.syslog.listenerPort, null, null);
            }

            // config PollEngine
            foreach (var node in (config.nodes ?? new JSONConfigNode[0]))
            {
                var pollNode = Activator.CreateInstance(typeof(PollingEngine).Assembly.GetType(node.type), new object[] { node.name, node.groups ?? new string[0], node.settings }) as PollNode;
                PollingEngine.TryAdd(pollNode);
            }
            PollingEngine.StartPolling();

            // config HTTP API
            var hostConfig = new HttpSelfHostConfiguration("http://127.0.0.1:" + config.http.listenerPort);
            // Remove the XML formatter
            hostConfig.Formatters.Remove(hostConfig.Formatters.XmlFormatter);
            hostConfig.Formatters.Add(new RazorFormatter());
            hostConfig.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto;
            hostConfig.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
            hostConfig.Formatters.JsonFormatter.SerializerSettings.Error += (x, y) =>
            {
                return;
            };
            hostConfig.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
            // Attribute routing.
            hostConfig.MapHttpAttributeRoutes();
            hostConfig.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            hostConfig.Filters.Add(new ApiExceptionFilterAttribute());

            httpServer = new HttpSelfHostServer(hostConfig);
            httpServer.OpenAsync().Wait();
        }
        public override string ToString()
        {
            List<Newtonsoft.Json.JsonConverter> myconverters = new List<Newtonsoft.Json.JsonConverter>();
            myconverters.Add(new CustomConvertersColorToRGB());
            myconverters.Add(new CustomConvertersAxis());
            myconverters.Add(new CustomConvertersLegend());
            myconverters.Add(new CustomConverterEnum());
            myconverters.Add(new CustomConverterTrendLine());

            Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings()
            {
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                Converters = myconverters
            };

            string s = string.Empty;
            s = Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.None, settings);
            return s;
        }
Ejemplo n.º 8
0
        public static void MakeRequest()
        {
            string url = @"";
            HttpClient client = new HttpClient();
            //client.BaseAddress = new Uri(url);

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = (HttpResponseMessage)client.GetAsync("http://localhost:4681/api/project").Result;

            if (response.IsSuccessStatusCode)
            {
                var pl = response.Content.ReadAsStringAsync().Result;

                Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
                setting.CheckAdditionalContent = false;

                DataSet ds = Newtonsoft.Json.JsonConvert.DeserializeObject<DataSet>(pl,setting);

            }
        }
        public void Does_Respect_Serialization_Settings()
        {
            // Arrange
            InvoiceEmailHeader header = new InvoiceEmailHeader() {
                Issuer = "Service Provider",
                Filename = "bill.pdf",
                InvoiceId = "XF4321-89",
                Paid = true,
                InvoiceDate = DateTime.Parse("2015-01-10T00:00:00+01:00"),
                DueDate = DateTime.Parse("2015-01-30T12:00:00+01:00"),
                PaidDate = DateTime.Parse("2015-01-10T08:35:12+01:00"),
                Amount = 39.90m,
                Currency = "USD"
            };
            var jsonSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings { StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml, Formatting = Newtonsoft.Json.Formatting.None };

            // Act
            var result = header.AsJSON(false, jsonSerializerSettings);

            // Assert
            Assert.IsNotNull(result);
            Assert.IsFalse(string.IsNullOrWhiteSpace(result));
        }
Ejemplo n.º 10
0
        protected void PersistProcessStatus(ChainRequest request)
        {
            ProcessSnapShot mysh = new ProcessSnapShot(request.ProcessTypeId, request.ProcessInstanceId);
            try
            {
                Newtonsoft.Json.JsonSerializerSettings x= new Newtonsoft.Json.JsonSerializerSettings();
                x.ReferenceLoopHandling=Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                mysh.jsonContext = Newtonsoft.Json.JsonConvert.SerializeObject(request,Newtonsoft.Json.Formatting.None,x);

                mysh.CurrentStep = request.CurrentStepIndex;
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(request.ProcessConfigConn);
                CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
                CloudTable table = tableClient.GetTableReference(Configuration.ButlerWorkflowStatus);
                TableOperation insertOperation = TableOperation.InsertOrReplace(mysh);
                table.CreateIfNotExists();
                table.Execute(insertOperation);
            }
            catch (Exception X)
            {
                string txtMessage = string.Format("[{0}] Persist Process Status Error at process {1} instance {2}: error messagase  {3}", this.GetType().FullName, request.ProcessInstanceId, request.ProcessTypeId, X.Message);
                Trace.TraceError(txtMessage);
                throw new Exception(txtMessage);
            }
        }
Ejemplo n.º 11
0
 internal string StringValue(INotifyPropertyChanged host)
 {
     string result = null;
     object val = propInfo.GetValue(host, emptyArgs);
     if (val == null)
         result = null;
     else if (propInfo.PropertyType == typeof(bool))
         result = (bool)val ? "t" : "f";
     else if (kind == PropertyKind.Enumerable)
     {
         Newtonsoft.Json.JsonSerializerSettings jsSettings = new Newtonsoft.Json.JsonSerializerSettings();
         jsSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
         result = Newtonsoft.Json.JsonConvert.SerializeObject(val, Newtonsoft.Json.Formatting.None, jsSettings);
     }
     else
         result = val.ToString();
     return result;
 }
Ejemplo n.º 12
0
 public static Type TryJsonDeserialize <Type>(string value, Newtonsoft.Json.JsonSerializerSettings settings)
 {
     if (string.IsNullOrWhiteSpace(value))
     {
         return(default);
 partial void UpdateJsonSerializerSettings(Newtonsoft.Json.JsonSerializerSettings settings);
Ejemplo n.º 14
0
 public static TConfig ParseJson <TConfig>(string josn, Newtonsoft.Json.JsonSerializerSettings jsonSerializerSettings) where TConfig : ConfigBase, new()
 {
     return(Newtonsoft.Json.JsonConvert.DeserializeObject <TConfig>(josn, jsonSerializerSettings));
 }
        private void workTimer_Tick(object sender, ElapsedEventArgs e)
        {
            try
            {
                // Log.Info($"Checking for new alerts...");

                string readEmailFile = "ReadEmails.id";

                List <String> seenMessages = new List <String>();
                if (File.Exists(readEmailFile))
                {
                    seenMessages = File.ReadAllLines(readEmailFile).ToList();
                }

                List <Message> NewMessages = FetchUnseenMessages(Email_Pop_Server,
                                                                 Convert.ToInt32(Email_Pop_Port),
                                                                 Convert.ToBoolean(Email_Pop_SSL),
                                                                 Email_Pop_User,
                                                                 Email_Pop_Password,
                                                                 seenMessages);

                string threatid = "";

                for (int i = 0; i < NewMessages.Count; i++)

                {
                    Log.Info($"New email: " + NewMessages[i].Headers.Subject);

                    OpenPop.Mime.MessagePart htmlBody = NewMessages[i].FindFirstHtmlVersion();
                    EmailSubject = NewMessages[i].Headers.Subject;

                    if (htmlBody != null)
                    {
                        threatid = htmlBody.GetBodyAsText();
                    }

                    int start = threatid.IndexOf("analyze/threats/") + 16;
                    int end   = threatid.IndexOf("/overview") - threatid.IndexOf("analyze/threats/") - 16;
                    threatid = threatid.Substring(start, end);
                    // Log.Info($"{nameof(Service.S1Notifier)} Threat ID: " + threatid);

                    var JsonSettings = new Newtonsoft.Json.JsonSerializerSettings
                    {
                        NullValueHandling     = Newtonsoft.Json.NullValueHandling.Include,
                        MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore
                    };
                    var    restClient     = new RestClientInterface();
                    string resourceString = ManagementServer + "/web/api/v1.6/threats/" + threatid;
                    // threatid = "59d5239e75c5fa05cf6d74d0";
                    // 59d5239e75c5fa05cf6d74d0
                    // string resourceString = ManagementServer + "/web/api/v1.6/threats/59d5239e75c5fa05cf6d74d0";
                    restClient.EndPoint = resourceString;
                    restClient.Method   = HttpVerb.GET;
                    var     batch_string = restClient.MakeRequest(Token).ToString();
                    dynamic threat       = Newtonsoft.Json.JsonConvert.DeserializeObject(batch_string, JsonSettings);
                    EmailBody = Newtonsoft.Json.Linq.JObject.Parse(batch_string.ToString()).ToString(Newtonsoft.Json.Formatting.Indented);
                    Log.Info($"Threat Details: " + EmailBody);

                    // Agent info ==============================================================================================
                    string agentid = threat.agent;
                    resourceString      = ManagementServer + "/web/api/v1.6/agents/" + agentid;
                    restClient.EndPoint = resourceString;
                    restClient.Method   = HttpVerb.GET;
                    var     agent_string = restClient.MakeRequest(Token).ToString();
                    dynamic agent        = Newtonsoft.Json.JsonConvert.DeserializeObject(agent_string, JsonSettings);

                    // Forensic info ==============================================================================================
                    resourceString      = ManagementServer + "/web/api/v1.6/threats/" + threatid + "/forensics/export/json";
                    restClient.EndPoint = resourceString;
                    restClient.Method   = HttpVerb.GET;
                    var     forensic_string = restClient.MakeRequest(Token).ToString();
                    dynamic forensic        = Newtonsoft.Json.JsonConvert.DeserializeObject(forensic_string, JsonSettings);
                    string  forensic_output = Newtonsoft.Json.Linq.JObject.Parse(forensic_string.ToString()).ToString(Newtonsoft.Json.Formatting.Indented);

                    // Get the assembly information
                    System.Reflection.Assembly assemblyInfo = System.Reflection.Assembly.GetExecutingAssembly();
                    // Location is where the assembly is run from
                    string assemblyLocation = assemblyInfo.CodeBase;
                    assemblyLocation = assemblyLocation.Substring(0, assemblyLocation.LastIndexOf('/'));
                    string report_file = assemblyLocation + "/email.html";
                    string local_path  = new Uri(report_file).LocalPath;
                    string report      = File.ReadAllText(local_path);

                    string timestamp   = threat.created_date.ToString();
                    string description = threat.description;
                    string resolved    = threat.resolved;
                    string status      = threat.mitigation_status;

                    string filename = threat.file_id.display_name;
                    string filepath = threat.file_id.path;
                    string filehash = threat.file_id.content_hash;

                    string rawdata = EmailBody;

                    switch (status)
                    {
                    case "0":
                        status = "<p class='S1Mitigated'>Mitigated</p>";
                        break;

                    case "1":
                        status = "<p class='S1Active'>Active</p>";
                        break;

                    case "2":
                        status = "<p class='S1Blocked'>Blocked</p>";
                        break;

                    case "3":
                        status = "<p class='S1Suspicious'>Suspicious</p>";
                        break;

                    case "4":
                        status = "<p class='S1Suspicious'>Pending</p>";
                        break;

                    case "5":
                        status = "<p class='S1Suspicious'>Suspicious cancelled</p>";
                        break;

                    default:
                        status = "<p class='S1Mitigated'>Mitigated</p>";
                        break;
                    }

                    switch (resolved.ToLower())
                    {
                    case "true":
                        resolved = "<p class='S1Green'>Yes</p>";
                        break;

                    case "false":
                        resolved = "<p class='S1Red'>No</p>";
                        break;

                    default:
                        resolved = "<p class='S1Red'>No</p>";
                        break;
                    }

                    string threatlink = "<a href='" + ManagementServer + "/#/analyze/threats/" + threatid + "/overview'>" + threatid + "</a>";
                    report = report.Replace("$threatid$", threatlink);
                    report = report.Replace("$timestamp$", timestamp);
                    report = report.Replace("$description$", description);
                    report = report.Replace("$resolved$", resolved);
                    report = report.Replace("$status$", status);

                    report = report.Replace("$filename$", filename);
                    report = report.Replace("$filepath$", filepath);
                    report = report.Replace("$filehash$", "<a href='https://www.virustotal.com/latest-scan/" + filehash + "'>" + filehash + "</a>");

                    string code = SyntaxHighlightJson(rawdata.Replace("\r\n", "<br/>").Replace(" ", "&nbsp;"));
                    // Log.Info($"{nameof(Service.S1Notifier)} Code: " + code);
                    report = report.Replace("$rawdata$", "<span class='Code'>" + code + "</span>");

                    string forensicdata = SyntaxHighlightJson(forensic_output.Replace("\r\n", "<br/>").Replace(" ", "&nbsp;"));
                    report = report.Replace("$forensicdata$", "<span class='Code'>" + forensicdata + "</span>");

                    string computername = agent.network_information.computer_name;
                    string os           = agent.software_information.os_name;
                    string agentversion = agent.agent_version;
                    string agentip      = agent.external_ip;
                    string machinetype  = agent.hardware_information.machine_type;

                    report = report.Replace("$computername$", computername);
                    report = report.Replace("$os$", os);
                    report = report.Replace("$agentversion$", agentversion);
                    report = report.Replace("$agentip$", agentip);
                    report = report.Replace("$machinetype$", machinetype);

                    EmailBody = report;

                    SendEmail();
                }

                File.WriteAllLines(readEmailFile, seenMessages);
            }
            catch (Exception ex)
            {
                Log.Error($"Error in mail processing: " + ex.Message);
            }
        }
Ejemplo n.º 16
0
 public MockProviderService(int port, bool enableSsl, string consumerName, string providerName, PactConfig config, IPAddress ipAddress, Newtonsoft.Json.JsonSerializerSettings jsonSerializerSettings)
     : this(
         baseUri => new RubyHttpHost(baseUri, consumerName, providerName, config, ipAddress),
         port,
         enableSsl,
         baseUri => new AdminHttpClient(baseUri, jsonSerializerSettings))
 {
 }
Ejemplo n.º 17
0
        private void Generate()
        {
            try
            {
                // webBrowserExecutiveSummary.DocumentText = "<html><body>Gathering data, but if the message is here for a minute, there is an error somewhere...<br/></body></html>";
                // webBrowserExecutiveSummary.ScriptErrorsSuppressed = true;
                labelEmailMessage.Visible = false;

                if (!checkBoxHTML.Checked && !checkBoxPDF.Checked)
                {
                    MessageBox.Show("Please select at least one of HTML or PDF output", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (checkBoxEmail.Checked && CheckEmailConfig() == false)
                {
                    return;
                }

                string token = crypto.Decrypt(crypto.GetSettings("ExcelPlugIn", "Token"));
                userName = crypto.GetSettings("ExcelPlugIn", "Username");

                // Agent Summary ==========================================================================================================
                string resourceString = mgmtServer + "/web/api/v1.6/agents/count-by-filters?participating_fields=" +
                                        "software_information__os_type,software_information__os_arch,hardware_information__machine_type," +
                                        "network_information__domain,network_status,configuration__learning_mode,is_pending_uninstall," +
                                        "is_up_to_date,infected,policy_id,is_active";
                var restClient = new RestClientInterface(resourceString);
                restClient.EndPoint = resourceString;
                restClient.Method   = HttpVerb.GET;
                var results      = restClient.MakeRequest(token).ToString();
                var JsonSettings = new Newtonsoft.Json.JsonSerializerSettings
                {
                    NullValueHandling     = Newtonsoft.Json.NullValueHandling.Include,
                    MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore
                };
                dynamic agent_summary = Newtonsoft.Json.JsonConvert.DeserializeObject(results, JsonSettings);

                // webBrowserExecutiveSummary.DocumentText = "<html><body>" + results + "</body></html>";

                string AgentsInstalled         = agent_summary.total_count.ToString();
                string AgentsIntalledFormatted = string.Format("{0:n0}", Convert.ToInt32(AgentsInstalled));

                string Connected        = agent_summary.network_status.connected == null ? "0" : agent_summary.network_status.connected.ToString();
                string Disconnected     = agent_summary.network_status.disconnected == null ? "0" : agent_summary.network_status.disconnected.ToString();
                int    PercentConnected = (int)Math.Round((double)(100 * Convert.ToInt32(Connected)) / (Convert.ToInt32(Disconnected) + Convert.ToInt32(Connected)));

                string IsActiveTrue  = agent_summary.is_active["true"] == null ? "0" : agent_summary.is_active["true"].ToString();
                string IsActiveFalse = agent_summary.is_active["false"] == null ? "0" : agent_summary.is_active["false"].ToString();
                // MessageBox.Show(IsActiveTrue + " - " + IsActiveFalse);
                int PercentActive = (int)Math.Round((double)(100 * Convert.ToInt32(IsActiveTrue)) / (Convert.ToInt32(IsActiveTrue) + Convert.ToInt32(IsActiveFalse)));

                // Get the assembly information
                System.Reflection.Assembly assemblyInfo = System.Reflection.Assembly.GetExecutingAssembly();
                // Location is where the assembly is run from
                string assemblyLocation = assemblyInfo.CodeBase;
                assemblyLocation = assemblyLocation.Substring(0, assemblyLocation.LastIndexOf('/'));

                string timeStamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");

                string reportPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                System.IO.Directory.CreateDirectory(reportPath + "\\SentinelOne Reports");

                string report_file   = assemblyLocation + "/S1 Exec Report.html";
                string report_target = reportPath + "\\SentinelOne Reports\\" + "s1_" + serverName.Substring(0, serverName.IndexOf(".")) + "_" + timeStamp + ".html";

                string localPath   = new Uri(report_file).LocalPath;
                string localTarget = new Uri(report_target).LocalPath;
                string workingdir  = new Uri(assemblyLocation).LocalPath;

                string report = File.ReadAllText(localPath);

                #region Replace
                report = report.Replace("$Server$", serverName);

                report = report.Replace("$ReportPeriod$", Globals.ReportPeriod);
                report = report.Replace("$StartDate$", Globals.StartDate);
                report = report.Replace("$EndDate$", Globals.EndDate);

                report = report.Replace("$AI$", AgentsIntalledFormatted);
                report = report.Replace("$PA$", PercentActive.ToString() + "%");
                report = report.Replace("$MG$", Globals.MostAtRiskGroup);
                report = report.Replace("$MU$", Globals.MostAtRiskUser);
                report = report.Replace("$ME$", Globals.MostAtRiskEndpoint);

                report = report.Replace("$TABLE-THREATDATA$", Globals.ThreatData);
                report = report.Replace("$TABLE-DETECTIONENGINE$", Globals.DetectionEngine);
                report = report.Replace("$TABLE-INFECTEDFILES$", Globals.InfectedFiles);
                report = report.Replace("$TABLE-MOSTATRISKGROUPS$", Globals.MostAtRiskGroups);
                report = report.Replace("$TABLE-MOSTATRISKUSERS$", Globals.MostAtRiskUsers);
                report = report.Replace("$TABLE-MOSTATRISKENDPOINTS$", Globals.MostAtRiskEndpoints);

                report = report.Replace("$ThreatDataLabel$", Globals.ThreatDataLabel);
                report = report.Replace("$DetectionEnginesLabel$", Globals.DetectionEnginesLabel);
                report = report.Replace("$InfectedFilesLabel$", Globals.InfectedFilesLabel);
                report = report.Replace("$MostAtRiskGroupsLabel$", Globals.MostAtRiskGroupsLabel);
                report = report.Replace("$MostAtRiskUsersLabel$", Globals.MostAtRiskUsersLabel);
                report = report.Replace("$MostAtRiskEndpointsLabel$", Globals.MostAtRiskEndpointsLabel);

                report = report.Replace("$ThreatDataValue$", Globals.ThreatDataValue);
                report = report.Replace("$DetectionEnginesValue$", Globals.DetectionEnginesValue);
                report = report.Replace("$InfectedFilesValue$", Globals.InfectedFilesValue);
                report = report.Replace("$MostAtRiskGroupsValue$", Globals.MostAtRiskGroupsValue);
                report = report.Replace("$MostAtRiskUsersValue$", Globals.MostAtRiskUsersValue);
                report = report.Replace("$MostAtRiskEndpointsValue$", Globals.MostAtRiskEndpointsValue);

                report = report.Replace("$TABLE-NETWORKSTATUS$", Globals.NetworkStatus);
                report = report.Replace("$TABLE-ENDPOINTOS$", Globals.EndpointOS);
                report = report.Replace("$TABLE-ENDPOINTVERSION$", Globals.EndpointVersion);

                report = report.Replace("$NetworkStatusLabel$", Globals.NetworkStatusLabel);
                report = report.Replace("$EndpointOSLabel$", Globals.EndpointOSLabel);
                report = report.Replace("$EndpointVersionLabel$", Globals.EndpointVersionLabel);

                report = report.Replace("$NetworkStatusValue$", Globals.NetworkStatusValue);
                report = report.Replace("$EndpointOSValue$", Globals.EndpointOSValue);
                report = report.Replace("$EndpointVersionValue$", Globals.EndpointVersionValue);

                report = report.Replace("$TABLE-TOPAPPLICATIONS$", Globals.TopApplications);
                report = report.Replace("$TopApplicationsLabel$", Globals.TopApplicationsLabel);
                report = report.Replace("$TopApplicationsValue$", Globals.TopApplicationsValue);

                report = report.Replace("$ReportTimestamp$", DateTime.UtcNow.ToString("f") + " (UTC)");
                report = report.Replace("$ReportUser$", userName);
                #endregion

                // Threat Summary ================================================================================================================
                resourceString      = mgmtServer + "/web/api/v1.6/threats/summary";
                restClient          = new RestClientInterface(resourceString);
                restClient.EndPoint = resourceString;
                restClient.Method   = HttpVerb.GET;
                var     resultsThreats = restClient.MakeRequest(token).ToString();
                dynamic threat_summary = Newtonsoft.Json.JsonConvert.DeserializeObject(resultsThreats, JsonSettings);

                string ActiveThreats     = threat_summary.active.ToString();
                string MitigatedThreats  = threat_summary.mitigated.ToString();
                string SuspiciousThreats = threat_summary.suspicious.ToString();
                string BloackedThreats   = threat_summary.blocked.ToString();

                report = report.Replace("$TT$", string.Format("{0:n0}", Convert.ToInt32(Globals.TotalThreats)));
                if (Globals.ActiveThreats == "")
                {
                    Globals.ActiveThreats = "0";
                }
                report = report.Replace("$AT$", string.Format("{0:n0}", Convert.ToInt32(Globals.ActiveThreats)));
                report = report.Replace("$AUT$", string.Format("{0:n0}", Convert.ToInt32(Globals.ActiveAndUnresolvedThreats)));
                report = report.Replace("$UnresolvedThreatOnly$", Globals.UnresolvedThreatOnly.ToString().ToLower());

                File.WriteAllText(localTarget, report);

                HTMLAttachment = localTarget;

                if (checkBoxHTML.Checked)
                {
                    System.Diagnostics.Process.Start(localTarget);
                }

                // webBrowserExecutiveSummary.Url = new Uri("file://127.0.0.1/c$/temp/S1Report.html");
                // webBrowserExecutiveSummary.IsWebBrowserContextMenuEnabled = false;
                // webBrowserExecutiveSummary.Url = new Uri(report_target);

                if (checkBoxPDF.Checked)
                {
                    Process p = new Process();
                    p.StartInfo.WorkingDirectory = workingdir;
                    p.StartInfo.FileName         = workingdir + "\\wkhtmltopdf.exe";
                    p.StartInfo.Arguments        = "--lowquality " +
                                                   "--print-media-type " +
                                                   "--page-size Letter " +
                                                   "--footer-spacing 2 " +
                                                   "--footer-right \"[page] of [toPage]\" " +
                                                   "--footer-left \"[isodate]    [time]\" " +
                                                   "--footer-font-size 6 " +
                                                   "\"" + localTarget + "\"" +
                                                   " \"" + Path.ChangeExtension(localTarget, ".pdf") + "\"";

                    // Stop the process from opening a new window
                    p.StartInfo.CreateNoWindow = true;

                    p.StartInfo.UseShellExecute        = false;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.RedirectStandardError  = true;
                    p.Start();
                    string output = p.StandardError.ReadToEnd();
                    p.WaitForExit();
                    p.Close();

                    PDFAttachment = Path.ChangeExtension(localTarget, ".pdf");
                    System.Diagnostics.Process.Start(Path.ChangeExtension(localTarget, ".pdf"));
                }

                if (checkBoxEmail.Checked)
                {
                    SendEmail();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error extracting report data", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 18
0
        public override async Task <bool> InvokeAsync(string paramList)
        {
            const string JsonFileFormat = "json/{0}.json";

            IEnumerable <string> filesToExport;

            if (string.IsNullOrWhiteSpace(paramList))
            {
                filesToExport = _Realm.GameData.AvailableSheets;
            }
            else
            {
                filesToExport = paramList.Split(' ').Select(_ => _Realm.GameData.FixName(_));
            }

            var successCount = 0;
            var failCount    = 0;

            foreach (var name in filesToExport)
            {
                var target = new FileInfo(Path.Combine(_Realm.GameVersion, string.Format(JsonFileFormat, name)));
                try {
                    var sheet = _Realm.GameData.GetSheet(name);

                    if (!target.Directory.Exists)
                    {
                        target.Directory.Create();
                    }

                    var output = new List <JObject>();

                    if (sheet is XivSheet2 <XivSubRow> s2)
                    {
                        var record = new JObject();
                        foreach (var row in s2)
                        {
                            record.Add(row.FullKey, row.DefaultValue?.ToString());
                        }
                        output.Add(record);
                    }
                    else
                    {
                        foreach (var row in sheet)
                        {
                            var record = new JObject();

                            if (sheet is IXivSubRow || row[0] == null || row[0].ToString() == "0")
                            {
                                continue;
                            }

                            _Columns = new Queue <RelationalColumn>(sheet.Header.Columns);
                            while (_Columns.Count > 0)
                            {
                                var column  = _Columns.Dequeue();
                                var element = ProcessSingleColumn(column, row);

                                if (element != null)
                                {
                                    AddItemToRecord(element, column, ref record);
                                }
                            }
                            output.Add(record);
                        }
                    }

                    var settings = new Newtonsoft.Json.JsonSerializerSettings()
                    {
                        Formatting        = Newtonsoft.Json.Formatting.None,
                        NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
                    };

                    File.WriteAllText(target.FullName, Newtonsoft.Json.JsonConvert.SerializeObject(output, settings));

                    ++successCount;
                }
                catch (Exception e) {
                    OutputError("Export of {0} failed: {1}", name, e.Message);
                    try { if (target.Exists)
                          {
                              target.Delete();
                          }
                    } catch { }
                    ++failCount;
                }
            }
            OutputInformation("{0} files exported, {1} failed", successCount, failCount);

            return(true);
        }
Ejemplo n.º 19
0
        /// <summary> Initialization function for this storage provider. </summary>
        /// <see cref="IProvider.Init"/>
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            Name = name;
            serviceId = providerRuntime.ServiceId.ToString();

            if (!config.Properties.ContainsKey(DataConnectionStringPropertyName) || string.IsNullOrWhiteSpace(config.Properties[DataConnectionStringPropertyName]))
                throw new ArgumentException("DataConnectionString property not set");

            dataConnectionString = config.Properties["DataConnectionString"];

            if (config.Properties.ContainsKey(TableNamePropertyName))
                tableName = config.Properties[TableNamePropertyName];

            isDeleteStateOnClear = config.Properties.ContainsKey(DeleteOnClearPropertyName) &&
                "true".Equals(config.Properties[DeleteOnClearPropertyName], StringComparison.OrdinalIgnoreCase);

            Log = providerRuntime.GetLogger("Storage.AzureTableStorage." + id);

            var initMsg = string.Format("Init: Name={0} ServiceId={1} Table={2} DeleteStateOnClear={3}",
                Name, serviceId, tableName, isDeleteStateOnClear);

            if (config.Properties.ContainsKey(UseJsonFormatPropertyName))
                useJsonFormat = "true".Equals(config.Properties[UseJsonFormatPropertyName], StringComparison.OrdinalIgnoreCase);

            this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(), config);
            initMsg = String.Format("{0} UseJsonFormat={1}", initMsg, useJsonFormat);

            Log.Info((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, initMsg);
            Log.Info((int)AzureProviderErrorCode.AzureTableProvider_ParamConnectionString, "AzureTableStorage Provider is using DataConnectionString: {0}", ConfigUtilities.PrintDataConnectionInfo(dataConnectionString));
            tableDataManager = new GrainStateTableDataManager(tableName, dataConnectionString, Log);
            return tableDataManager.InitTableAsync();
        }
        public async Task <IActionResult> Get([FromQuery] Int32 hid, String tgtcurr)
        {
            if (hid <= 0)
            {
                return(BadRequest("No Home Inputted"));
            }

            String usrName = String.Empty;

            if (Startup.UnitTestMode)
            {
                usrName = UnitTestUtility.UnitTestUser;
            }
            else
            {
                var usrObj = HIHAPIUtility.GetUserClaim(this);
                usrName = usrObj.Value;
            }
            if (String.IsNullOrEmpty(usrName))
            {
                return(BadRequest("User cannot recognize"));
            }

            List <FinanceDocPlanExgRateViewModel> listVMs = new List <FinanceDocPlanExgRateViewModel>();
            SqlConnection  conn        = null;
            SqlCommand     cmd         = null;
            SqlDataReader  reader      = null;
            String         queryString = "";
            String         strErrMsg   = "";
            HttpStatusCode errorCode   = HttpStatusCode.OK;

            try
            {
                queryString = @"SELECT [ID]
                                  ,[HID]
                                  ,[DOCTYPE]
                                  ,[TRANDATE]
                                  ,[TRANCURR]
                                  ,[DESP]
                                  ,[EXGRATE]
                                  ,[EXGRATE_PLAN]
                                  ,[EXGRATE_PLAN2]
                                  ,[TRANCURR2]
                                  ,[EXGRATE2]
                              FROM [dbo].[t_fin_document]
	                            WHERE [HID] = @hid
	                            AND ( ( [EXGRATE_PLAN] = 1 AND [TRANCURR] = @curr )
		                            OR ( [EXGRATE_PLAN2] = 1 AND [TRANCURR2] = @curr ) )"        ;

                using (conn = new SqlConnection(Startup.DBConnectionString))
                {
                    await conn.OpenAsync();

                    // Check Home assignment with current user
                    try
                    {
                        HIHAPIUtility.CheckHIDAssignment(conn, hid, usrName);
                    }
                    catch (Exception)
                    {
                        errorCode = HttpStatusCode.BadRequest;
                        throw;
                    }

                    cmd = new SqlCommand(queryString, conn);
                    cmd.Parameters.AddWithValue("@hid", hid);
                    cmd.Parameters.AddWithValue("@curr", tgtcurr);
                    reader = cmd.ExecuteReader();

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            FinanceDocPlanExgRateViewModel avm = new FinanceDocPlanExgRateViewModel();
                            Int32 idx = 0;
                            avm.DocID    = reader.GetInt32(idx++);
                            avm.HID      = reader.GetInt32(idx++);
                            avm.DocType  = reader.GetInt16(idx++);
                            avm.TranDate = reader.GetDateTime(idx++);
                            avm.TranCurr = reader.GetString(idx++);
                            avm.Desp     = reader.GetString(idx++);
                            if (reader.IsDBNull(idx))
                            {
                                ++idx;
                            }
                            else
                            {
                                avm.ExgRate = reader.GetDecimal(idx++);
                            }
                            if (reader.IsDBNull(idx))
                            {
                                ++idx;
                            }
                            else
                            {
                                avm.ExgRate_Plan = reader.GetBoolean(idx++);
                            }
                            if (reader.IsDBNull(idx))
                            {
                                ++idx;
                            }
                            else
                            {
                                avm.ExgRate_Plan2 = reader.GetBoolean(idx++);
                            }
                            if (reader.IsDBNull(idx))
                            {
                                ++idx;
                            }
                            else
                            {
                                avm.TranCurr2 = reader.GetString(idx++);
                            }
                            if (reader.IsDBNull(idx))
                            {
                                ++idx;
                            }
                            else
                            {
                                avm.ExgRate2 = reader.GetDecimal(idx++);
                            }


                            listVMs.Add(avm);
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine(exp.Message);
                strErrMsg = exp.Message;
                if (errorCode == HttpStatusCode.OK)
                {
                    errorCode = HttpStatusCode.InternalServerError;
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                    reader = null;
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                    cmd = null;
                }
                if (conn != null)
                {
                    conn.Dispose();
                    conn = null;
                }
            }

            if (errorCode != HttpStatusCode.OK)
            {
                switch (errorCode)
                {
                case HttpStatusCode.Unauthorized:
                    return(Unauthorized());

                case HttpStatusCode.NotFound:
                    return(NotFound());

                case HttpStatusCode.BadRequest:
                    return(BadRequest(strErrMsg));

                default:
                    return(StatusCode(500, strErrMsg));
                }
            }

            var setting = new Newtonsoft.Json.JsonSerializerSettings
            {
                DateFormatString = HIHAPIConstants.DateFormatPattern,
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };

            return(new JsonResult(listVMs, setting));
        }
        public async Task <IActionResult> Get([FromQuery] Int32 hid = 0, Int32 top = 100, Int32 skip = 0)
        {
            String usrName = String.Empty;

            if (Startup.UnitTestMode)
            {
                usrName = UnitTestUtility.UnitTestUser;
            }
            else
            {
                var usrObj = HIHAPIUtility.GetUserClaim(this);
                usrName = usrObj.Value;
            }
            if (String.IsNullOrEmpty(usrName))
            {
                return(BadRequest("User cannot recognize"));
            }

            BaseListViewModel <LibMovieGenreViewModel> listVm = new BaseListViewModel <LibMovieGenreViewModel>();
            SqlConnection  conn        = null;
            SqlCommand     cmd         = null;
            SqlDataReader  reader      = null;
            String         queryString = "";
            String         strErrMsg   = "";
            HttpStatusCode errorCode   = HttpStatusCode.OK;

            try
            {
                queryString = this.getQueryString(true, top, skip, null, hid);

                using (conn = new SqlConnection(Startup.DBConnectionString))
                {
                    await conn.OpenAsync();

                    // Check Home assignment with current user
                    if (hid > 0)
                    {
                        try
                        {
                            HIHAPIUtility.CheckHIDAssignment(conn, hid, usrName);
                        }
                        catch (Exception)
                        {
                            errorCode = HttpStatusCode.BadRequest;
                            throw;
                        }
                    }

                    cmd    = new SqlCommand(queryString, conn);
                    reader = cmd.ExecuteReader();
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            listVm.TotalCount = reader.GetInt32(0);
                            break;
                        }
                    }
                    reader.NextResult();

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            LibMovieGenreViewModel vm = new LibMovieGenreViewModel();
                            HIHDBUtility.LibMovieGenre_DB2VM(reader, vm);
                            listVm.Add(vm);
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine(exp.Message);

                strErrMsg = exp.Message;
                if (errorCode == HttpStatusCode.OK)
                {
                    errorCode = HttpStatusCode.InternalServerError;
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                    reader = null;
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                    cmd = null;
                }
                if (conn != null)
                {
                    conn.Dispose();
                    conn = null;
                }
            }

            if (errorCode != HttpStatusCode.OK)
            {
                switch (errorCode)
                {
                case HttpStatusCode.Unauthorized:
                    return(Unauthorized());

                case HttpStatusCode.NotFound:
                    return(NotFound());

                case HttpStatusCode.BadRequest:
                    return(BadRequest(strErrMsg));

                default:
                    return(StatusCode(500, strErrMsg));
                }
            }

            var setting = new Newtonsoft.Json.JsonSerializerSettings
            {
                DateFormatString = HIHAPIConstants.DateFormatPattern,
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };

            return(new JsonResult(listVm, setting));
        }
Ejemplo n.º 22
0
        public static int Main(string[] args)
        {
            UserInterface.SetConsoleTitle(null);

            Kalmit.BlobLibrary.OverrideGetBlobWithSHA256 =
                defaultGetter => (hashSHA256 => GetFileFromHashSHA256(hashSHA256) ?? defaultGetter(hashSHA256));

            //  Build interface based on sample from https://github.com/natemcmaster/CommandLineUtils/blob/be230400aaae2f00b29dac005c1b59a386a42165/docs/samples/subcommands/builder-api/Program.cs

            var app = new CommandLineApplication
            {
                Name        = "BotEngine",
                Description = "Run bots from the commandline.\nSee " + generalGuideLink + " for a detailed guide.",
            };

            app.HelpOption(inherited: true);

            app.VersionOption(template: "-v|--version", shortFormVersion: "BotEngine console version " + AppVersionId);

            app.Command("start-bot", startBotCmd =>
            {
                startBotCmd.Description = "Start a bot on this machine. The bot will continue running until you stop it or it stops itself.";
                startBotCmd.ThrowOnUnexpectedArgument = false;

                startBotCmd.OnExecute(() =>
                {
                    void dotnetConsoleWriteProblemCausingAbort(string line)
                    {
                        DotNetConsole.WriteLine("");

                        var colorBefore = DotNetConsole.ForegroundColor;

                        DotNetConsole.ForegroundColor = ConsoleColor.Yellow;

                        DotNetConsole.WriteLine(line);

                        DotNetConsole.ForegroundColor = colorBefore;
                    }

                    var sessionStartTime     = DateTimeOffset.UtcNow;
                    var sessionStartTimeText = sessionStartTime.ToString("yyyy-MM-ddTHH-mm-ss");
                    var sessionId            = sessionStartTimeText + "-" + Kalmit.CommonConversion.StringBase16FromByteArray(GetRandomBytes(6));

                    Exception sessionException = null;

                    var botSessionDirectory =
                        System.IO.Path.Combine(
                            System.IO.Directory.GetCurrentDirectory(), "bot-session", sessionId);

                    var logFileName = "session." + sessionId + ".jsonl";

                    var logFilePath = System.IO.Path.Combine(botSessionDirectory, logFileName);

                    Action <LogEntry> appendLogEntry = null;

                    {
                        System.IO.Stream logStream = null;

                        try
                        {
                            System.IO.Directory.CreateDirectory(botSessionDirectory);

                            logStream = new System.IO.FileStream(logFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);

                            DotNetConsole.WriteLine($"I am recording a log of this session to file '{ logFilePath }'");

                            appendLogEntry = logEntry =>
                            {
                                logEntry.time = DateTimeOffset.UtcNow;

                                var settings = new Newtonsoft.Json.JsonSerializerSettings
                                {
                                    NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                                };

                                var serializedLogEntry =
                                    System.Text.Encoding.UTF8.GetBytes(
                                        Newtonsoft.Json.JsonConvert.SerializeObject(logEntry, settings));

                                var serializedLogEntryWithNewline =
                                    serializedLogEntry.Concat(new byte[] { 13, 10 }).ToArray();

                                logStream.Write(serializedLogEntryWithNewline);

                                logStream.Flush();
                            };
                        }
                        catch (Exception e)
                        {
                            dotnetConsoleWriteProblemCausingAbort("Failed to open log file: " + e?.ToString());
                            return(1);
                        }
                    }

                    try
                    {
                        var botSourceParamName        = "--bot-source";
                        var botConfigurationParamName = "--bot-configuration";

                        var botSourceParamInstruction = "Add the '" + botSourceParamName + "' argument to specify the directory containing a bot. Following is an example: " + botSourceParamName + @"=""C:\bots\bot-to-start""";

                        (bool isPresent, string argumentValue)argumentFromParameterName(string parameterName)
                        {
                            var match =
                                args
                                .Select(arg => Regex.Match(arg, parameterName + "(=(.*)|)", RegexOptions.IgnoreCase))
                                .FirstOrDefault(match => match.Success);

                            if (match == null)
                            {
                                return(false, null);
                            }

                            if (match.Groups[1].Length < 1)
                            {
                                return(true, null);
                            }

                            return(true, match?.Groups[2].Value);
                        }
Ejemplo n.º 23
0
 public void TestJsonNet()
 {
     var p1 = new Person { Name = "zz" };
     Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
     settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
     var st2r = Newtonsoft.Json.JsonConvert.SerializeObject(p1, Newtonsoft.Json.Formatting.Indented, settings);
     TestModel mo = new TestModel();
     mo.sub = new SubTestModel();
     var ss = mo.ToJson();
     var model = Winchannel_Win10.Model.BaseModel.Create<TestModel>(ss);
 }
Ejemplo n.º 24
0
        public ActionResult Edit(int?id, string UrlReferrer, string HostingEntityName, string AssociatedType, string defaultview)
        {
            if (!User.CanEdit("T_ShiftMealTime") || !CustomAuthorizationBeforeEdit(id, HostingEntityName, AssociatedType))
            {
                return(RedirectToAction("Index", "Error"));
            }
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            T_ShiftMealTime t_shiftmealtime = db.T_ShiftMealTimes.Find(id);

            // NEXT-PREVIOUS DROP DOWN CODE
            TempData.Keep();
            string json = "";

            if (TempData["T_ShiftMealTimelist"] == null)
            {
                json = Newtonsoft.Json.JsonConvert.SerializeObject(db.T_ShiftMealTimes.Select(z => new { ID = z.Id, DisplayValue = z.DisplayValue }).ToList());
            }
            else
            {
                ViewBag.EntityT_ShiftMealTimeDisplayValueEdit = TempData["T_ShiftMealTimelist"];
                json = Newtonsoft.Json.JsonConvert.SerializeObject(TempData["T_ShiftMealTimelist"]);
            }

            Newtonsoft.Json.JsonSerializerSettings serSettings = new    Newtonsoft.Json.JsonSerializerSettings();
            serSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
            var lst = Newtonsoft.Json.JsonConvert.DeserializeObject <IEnumerable <object> >(json, serSettings);

            ViewBag.EntityT_ShiftMealTimeDisplayValueEdit = new SelectList(lst, "ID", "DisplayValue");
            //
            if (t_shiftmealtime == null)
            {
                return(HttpNotFound());
            }
            if (string.IsNullOrEmpty(defaultview))
            {
                defaultview = "Edit";
            }
            GetTemplatesForEdit(defaultview);
            // NEXT-PREVIOUS DROP DOWN CODE
            SelectList            selitm  = new SelectList(lst, "ID", "DisplayValue");
            List <SelectListItem> newList = selitm.ToList();

            if (Request.UrlReferrer != null && Request.UrlReferrer.AbsolutePath.EndsWith("/T_ShiftMealTime/Create"))
            {
                newList.Insert(0, (new SelectListItem {
                    Text = t_shiftmealtime.DisplayValue, Value = t_shiftmealtime.Id.ToString()
                }));
                ViewBag.EntityT_ShiftMealTimeDisplayValueEdit = newList;
                TempData["T_ShiftMealTimelist"] = newList.Select(z => new { ID = z.Value, DisplayValue = z.Text });
            }
            else if (!newList.Exists(p => p.Value == Convert.ToString(t_shiftmealtime.Id)))
            {
                if (newList.Count > 0)
                {
                    newList[0].Text  = t_shiftmealtime.DisplayValue;
                    newList[0].Value = t_shiftmealtime.Id.ToString();
                }
                else
                {
                    newList.Insert(0, (new SelectListItem {
                        Text = t_shiftmealtime.DisplayValue, Value = t_shiftmealtime.Id.ToString()
                    }));
                }
                ViewBag.EntityT_ShiftMealTimeDisplayValueEdit = newList;
                TempData["T_ShiftMealTimelist"] = newList.Select(z => new { ID = z.Value, DisplayValue = z.Text });
            }
            //
            if (UrlReferrer != null)
            {
                ViewData["T_ShiftMealTimeParentUrl"] = UrlReferrer;
            }
            if (ViewData["T_ShiftMealTimeParentUrl"] == null && Request.UrlReferrer != null && !Request.UrlReferrer.AbsolutePath.EndsWith("/T_ShiftMealTime") && !Request.UrlReferrer.AbsolutePath.EndsWith("/T_ShiftMealTime/Edit/" + t_shiftmealtime.Id + "") && !Request.UrlReferrer.AbsolutePath.EndsWith("/T_ShiftMealTime/Create"))
            {
                ViewData["T_ShiftMealTimeParentUrl"] = Request.UrlReferrer;
            }
            ViewData["HostingEntityName"] = HostingEntityName;
            ViewData["AssociatedType"]    = AssociatedType;
            LoadViewDataBeforeOnEdit(t_shiftmealtime);
            ViewBag.T_ShiftMealTimeIsHiddenRule       = checkHidden("T_ShiftMealTime", "OnEdit", false);
            ViewBag.T_ShiftMealTimeIsGroupsHiddenRule = checkHidden("T_ShiftMealTime", "OnEdit", true);
            ViewBag.T_ShiftMealTimeIsSetValueUIRule   = checkSetValueUIRule("T_ShiftMealTime", "OnEdit");
            return(View(t_shiftmealtime));
        }
        private Func <object, Value> BuildProtoConverter()
        {
            // Create reusable JsonSerializer to reduce allocations
            var jsonSettings = new Newtonsoft.Json.JsonSerializerSettings()
            {
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            };

            jsonSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
            // The default serialization of these reflection types really isn't useful, so
            // just call ToString on them instead.
            jsonSettings.Converters.Add(new ToStringJsonConverter(typeof(MemberInfo)));
            jsonSettings.Converters.Add(new ToStringJsonConverter(typeof(Assembly)));
            jsonSettings.Converters.Add(new ToStringJsonConverter(typeof(Module)));
            jsonSettings.Converters.Add(new ToStringJsonConverter(typeof(System.IO.Stream)));

            jsonSettings.Error = (sender, args) =>
            {
                // Serialization of properties that throws exceptions should not break everything
                InternalLogger.Debug(args.ErrorContext.Error, "GoogleStackdriver(Name={0}): Error serializing exception property: {1}", Name, args.ErrorContext.Member);
                args.ErrorContext.Handled = true;
            };
            var jsonSerializer = Newtonsoft.Json.JsonSerializer.CreateDefault(jsonSettings);

            return(o => {
                try
                {
                    switch (Convert.GetTypeCode(o))
                    {
                    case TypeCode.Empty:
                        return Value.ForNull();

                    case TypeCode.Boolean:
                        return Value.ForBool(Convert.ToBoolean(o));

                    case TypeCode.Decimal:
                    case TypeCode.Double:
                    case TypeCode.Single:
                        return Value.ForNumber(Convert.ToDouble(o));

                    case TypeCode.Byte:
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                    case TypeCode.Int32:
                    case TypeCode.UInt32:
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                        if (o is System.Enum)
                        {
                            break;      // Let StringEnumConverter handle formatting
                        }
                        return Value.ForNumber(Convert.ToDouble(o));

                    case TypeCode.String:
                    case TypeCode.Char:
                        return Value.ForString(o.ToString());
                    }
                    return ProtoConverter.Convert(JToken.FromObject(o, jsonSerializer));
                }
                catch
                {
                    // Reset the JsonSerializer as it now can be in a bad state
                    jsonSerializer = Newtonsoft.Json.JsonSerializer.CreateDefault(jsonSettings);
                    throw;
                }
            });
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Be careful, camel case is the default.
 /// </summary>
 /// <param name="value"></param>
 /// <param name="serializerSettings"></param>
 public JsonTypeResult(T value, Newtonsoft.Json.JsonSerializerSettings serializerSettings) : base(value, serializerSettings)
 {
 }
Ejemplo n.º 27
0
 public void JsonSettings(Newtonsoft.Json.JsonSerializerSettings jsonSerializerSettings)
 {
 }
Ejemplo n.º 28
0
        public void GetData()
        {
            try
            {
                #region Create worksheet
                // Creates a worksheet for "Threats" if one does not already exist
                // =================================================================================================================
                Excel.Worksheet threatsWorksheet;
                try
                {
                    threatsWorksheet = (Excel.Worksheet)(ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Worksheets.get_Item("Agent Data");
                    threatsWorksheet.Activate();
                }
                catch
                {
                    threatsWorksheet      = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ActiveWorkbook.Worksheets.Add() as Excel.Worksheet;
                    threatsWorksheet.Name = "Agent Data";
                    threatsWorksheet.Activate();
                }
                #endregion

                #region Clear worksheet
                // Clear spreadsheet
                eHelper.Clear();
                #endregion

                #region Get Data

                #region Get data from server
                // Extract data from SentinelOne Management Server (Looping Calls)
                // =================================================================================================================
                mgmtServer = crypto.GetSettings("ExcelPlugIn", "ManagementServer");
                string token = crypto.Decrypt(crypto.GetSettings("ExcelPlugIn", "Token"));
                userName = crypto.GetSettings("ExcelPlugIn", "Username");

                crypto.SetSettings("ExcelPlugIn", "AgentQuery", textBoxQuery.Text);
                crypto.SetSettings("ExcelPlugIn", "AgentReturnAll", checkBoxAll.Checked.ToString());

                string query = "";
                if (textBoxQuery.Text != "" && checkBoxAll.Checked == false)
                {
                    query = "&query=" + textBoxQuery.Text;
                }
                else
                {
                }

                string        limit          = "limit=" + Globals.ApiBatch.ToString();
                bool          Gogo           = true;
                string        skip           = "&skip=";
                string        last_id        = "";
                int           skip_count     = 0;
                StringBuilder results        = new StringBuilder("[");
                int           maxColumnWidth = 80;
                dynamic       threats        = "";
                dynamic       agents         = "";
                dynamic       agentsIterate  = "";
                int           rowCountTemp   = 0;

                var JsonSettings = new Newtonsoft.Json.JsonSerializerSettings
                {
                    NullValueHandling     = Newtonsoft.Json.NullValueHandling.Include,
                    MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore
                };

                formMsg.StopProcessing = false;
                formMsg.Message("Loading agent data: " + rowCount.ToString("N0"),
                                eHelper.ToReadableStringUpToSec(stopWatch.Elapsed) + " elapsed", allowCancel: true);

                this.Opacity       = 0;
                this.ShowInTaskbar = false;

                int percentComplete = 0;

                var restClient = new RestClientInterface();

                stopWatch.Start();

                if (Globals.ServerVersion.Contains("v1."))
                {
                    #region v1 API using limit
                    while (Gogo)
                    {
                        resourceString      = mgmtServer + "/web/api/v1.6/agents?" + limit + skip + skip_count.ToString() + query;
                        restClient.EndPoint = resourceString;
                        restClient.Method   = HttpVerb.GET;
                        var batch_string = restClient.MakeRequest(token).ToString();
                        threats      = Newtonsoft.Json.JsonConvert.DeserializeObject(batch_string, JsonSettings);
                        rowCountTemp = (int)threats.Count;
                        skip_count   = skip_count + Globals.ApiBatch;
                        results.Append(batch_string.TrimStart('[').TrimEnd(']', '\r', '\n')).Append(",");

                        rowCount = rowCount + rowCountTemp;

                        if (rowCountTemp < Globals.ApiBatch)
                        {
                            Gogo = false;
                        }

                        percentComplete = (int)Math.Round((double)(100 * rowCount) / Globals.TotalAgents);
                        formMsg.Message("Loading " + rowCount.ToString("N0") + " of " + Globals.TotalAgents.ToString("N0") + " agents (" + percentComplete.ToString() + "%)...",
                                        eHelper.ToReadableStringUpToSec(stopWatch.Elapsed) + " elapsed", allowCancel: true);
                        if (formMsg.StopProcessing == true)
                        {
                            formMsg.Hide();
                            return;
                        }
                    }
                    #endregion
                }
                else
                {
                    #region v2 API using iterator
                    while (Gogo)
                    {
                        resourceString      = mgmtServer + "/web/api/v1.6/agents/iterator?" + limit + last_id + query;
                        restClient.EndPoint = resourceString;
                        restClient.Method   = HttpVerb.GET;
                        var res = restClient.MakeRequest(token).ToString();
                        agentsIterate = Newtonsoft.Json.JsonConvert.DeserializeObject(res, JsonSettings);
                        rowCountTemp  = (int)agentsIterate.data.Count;
                        agents        = agentsIterate.data;
                        last_id       = "&last_id=" + agentsIterate.last_id;
                        skip_count    = skip_count + Globals.ApiBatch;

                        results.Append(agents.ToString().TrimStart('[').TrimEnd(']', '\r', '\n')).Append(",");

                        rowCount = rowCount + rowCountTemp;

                        if (agentsIterate.last_id == null)
                        {
                            Gogo = false;
                        }

                        percentComplete = (int)Math.Round((double)(100 * rowCount) / Globals.TotalAgents);
                        formMsg.Message("Iterating data for " + rowCount.ToString("N0") + " of " + Globals.TotalAgents.ToString("N0") + " agents for reference (" + percentComplete.ToString() + "%)...",
                                        eHelper.ToReadableStringUpToSec(stopWatch.Elapsed) + " elapsed", allowCancel: true);
                        if (formMsg.StopProcessing == true)
                        {
                            formMsg.Hide();
                            return;
                        }
                    }
                    #endregion
                }

                stopWatch.Stop();
                formMsg.Hide();

                Globals.ApiUrl = resourceString;

                // results.ToString().TrimEnd(',', ' ');
                results.Length--;
                results.Append("]");

                threats = Newtonsoft.Json.JsonConvert.DeserializeObject(results.ToString(), JsonSettings);

                #endregion

                #region Parse attribute headers
                JArray ja = JArray.Parse(results.ToString());
                // Stop processing if no data found
                if (ja.Count == 0)
                {
                    (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Cells[1, 1] = "No agent data found";
                    (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A2", "A2").Select();
                    (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Columns.AutoFit();
                    formMsg.Hide();
                    return;
                }

                Dictionary <string, object>           dictObj          = ja[0].ToObject <Dictionary <string, object> >();
                List <KeyValuePair <string, string> > AttribCollection = new List <KeyValuePair <string, string> >();
                int AttribNo = 0;

                for (int index = 0; index < dictObj.Count; index++)
                {
                    var    Level1   = dictObj.ElementAt(index);
                    string dataType = "String";
                    dataType = eHelper.GetDataType(Level1);

                    if (dataType == "Object")
                    {
                        foreach (KeyValuePair <string, object> Level2 in ((JObject)Level1.Value).ToObject <Dictionary <string, object> >())
                        {
                            dataType = eHelper.GetDataType(Level2);
                            if (dataType == "Object")
                            {
                                foreach (KeyValuePair <string, object> Level3 in ((JObject)Level2.Value).ToObject <Dictionary <string, object> >())
                                {
                                    dataType = eHelper.GetDataType(Level3);
                                    AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>(Level1.Key + "." + Level2.Key + "." + Level3.Key, dataType));
                                    AttribNo++;
                                    AddFormatter(AttribNo - 1, dataType, Level1.Key + "." + Level2.Key + "." + Level3.Key);
                                }
                            }
                            else if (dataType == "Array" && Level1.Key == "network_information")
                            {
                                AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>(Level1.Key + "." + Level2.Key, dataType));
                                AttribNo++;

                                AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>(Level1.Key + "." + "ip_addresses", "String"));
                                AttribNo++;
                                // AttribCollection.Insert(AttribNo, new KeyValuePair<string, string>(Level1.Key + "." + "ip_address_2", "String"));
                                // AttribNo++;
                                // AttribCollection.Insert(AttribNo, new KeyValuePair<string, string>(Level1.Key + "." + "ip_address_3", "String"));
                                // AttribNo++;
                            }
                            else
                            {
                                AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>(Level1.Key + "." + Level2.Key, dataType));
                                AttribNo++;
                                AddFormatter(AttribNo - 1, dataType, Level1.Key + "." + Level2.Key);
                            }
                        }
                    }

                    else if (dataType == "Array" && Level1.Key == "engine_data")
                    {
                        AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>(Level1.Key + "." + "engine", "String"));
                        AttribNo++;
                        AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>(Level1.Key + "." + "asset_name", "String"));
                        AttribNo++;
                        AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>(Level1.Key + "." + "asset_version", "String"));
                        AttribNo++;
                    }
                    else if (Level1.Key == "group_id")
                    {
                        AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>(Level1.Key, dataType));
                        AttribNo++;
                        AddFormatter(AttribNo - 1, dataType, Level1.Key);

                        AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>("group_name", "Reference"));
                        AttribNo++;
                        AddFormatter(AttribNo - 1, "Reference", "group_name");
                    }
                    else
                    {
                        AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>(Level1.Key, dataType));
                        AttribNo++;
                        AddFormatter(AttribNo - 1, dataType, Level1.Key);
                    }
                }
                colCount = AttribCollection.Count;
                #endregion

                #endregion

                #region Create Headings
                // Create headings
                // =================================================================================================================
                Excel.Range titleRow = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A1", eHelper.ExcelColumnLetter(colCount - 1) + "1");
                titleRow.Select();
                titleRow.RowHeight      = 33;
                titleRow.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(r_color, g_color, b_color));

                Excel.Range rowSeparator = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A3", eHelper.ExcelColumnLetter(colCount - 1) + "3");
                rowSeparator.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).Color     = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(r_color, g_color, b_color)); //
                rowSeparator.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = 1;                                                                                              // xlContinuous
                rowSeparator.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).Weight    = 4;                                                                                              // xlThick
                #endregion

                #region Write data
                // Write all the data rows
                // =================================================================================================================
                string[,] dataBlock = new string[rowCount, colCount];
                dynamic temp = "";

                string[] prop;
                string   header0 = "";
                string[] ip_interfaces;
                bool     byPass2 = false;
                bool     byPass3 = false;

                Excel.Worksheet lookupSheet = (Excel.Worksheet)(ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Worksheets.get_Item("Lookup Tables");
                int             rows        = Convert.ToInt32(lookupSheet.Cells[3, 25].Value) + 4;

                formMsg.Message(rowCount.ToString("N0") + " agent data loaded, now processing locally in Excel...", "", allowCancel: false);

                for (int i = 0; i < rowCount; i++)
                {
                    byPass2 = false;
                    byPass3 = false;

                    for (int j = 0; j < AttribCollection.Count; j++)
                    {
                        prop    = AttribCollection[j].Key.Split('.');
                        header0 = prop[0];

                        if (prop.Length == 1)
                        {
                            temp = (threats[i][prop[0]] == null) ? "null" : threats[i][prop[0]].ToString();
                        }
                        else if (prop.Length == 2)
                        {
                            if (prop[1] == "ip_addresses")
                            {
                                JArray ipa       = JArray.Parse(threats[i][prop[0]]["interfaces"].ToString());
                                int    ipa_count = ipa.Count;
                                temp = "";

                                for (int k = 0; k < ipa.Count; k++)
                                {
                                    if (ipa[k]["physical"].ToString() != "00:00:00:00:00:00" && ipa[k]["inet"].ToObject <string[]>().Length > 0)
                                    {
                                        temp = temp + ipa[k]["inet"].ToObject <string[]>()[0] + "; ";
                                    }
                                }

                                temp = temp.ToString().TrimEnd(';', ' ');

                                /*
                                 * if (prop[1] == "ip_address_1" && ipa_count > 0)
                                 * {
                                 *  if (ipa[0]["physical"].ToString() != "00:00:00:00:00:00")
                                 *  {
                                 *      ip_interfaces = ipa[0]["inet"].ToObject<string[]>();
                                 *      temp = ip_interfaces.Length > 0 ? ip_interfaces[0] : "";
                                 *  }
                                 *  else if (ipa_count > 1 && ipa[1]["physical"].ToString() != "00:00:00:00:00:00")
                                 *  {
                                 *      ip_interfaces = ipa[1]["inet"].ToObject<string[]>();
                                 *      temp = ip_interfaces.Length > 0 ? ip_interfaces[0] : "";
                                 *      byPass2 = true;
                                 *  }
                                 *  else if (ipa_count > 2 && ipa[2]["physical"].ToString() != "00:00:00:00:00:00")
                                 *  {
                                 *      ip_interfaces = ipa[2]["inet"].ToObject<string[]>();
                                 *      temp = ip_interfaces.Length > 0 ? ip_interfaces[0] : "";
                                 *      byPass3 = true;
                                 *  }
                                 * }
                                 * else if (prop[1] == "ip_address_2" && ipa_count > 1)
                                 * {
                                 *  if (ipa[1]["physical"].ToString() != "00:00:00:00:00:00" && byPass2 == false)
                                 *  {
                                 *      ip_interfaces = ipa[1]["inet"].ToObject<string[]>();
                                 *      temp = ip_interfaces.Length > 0 ? ip_interfaces[0] : "";
                                 *  }
                                 *  else if (ipa_count > 2 && ipa[2]["physical"].ToString() != "00:00:00:00:00:00" && byPass3 == false)
                                 *  {
                                 *      ip_interfaces = ipa[2]["inet"].ToObject<string[]>();
                                 *      temp = ip_interfaces.Length > 0 ? ip_interfaces[0] : "";
                                 *      byPass3 = true;
                                 *  }
                                 * }
                                 * else if (prop[1] == "ip_address_3" && ipa_count > 2)
                                 * {
                                 *  if (ipa[2]["physical"].ToString() != "00:00:00:00:00:00" && byPass3 == false)
                                 *  {
                                 *      ip_interfaces = ipa[2]["inet"].ToObject<string[]>();
                                 *      temp = ip_interfaces.Length > 0 ? ip_interfaces[0] : "";
                                 *  }
                                 * }
                                 */
                            }
                            else
                            {
                                temp = (threats[i][prop[0]][prop[1]] == null) ? "null" : threats[i][prop[0]][prop[1]].ToString();
                            }
                        }
                        else if (prop.Length == 3)
                        {
                            temp = (threats[i][prop[0]][prop[1]][prop[2]] == null) ? "null" : threats[i][prop[0]][prop[1]][prop[2]].ToString();
                        }
                        else if (prop.Length == 4)
                        {
                            temp = (threats[i][prop[0]][prop[1]][prop[2]][prop[3]] == null) ? "null" : threats[i][prop[0]][prop[1]][prop[2]][prop[3]].ToString();
                        }

                        if (prop.Length == 2 && prop[1] == "os_start_time")
                        {
                            DateTime d2 = DateTime.Parse(temp, null, System.Globalization.DateTimeStyles.RoundtripKind);
                            temp = "=DATE(" + d2.ToString("yyyy,MM,dd") + ")+TIME(" + d2.ToString("HH,mm,ss") + ")";
                        }

                        switch (header0)
                        {
                            #region Lookups
                        case "group_name":
                        {
                            temp = "=IFERROR(VLOOKUP(" + eHelper.ExcelColumnLetter(j - 1) + (i + 5).ToString() + ",'Lookup Tables'!Y4:Z" + rows.ToString() + ",2,FALSE),\"null\")";
                            break;
                        }

                        case "created_date":
                        case "last_active_date":
                        case "meta_data":
                        {
                            if (temp != "null")
                            {
                                DateTime d2 = DateTime.Parse(temp, null, System.Globalization.DateTimeStyles.RoundtripKind);
                                temp = "=DATE(" + d2.ToString("yyyy,MM,dd") + ")+TIME(" + d2.ToString("HH,mm,ss") + ")";
                            }
                            else
                            {
                                temp = "";
                            }
                            break;
                        }
                            #endregion
                        }

                        dataBlock[i, j] = temp;
                    }
                }

                Excel.Range range;
                range = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A5", Missing.Value);

                if (threats.Count > 0)
                {
                    range = range.Resize[rowCount, colCount];
                    range.Cells.ClearFormats();
                    // Writes the array into Excel
                    // This is probably the single thing that sped up the report the most, by writing array
                    range.Value     = dataBlock;
                    range.Font.Size = "10";
                    range.RowHeight = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A2", "A2").Height;
                }
                #endregion

                #region Column Headers
                // Column Headers
                // =================================================================================================================
                eHelper.WriteHeaders("Agent Data", colCount, rowCount, stopWatch);

                // This block writes the column headers
                string hd = "";
                for (int m = 0; m < AttribCollection.Count; m++)
                {
                    TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
                    hd = textInfo.ToTitleCase(AttribCollection[m].Key).Replace('_', ' ');
                    (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Cells[4, m + 1] = hd;
                }
                #endregion

                #region Formatting
                // Create the data filter
                // =================================================================================================================
                Excel.Range range2;
                range2 = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A4", Missing.Value);
                range2 = range2.Resize[rowCount + 1, colCount];
                range2.Select();
                // range2.AutoFilter("1", "<>", Excel.XlAutoFilterOperator.xlOr, "", true);
                range2.AutoFilter(1, Type.Missing, Excel.XlAutoFilterOperator.xlOr, Type.Missing, true);

                // Format number columns
                // =================================================================================================================
                for (int i = 0; i < integerCol.Count; i++)
                {
                    Excel.Range rangeInt;
                    rangeInt = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range(eHelper.ExcelColumnLetter((int)integerCol[i]) + "5", eHelper.ExcelColumnLetter((int)integerCol[i]) + (rowCount + 5).ToString());
                    rangeInt.NumberFormat = "0";
                    rangeInt.Cells.HorizontalAlignment = -4152; // Right align the number
                    rangeInt.Value = rangeInt.Value;            // Strange technique and workaround to get numbers into Excel. Otherwise, Excel sees them as Text
                }

                // Format date time columns
                // =================================================================================================================
                for (int j = 0; j < dateTimeCol.Count; j++)
                {
                    Excel.Range rangeTime;
                    rangeTime = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range(eHelper.ExcelColumnLetter((int)dateTimeCol[j]) + "5", eHelper.ExcelColumnLetter((int)dateTimeCol[j]) + (rowCount + 5).ToString());
                    rangeTime.NumberFormat = "[$-409]yyyy/mm/dd hh:mm AM/PM;@";
                    rangeTime.Cells.HorizontalAlignment = -4152; // Right align the Time
                    rangeTime.Value = rangeTime.Value;           // Strange technique and workaround to get numbers into Excel. Otherwise, Excel sees them as Text
                }

                // Format reference columns
                // =================================================================================================================
                for (int k = 0; k < referenceCol.Count; k++)
                {
                    Excel.Range rangeReference;
                    rangeReference = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range(eHelper.ExcelColumnLetter((int)referenceCol[k]) + "5", eHelper.ExcelColumnLetter((int)referenceCol[k]) + (rowCount + 4).ToString());
                    rangeReference.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(r_color_ref, g_color_ref, b_color_ref));
                    rangeReference.Formula        = rangeReference.Value;

                    rangeReference = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range(eHelper.ExcelColumnLetter((int)referenceCol[k]) + "4", eHelper.ExcelColumnLetter((int)referenceCol[k]) + "4");
                    rangeReference.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(r_color_refh, g_color_refh, b_color_refh));
                    // rangeReference.Value = rangeReference.Value;
                }

                if (referenceCol.Count > 0)
                {
                    Excel.Range rangeReference;
                    rangeReference                = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("E2", "E2");
                    rangeReference.Value          = "Reference lookup data";
                    rangeReference.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(r_color_refh, g_color_refh, b_color_refh));
                }


                // Autofit column width
                // Formats the column width nicely to see the content, but not too wide and limit to maximum of 80
                // =================================================================================================================
                (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Columns.AutoFit();
                for (int i = 0; i < colCount; i++)
                {
                    Excel.Range rangeCol;
                    rangeCol = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range(eHelper.ExcelColumnLetter(i) + "1", eHelper.ExcelColumnLetter(i) + "1");
                    if (Convert.ToInt32(rangeCol.ColumnWidth) > maxColumnWidth)
                    {
                        rangeCol.ColumnWidth = maxColumnWidth;
                    }
                }

                // Place the cursor in cell A2 - which is at the start of the document
                // =================================================================================================================
                (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A2", "A2").Select();
                #endregion

                formMsg.Message("Creating pivot tables and charts for the agent data...", "", allowCancel: false);

                (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ScreenUpdating = false;
                GenerateReport();
                (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ScreenUpdating = true;

                formMsg.Hide();

                // This is saved for viewing in the Show API window
                Globals.ApiResults = JArray.Parse(results.ToString()).ToString();
            }
            catch (Exception ex)
            {
                formMsg.Hide();
                MessageBox.Show(ex.Message, "Error extracting Agent data", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public async Task <IActionResult> Get(string usr)
        {
            List <QuizAmountByTypeStatistics> listRst = new List <QuizAmountByTypeStatistics>();
            String         strErrMsg = "";
            SqlConnection  conn      = null;
            SqlCommand     cmd       = null;
            SqlDataReader  reader    = null;
            HttpStatusCode errorCode = HttpStatusCode.OK;

            // Get user name
            String usrName = String.Empty;

            if (String.IsNullOrEmpty(usr))
            {
                var usro = User.FindFirst(c => c.Type == "sub");
                if (usr != null)
                {
                    usrName = usro.Value;
                }
                else
                {
                    return(BadRequest("User cannot recognize"));
                }
            }
            else
            {
                usrName = usr;
            }

            try
            {
                String queryString = @"SELECT [quiztype]
                                  ,[attenduser]
                                  ,[quizamount]
                              FROM [v_quizamountbytype]
                              WHERE [attenduser] = @user";
                using (conn = new SqlConnection(Startup.DBConnectionString))
                {
                    await conn.OpenAsync();

                    cmd = new SqlCommand(queryString, conn);
                    cmd.Parameters.AddWithValue("@user", usrName);
                    reader = cmd.ExecuteReader();

                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            QuizAmountByTypeStatistics qz = new QuizAmountByTypeStatistics
                            {
                                QuizType   = (QuizTypeEnum)reader.GetInt16(0),
                                AttendUser = reader.GetString(1),
                                Amount     = reader.GetInt32(2)
                            };
                            listRst.Add(qz);
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine(exp.Message);
                strErrMsg = exp.Message;
                if (errorCode == HttpStatusCode.OK)
                {
                    errorCode = HttpStatusCode.InternalServerError;
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                    reader = null;
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                    cmd = null;
                }
                if (conn != null)
                {
                    conn.Dispose();
                    conn = null;
                }
            }

            if (errorCode != HttpStatusCode.OK)
            {
                switch (errorCode)
                {
                case HttpStatusCode.Unauthorized:
                    return(Unauthorized());

                case HttpStatusCode.NotFound:
                    return(NotFound());

                case HttpStatusCode.BadRequest:
                    return(BadRequest());

                default:
                    return(StatusCode(500, strErrMsg));
                }
            }

            var setting = new Newtonsoft.Json.JsonSerializerSettings
            {
                DateFormatString = "yyyy-MM-dd",
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };

            return(new JsonResult(listRst, setting));
        }
Ejemplo n.º 30
0
 partial void UpdateJsonSerializerSettings(Newtonsoft.Json.JsonSerializerSettings settings)
 {
     settings.Converters.Add(new ClientModelCreationConverter(this));
 }
Ejemplo n.º 31
0
        public ActionResult Edit([Bind(Include = "Id,ConcurrencyKey,T_MealTime")] T_ShiftMealTime t_shiftmealtime, string UrlReferrer)
        {
            string command = Request.Form["hdncommand"];

            CheckBeforeSave(t_shiftmealtime, command);
            if (ModelState.IsValid)
            {
                bool customsave_hasissues = false;
                if (!CustomSaveOnEdit(t_shiftmealtime, out customsave_hasissues, command))
                {
                    db.Entry(t_shiftmealtime).State = EntityState.Modified;
                    db.SaveChanges();
                }
                if (!customsave_hasissues)
                {
                    RedirectToRouteResult customRedirectAction = CustomRedirectUrl(t_shiftmealtime, "Edit", command);
                    if (customRedirectAction != null)
                    {
                        return(customRedirectAction);
                    }
                    if (command != "Save")
                    {
                        if (command == "SaveNextPrev")
                        {
                            long NextPreId = Convert.ToInt64(Request.Form["hdnNextPrevId"]);
                            return(RedirectToAction("Edit", new { Id = NextPreId, UrlReferrer = UrlReferrer }));
                        }
                        else
                        {
                            return(RedirectToAction("Edit", new { Id = t_shiftmealtime.Id, UrlReferrer = UrlReferrer }));
                        }
                    }
                    if (!string.IsNullOrEmpty(UrlReferrer))
                    {
                        var uri   = new Uri(UrlReferrer);
                        var query = HttpUtility.ParseQueryString(uri.Query);
                        if (Convert.ToBoolean(query.Get("IsFilter")) == true)
                        {
                            return(RedirectToAction("Index"));
                        }
                        else
                        {
                            return(Redirect(UrlReferrer));
                        }
                    }
                    else
                    {
                        return(RedirectToAction("Index"));
                    }
                }
            }

            // NEXT-PREVIOUS DROP DOWN CODE
            TempData.Keep();
            string json = "";

            if (TempData["T_ShiftMealTimelist"] == null)
            {
                json = Newtonsoft.Json.JsonConvert.SerializeObject(db.T_ShiftMealTimes.Select(z => new { ID = z.Id, DisplayValue = z.DisplayValue }).ToList());
            }
            else
            {
                ViewBag.EntityT_ShiftMealTimeDisplayValueEdit = TempData["T_ShiftMealTimelist"];
                json = Newtonsoft.Json.JsonConvert.SerializeObject(TempData["T_ShiftMealTimelist"]);
            }

            Newtonsoft.Json.JsonSerializerSettings serSettings = new    Newtonsoft.Json.JsonSerializerSettings();
            serSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
            var lst = Newtonsoft.Json.JsonConvert.DeserializeObject <IEnumerable <object> >(json, serSettings);

            ViewBag.EntityT_ShiftMealTimeDisplayValueEdit = new SelectList(lst, "ID", "DisplayValue");
            //
            LoadViewDataAfterOnEdit(t_shiftmealtime);
            ViewData["T_ShiftMealTimeParentUrl"]      = UrlReferrer;
            ViewBag.T_ShiftMealTimeIsHiddenRule       = checkHidden("T_ShiftMealTime", "OnEdit", false);
            ViewBag.T_ShiftMealTimeIsGroupsHiddenRule = checkHidden("T_ShiftMealTime", "OnEdit", true);
            ViewBag.T_ShiftMealTimeIsSetValueUIRule   = checkSetValueUIRule("T_ShiftMealTime", "OnEdit");
            return(View(t_shiftmealtime));
        }
Ejemplo n.º 32
0
        public async Task <IActionResult> Get()
        {
            List <LanguageViewModel> listVMs = new List <LanguageViewModel>();
            SqlConnection            conn    = new SqlConnection(Startup.DBConnectionString);
            String  queryString = "";
            Boolean bError      = false;
            String  strErrMsg   = "";

            try
            {
                queryString = @"SELECT [LCID]
                              ,[ISONAME]
                              ,[ENNAME]
                              ,[NAVNAME]
                              ,[APPFLAG]
                          FROM [dbo].[t_language]";

                await conn.OpenAsync();

                SqlCommand    cmd    = new SqlCommand(queryString, conn);
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        LanguageViewModel avm = new LanguageViewModel
                        {
                            Lcid        = reader.GetInt32(0),
                            ISOName     = reader.GetString(1),
                            EnglishName = reader.GetString(2),
                            NativeName  = reader.GetString(3)
                        };
                        if (!reader.IsDBNull(4))
                        {
                            avm.AppFlag = reader.GetBoolean(4);
                        }

                        listVMs.Add(avm);
                    }
                }
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine(exp.Message);
                bError    = true;
                strErrMsg = exp.Message;
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }

            if (bError)
            {
                return(StatusCode(500, strErrMsg));
            }

            var setting = new Newtonsoft.Json.JsonSerializerSettings
            {
                DateFormatString = HIHAPIConstants.DateFormatPattern,
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };

            return(new JsonResult(listVMs, setting));
        }
Ejemplo n.º 33
0
 public string ToJson(Newtonsoft.Json.JsonSerializerSettings jsonSerializerSettings)
 {
     return(Newtonsoft.Json.JsonConvert.SerializeObject(this, jsonSerializerSettings));
 }
Ejemplo n.º 34
0
        public static void Main(string[] args)
        {
            Newtonsoft.Json.JsonConvert.DefaultSettings = (() =>
            {
                var settings = new Newtonsoft.Json.JsonSerializerSettings();
                settings.Formatting = Newtonsoft.Json.Formatting.Indented;
                settings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter {
                    CamelCaseText = true
                });
                return(settings);
            });

            var binding = new BasicHttpBinding();
            // todo: why DataContractSerializer not working?
            var endpoint       = new EndpointAddress(new Uri(string.Format("http://{0}:5050/Service.svc", Environment.MachineName)));
            var channelFactory = new ChannelFactory <ISampleService>(binding, endpoint);
            var serviceClient  = channelFactory.CreateChannel();
            var result         = serviceClient.Ping("hey");

            Console.WriteLine("Ping method result: {0}", result);

            var complexModel = new ComplexModelInput
            {
                StringProperty = Guid.NewGuid().ToString(),
                IntProperty    = int.MaxValue / 2,
                ListProperty   = new List <string> {
                    "test", "list", "of", "strings"
                },
                //DateTimeOffsetProperty = new DateTimeOffset(2018, 12, 31, 13, 59, 59, TimeSpan.FromHours(1))
            };

            var pingComplexModelResult = serviceClient.PingComplexModel(complexModel);

            Console.WriteLine($"{nameof(pingComplexModelResult)}:\n{Newtonsoft.Json.JsonConvert.SerializeObject(pingComplexModelResult)}\n");

            serviceClient.EnumMethod(out var enumValue);
            Console.WriteLine("Enum method result: {0}", enumValue);

            var responseModelRef1 = ComplexModelResponse.CreateSample1();
            var responseModelRef2 = ComplexModelResponse.CreateSample2();
            var pingComplexModelOutAndRefResult =
                serviceClient.PingComplexModelOutAndRef(
                    ComplexModelInput.CreateSample1(),
                    ref responseModelRef1,
                    ComplexObject.CreateSample1(),
                    ref responseModelRef2,
                    ComplexObject.CreateSample2(),
                    out var responseModelOut1,
                    out var responseModelOut2);

            Console.WriteLine($"{nameof(pingComplexModelOutAndRefResult)}: {pingComplexModelOutAndRefResult}\n");
            Console.WriteLine($"{nameof(responseModelRef1)}:\n{Newtonsoft.Json.JsonConvert.SerializeObject(responseModelRef1)}\n");
            Console.WriteLine($"{nameof(responseModelRef2)}:\n{Newtonsoft.Json.JsonConvert.SerializeObject(responseModelRef2)}\n");
            Console.WriteLine($"{nameof(responseModelOut1)}:\n{Newtonsoft.Json.JsonConvert.SerializeObject(responseModelOut1)}\n");
            Console.WriteLine($"{nameof(responseModelOut2)}:\n{Newtonsoft.Json.JsonConvert.SerializeObject(responseModelOut2)}\n");

            serviceClient.VoidMethod(out var stringValue);
            Console.WriteLine("Void method result: {0}", stringValue);

            var asyncMethodResult = serviceClient.AsyncMethod().Result;

            Console.WriteLine("Async method result: {0}", asyncMethodResult);

            Console.ReadKey();
        }
Ejemplo n.º 35
0
        public void SqlRepositoryImplementation_ReadSQLSchema_Test()
        {
            var testCfg = OfaSchlupfer.TestCfg.Get();
            var repSQLConnectionString = testCfg.SQLConnectionString;


            IServiceCollection services = new ServiceCollection();

            services.AddLogging((builder) => { builder.AddDebug(); });
            var serviceProvider = services.BuildServiceProvider();

            var modelRoot       = new ModelRoot();
            var modelRepository = new ModelRepository();

            modelRepository.Name = "ProjectServerSQL";
            modelRoot.Repositories.Add(modelRepository);

            SqlRepositoryModel sqlRepository = new SqlRepositoryImplementation();

            sqlRepository.ConnectionString            = repSQLConnectionString;
            modelRepository.ReferencedRepositoryModel = sqlRepository;

            var errors = new ModelErrors();
            MetaModelBuilder metaModelBuilder = new MetaModelBuilder();

            sqlRepository.ReadSQLSchema(metaModelBuilder, errors);

            if (errors.HasErrors())
            {
                output.WriteLine(errors.ToString());
            }
            Assert.False(errors.HasErrors());

            Assert.NotNull(sqlRepository.ModelSchema);
            Assert.True(sqlRepository.ModelSchema.ComplexTypes.Count > 0);

            var entitySchema = sqlRepository.ModelSchema.GetEntitySchema();

            Assert.NotNull(entitySchema);

            {
                var serializeSettings = new Newtonsoft.Json.JsonSerializerSettings();
                serializeSettings.TypeNameAssemblyFormatHandling = Newtonsoft.Json.TypeNameAssemblyFormatHandling.Simple;
                serializeSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto;
                var schemaAsJson = Newtonsoft.Json.JsonConvert.SerializeObject(sqlRepository.ModelSchema, Newtonsoft.Json.Formatting.Indented, serializeSettings);
                try {
                    string outputPath = System.IO.Path.Combine(testCfg.SolutionFolder, @"test\temp\SqlRepositoryImplementation_ReadSQLSchema_Test_ModelSchema.json");
                    System.IO.File.WriteAllText(outputPath, schemaAsJson);
                } catch {
                    throw;
                }
            }

            {
                var serializeSettings = new Newtonsoft.Json.JsonSerializerSettings();
                serializeSettings.TypeNameAssemblyFormatHandling = Newtonsoft.Json.TypeNameAssemblyFormatHandling.Simple;
                serializeSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto;
                var schemaAsJson = Newtonsoft.Json.JsonConvert.SerializeObject(entitySchema, Newtonsoft.Json.Formatting.Indented, serializeSettings);
                try {
                    string outputPath = System.IO.Path.Combine(testCfg.SolutionFolder, @"test\temp\SqlRepositoryImplementation_ReadSQLSchema_Test_EntitySchema.json");
                    System.IO.File.WriteAllText(outputPath, schemaAsJson);
                } catch {
                    throw;
                }
            }
        }
Ejemplo n.º 36
0
        public static string GetDatabasePath(string backend, Options options, bool autoCreate = true, bool anyUsername = false)
        {
            if (options == null)
            {
                options = new Options(new Dictionary <string, string>());
            }

            if (!string.IsNullOrEmpty(options.Dbpath))
            {
                return(options.Dbpath);
            }

            //Normal mode uses the systems "(Local) Application Data" folder
            // %LOCALAPPDATA% on Windows, ~/.config on Linux

            // Special handling for Windows:
            //   - Older versions use %APPDATA%
            //   - but new versions use %LOCALAPPDATA%
            //
            //  If we find a new version, lets use that
            //    otherwise use the older location
            //

            var folder = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Duplicati");

            if (Platform.IsClientWindows)
            {
                var newlocation = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Duplicati");

                var prevfile = System.IO.Path.Combine(folder, "dbconfig.json");
                var curfile  = System.IO.Path.Combine(newlocation, "dbconfig.json");

                // If the new file exists, we use that
                // If the new file does not exist, and the old file exists we use the old
                // Otherwise we use the new location
                if (System.IO.File.Exists(curfile) || !System.IO.File.Exists(prevfile))
                {
                    folder = newlocation;
                }
            }

            if (!System.IO.Directory.Exists(folder))
            {
                System.IO.Directory.CreateDirectory(folder);
            }

            var file = System.IO.Path.Combine(folder, "dbconfig.json");
            List <BackendEntry> configs;

            if (!System.IO.File.Exists(file))
            {
                configs = new List <BackendEntry>();
            }
            else
            {
                configs = Newtonsoft.Json.JsonConvert.DeserializeObject <List <BackendEntry> >(System.IO.File.ReadAllText(file, System.Text.Encoding.UTF8));
            }

            var    uri      = new Library.Utility.Uri(backend);
            string server   = uri.Host;
            string path     = uri.Path;
            string type     = uri.Scheme;
            int    port     = uri.Port;
            string username = uri.Username;
            string prefix   = options.Prefix;

            if (username == null || uri.Password == null)
            {
                var sopts = DynamicLoader.BackendLoader.GetSupportedCommands(backend);
                var ropts = new Dictionary <string, string>(options.RawOptions);
                foreach (var k in uri.QueryParameters.AllKeys)
                {
                    ropts[k] = uri.QueryParameters[k];
                }

                if (sopts != null)
                {
                    foreach (var o in sopts)
                    {
                        if (username == null && o.Aliases != null && o.Aliases.Contains("auth-username", StringComparer.OrdinalIgnoreCase) && ropts.ContainsKey(o.Name))
                        {
                            username = ropts[o.Name];
                        }
                    }

                    foreach (var o in sopts)
                    {
                        if (username == null && o.Name.Equals("auth-username", StringComparison.OrdinalIgnoreCase) && ropts.ContainsKey("auth-username"))
                        {
                            username = ropts["auth-username"];
                        }
                    }
                }
            }

            //Now find the one that matches :)
            var matches = (from n in configs
                           where
                           n.Type == type &&
                           //n.Passwordhash == password &&
                           n.Username == username &&
                           n.Port == port &&
                           n.Server == server &&
                           n.Path == path &&
                           n.Prefix == prefix
                           select n).ToList();

            if (matches.Count > 1)
            {
                throw new Duplicati.Library.Interface.UserInformationException(string.Format("Multiple sources found for: {0}", backend), "MultipleLocalDatabaseSourcesFound");
            }

            // Re-select
            if (matches.Count == 0 && anyUsername && string.IsNullOrEmpty(username))
            {
                matches = (from n in configs
                           where
                           n.Type == type &&
                           n.Port == port &&
                           n.Server == server &&
                           n.Path == path &&
                           n.Prefix == prefix
                           select n).ToList();

                if (matches.Count > 1)
                {
                    throw new Duplicati.Library.Interface.UserInformationException(String.Format("Multiple sources found for \"{0}\", try supplying --{1}", backend, "auth-username"), "MultipleLocalDatabaseSourcesFound");
                }
            }

            if (matches.Count == 0 && !autoCreate)
            {
                return(null);
            }

            if (matches.Count == 0)
            {
                var backupname = options.BackupName;
                if (string.IsNullOrEmpty(backupname) || backupname == Options.DefaultBackupName)
                {
                    backupname = GenerateRandomName();
                }
                else
                {
                    foreach (var c in System.IO.Path.GetInvalidFileNameChars())
                    {
                        backupname = backupname.Replace(c.ToString(), "");
                    }
                }

                var newpath   = System.IO.Path.Combine(folder, backupname + ".sqlite");
                int max_tries = 100;
                while (System.IO.File.Exists(newpath) && max_tries-- > 0)
                {
                    newpath = System.IO.Path.Combine(folder, GenerateRandomName());
                }

                if (System.IO.File.Exists(newpath))
                {
                    throw new Duplicati.Library.Interface.UserInformationException("Unable to find a unique name for the database, please use --dbpath", "CannotCreateRandomName");
                }

                //Create a new one, add it to the list, and save it
                configs.Add(new BackendEntry()
                {
                    Type     = type,
                    Server   = server,
                    Path     = path,
                    Prefix   = prefix,
                    Username = username,
                    //Passwordhash = password,
                    Port          = port,
                    Databasepath  = newpath,
                    ParameterFile = null
                });

                var settings = new Newtonsoft.Json.JsonSerializerSettings();
                settings.Formatting = Newtonsoft.Json.Formatting.Indented;
                System.IO.File.WriteAllText(file, Newtonsoft.Json.JsonConvert.SerializeObject(configs, settings), System.Text.Encoding.UTF8);

                return(newpath);
            }
            else
            {
                return(matches[0].Databasepath);
            }
        }
Ejemplo n.º 37
0
        public async System.Threading.Tasks.Task <mmria.common.model.couchdb.document_put_response> Post()
        {
            //bool valid_login = false;
            mmria.common.metadata.app metadata = null;
            string object_string = null;

            mmria.common.model.couchdb.document_put_response result = new mmria.common.model.couchdb.document_put_response();

            try
            {
                System.IO.Stream dataStream0 = await this.Request.Content.ReadAsStreamAsync();

                // Open the stream using a StreamReader for easy access.
                //dataStream0.Seek(0, System.IO.SeekOrigin.Begin);
                System.IO.StreamReader reader0 = new System.IO.StreamReader(dataStream0);
                // Read the content.
                string temp = reader0.ReadToEnd();

                metadata = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.metadata.app>(temp);
                //System.Dynamic.ExpandoObject json_result = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Dynamic.ExpandoObject>(result, new  Newtonsoft.Json.Converters.ExpandoObjectConverter());



                //string metadata = DecodeUrlString(temp);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            try
            {
                Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                object_string = Newtonsoft.Json.JsonConvert.SerializeObject(metadata, settings);

                string metadata_url = this.get_couch_db_url() + "/metadata/" + metadata._id;

                System.Net.WebRequest request = System.Net.WebRequest.Create(new System.Uri(metadata_url));
                request.Method          = "PUT";
                request.ContentType     = "application/json";
                request.ContentLength   = object_string.Length;
                request.PreAuthenticate = false;

                if (this.Request.Headers.Contains("Cookie") && this.Request.Headers.GetValues("Cookie").Count() > 0)
                {
                    string[] cookie_set = this.Request.Headers.GetValues("Cookie").First().Split(';');
                    for (int i = 0; i < cookie_set.Length; i++)
                    {
                        string[] auth_session_token = cookie_set[i].Split('=');
                        if (auth_session_token[0].Trim() == "AuthSession")
                        {
                            request.Headers.Add("Cookie", "AuthSession=" + auth_session_token[1]);
                            request.Headers.Add("X-CouchDB-WWW-Authenticate", auth_session_token[1]);
                            break;
                        }
                    }
                }

                using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))
                {
                    try
                    {
                        streamWriter.Write(object_string);
                        streamWriter.Flush();
                        streamWriter.Close();


                        System.Net.WebResponse response = await request.GetResponseAsync();

                        System.IO.Stream       dataStream = response.GetResponseStream();
                        System.IO.StreamReader reader     = new System.IO.StreamReader(dataStream);
                        string responseFromServer         = reader.ReadToEnd();

                        result = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.document_put_response>(responseFromServer);

                        if (response.Headers["Set-Cookie"] != null)
                        {
                            string[] set_cookie = response.Headers["Set-Cookie"].Split(';');
                            string[] auth_array = set_cookie[0].Split('=');
                            if (auth_array.Length > 1)
                            {
                                string auth_session_token = auth_array[1];
                                result.auth_session = auth_session_token;
                            }
                            else
                            {
                                result.auth_session = "";
                            }
                        }



                        //System.Threading.Tasks.Task.Run( new Action(()=> { var f = new GenerateSwaggerFile(); System.IO.File.WriteAllText(Program.config_file_root_folder + "/api-docs/api.json", f.generate(metadata)); }));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }

                if (!result.ok)
                {
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            return(result);
        }
        public async Task <IActionResult> Get([FromQuery] Int32 hid)
        {
            if (hid <= 0)
            {
                return(BadRequest("No HID inputted"));
            }

            String usrName = String.Empty;

            if (Startup.UnitTestMode)
            {
                usrName = UnitTestUtility.UnitTestUser;
            }
            else
            {
                var usrObj = HIHAPIUtility.GetUserClaim(this);
                usrName = usrObj.Value;
            }
            if (String.IsNullOrEmpty(usrName))
            {
                return(BadRequest("User cannot recognize"));
            }

            List <FinanceReportBSViewModel> listVm = null;
            SqlConnection  conn        = null;
            SqlCommand     cmd         = null;
            SqlDataReader  reader      = null;
            String         queryString = "";
            String         strErrMsg   = "";
            HttpStatusCode errorCode   = HttpStatusCode.OK;

            try
            {
                var cacheKey = String.Format(CacheKeys.FinReportBS, hid);

                if (_cache.TryGetValue <List <FinanceReportBSViewModel> >(cacheKey, out listVm))
                {
                    // Do nothing
                }
                else
                {
                    listVm = new List <FinanceReportBSViewModel>();

                    queryString = @"SELECT [accountid]
                          ,[ACCOUNTNAME]
                          ,[ACCOUNTCTGYID]
                          ,[ACCOUNTCTGYNAME]
                          ,[debit_balance]
                          ,[credit_balance]
                          ,[balance]
                      FROM [dbo].[v_fin_report_bs] WHERE [HID] = " + hid.ToString();

                    using (conn = new SqlConnection(Startup.DBConnectionString))
                    {
                        await conn.OpenAsync();

                        // Check Home assignment with current user
                        try
                        {
                            HIHAPIUtility.CheckHIDAssignment(conn, hid, usrName);
                        }
                        catch (Exception)
                        {
                            errorCode = HttpStatusCode.BadRequest;
                            throw;
                        }

                        cmd    = new SqlCommand(queryString, conn);
                        reader = cmd.ExecuteReader();
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                FinanceReportBSViewModel avm = new FinanceReportBSViewModel
                                {
                                    AccountID           = reader.GetInt32(0),
                                    AccountName         = reader.GetString(1),
                                    AccountCategoryID   = reader.GetInt32(2),
                                    AccountCategoryName = reader.GetString(3)
                                };
                                if (reader.IsDBNull(4))
                                {
                                    avm.DebitBalance = 0;
                                }
                                else
                                {
                                    avm.DebitBalance = Math.Round(reader.GetDecimal(4), 2);
                                }
                                if (reader.IsDBNull(5))
                                {
                                    avm.CreditBalance = 0;
                                }
                                else
                                {
                                    avm.CreditBalance = Math.Round(reader.GetDecimal(5), 2);
                                }
                                if (reader.IsDBNull(6))
                                {
                                    avm.Balance = 0;
                                }
                                else
                                {
                                    avm.Balance = Math.Round(reader.GetDecimal(6), 2);
                                }
                                listVm.Add(avm);
                            }
                        }
                    }

                    this._cache.Set <List <FinanceReportBSViewModel> >(cacheKey, listVm, TimeSpan.FromSeconds(600));
                }
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine(exp.Message);
                strErrMsg = exp.Message;
                if (errorCode == HttpStatusCode.OK)
                {
                    errorCode = HttpStatusCode.InternalServerError;
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                    reader = null;
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                    cmd = null;
                }
                if (conn != null)
                {
                    conn.Dispose();
                    conn = null;
                }
            }

            if (errorCode != HttpStatusCode.OK)
            {
                switch (errorCode)
                {
                case HttpStatusCode.Unauthorized:
                    return(Unauthorized());

                case HttpStatusCode.NotFound:
                    return(NotFound());

                case HttpStatusCode.BadRequest:
                    return(BadRequest(strErrMsg));

                default:
                    return(StatusCode(500, strErrMsg));
                }
            }

            var setting = new Newtonsoft.Json.JsonSerializerSettings
            {
                DateFormatString = HIHAPIConstants.DateFormatPattern,
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };

            return(new JsonResult(listVm, setting));
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            List<Newtonsoft.Json.JsonConverter> myconverters = new List<Newtonsoft.Json.JsonConverter>();
            myconverters.Add(new CustomConvertersColorToRGB());
            myconverters.Add(new CustomConvertersAxis());
            myconverters.Add(new CustomConvertersLegend());
            myconverters.Add(new CustomConverterEnum());

            Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings()
            {
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                Converters = myconverters
            };

            TrendLine[] lines = value as TrendLine[];

            if (lines.Count() == 0) return;

            writer.WriteStartObject();

            for (int i = 0; i < lines.Count(); i++ )
            {
                writer.WritePropertyName(i.ToString());
                string json = Newtonsoft.Json.JsonConvert.SerializeObject(lines[i], Formatting.None, settings);
                json = BaseGVI.FixJSON(json);
                json = json.Trim('"');
                writer.WriteRawValue( json );
            }

            writer.WriteEndObject();
        }
        public void GetData()
        {
            try
            {
                #region Create worksheet
                // Creates a worksheet for "Applications" if one does not already exist
                // =================================================================================================================
                Excel.Worksheet threatsWorksheet;
                try
                {
                    threatsWorksheet = (Excel.Worksheet)(ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Worksheets.get_Item("Process Data");
                    threatsWorksheet.Activate();
                }
                catch
                {
                    threatsWorksheet      = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ActiveWorkbook.Worksheets.Add() as Excel.Worksheet;
                    threatsWorksheet.Name = "Process Data";
                    threatsWorksheet.Activate();
                }
                #endregion

                #region Clear worksheet
                // Clear spreadsheet
                eHelper.Clear();
                #endregion

                #region Get Data

                #region Find All the Agents from the hidden Lookup Table sheet
                Excel.Worksheet lookupSheet = (Excel.Worksheet)(ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Worksheets.get_Item("Lookup Tables");
                int             rows        = Convert.ToInt32(lookupSheet.Cells[3, 6].Value) + 4;
                Excel.Range     AgentIDs    = lookupSheet.Range["F5:H" + rows.ToString()];
                AgentArray      = AgentIDs.Value;
                AgentArrayItems = AgentArray.GetLength(0);
                #endregion

                #region Get data from server (Looping Call)

                // Extract data from SentinelOne Management Server (Looping Calls)
                // =================================================================================================================
                mgmtServer = crypto.GetSettings("ExcelPlugIn", "ManagementServer");
                string token = crypto.Decrypt(crypto.GetSettings("ExcelPlugIn", "Token"));
                userName = crypto.GetSettings("ExcelPlugIn", "Username");

                StringBuilder results         = new StringBuilder("[");
                int           maxColumnWidth  = 80;
                dynamic       threats         = "";
                int           rowCountTemp    = 0;
                int           percentComplete = 0;
                Stopwatch     stopWatch       = new Stopwatch();
                stopWatch.Start();

                var JsonSettings = new Newtonsoft.Json.JsonSerializerSettings
                {
                    NullValueHandling     = Newtonsoft.Json.NullValueHandling.Include,
                    MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore
                };

                string resourceString = "";
                var    restClient     = new RestClientInterface();

                if (AgentArrayItems > maxIterations)
                {
                    AgentArrayItems = maxIterations;
                }

                formMsg.StopProcessing = false;
                formMsg.Message("Loading process data: " + rowCount.ToString("N0"),
                                eHelper.ToReadableStringUpToSec(stopWatch.Elapsed) + " elapsed", allowCancel: true);

                for (int i = 1; i <= AgentArrayItems; i++)
                {
                    resourceString = mgmtServer + "/web/api/v1.6/agents/" + AgentArray.GetValue(i, 1).ToString() + "/processes";

                    Globals.ApiUrl      = resourceString;
                    restClient.EndPoint = resourceString;
                    restClient.Method   = HttpVerb.GET;

                    var batch_string = "";
                    try
                    {
                        batch_string = restClient.MakeRequest(token).ToString();
                    }
                    catch { };

                    if (batch_string.Length < 4)
                    {
                        continue;
                    }

                    if (i % UpdateInterval == 0)
                    {
                        percentComplete = (int)Math.Round((double)(100 * i) / AgentArrayItems);
                        formMsg.Message("Collecting processes from " + i.ToString("N0") + " of " + AgentArrayItems.ToString("N0") + " agents (" + percentComplete.ToString() + "%)...",
                                        rowCount.ToString("N0") + " processes found, " + eHelper.ToReadableStringUpToSec(stopWatch.Elapsed) + " elapsed", allowCancel: true);
                        if (formMsg.StopProcessing == true)
                        {
                            formMsg.Hide();
                            return;
                        }
                    }

                    JArray batchArray = JArray.Parse(batch_string);
                    string procName   = "";

                    List <string> excludeProcesses = new List <string>();
                    excludeProcesses.Add("conhost.exe");
                    excludeProcesses.Add("csrss.exe");
                    excludeProcesses.Add("dllhost.exe");
                    excludeProcesses.Add("dwm.exe");
                    excludeProcesses.Add("explorer.exe");
                    excludeProcesses.Add("logonui.exe");
                    excludeProcesses.Add("lsass.exe");
                    excludeProcesses.Add("msdtc.exe");
                    excludeProcesses.Add("rundll32.exe");
                    excludeProcesses.Add("runtimebroker.exe");
                    excludeProcesses.Add("searchindexer.exe");
                    excludeProcesses.Add("searchprotocolhost.exe");
                    excludeProcesses.Add("sentinelagent.exe");
                    excludeProcesses.Add("sentinelagent.exe");
                    excludeProcesses.Add("sentinelagent.exe");
                    excludeProcesses.Add("sentinelservicehost.exe");
                    excludeProcesses.Add("sentinelstaticengine.exe");
                    excludeProcesses.Add("sentinelstaticenginescanner.exe");
                    excludeProcesses.Add("services.exe");
                    excludeProcesses.Add("smss.exe");
                    excludeProcesses.Add("smsvchost.exe");
                    excludeProcesses.Add("spoolsv.exe");
                    excludeProcesses.Add("svchost.exe");
                    excludeProcesses.Add("taskhost.exe");
                    excludeProcesses.Add("taskhostw.exe");
                    excludeProcesses.Add("wininit.exe");
                    excludeProcesses.Add("winlogon.exe");
                    excludeProcesses.Add("wmiprvse.exe");
                    excludeProcesses.Add("wudfhost.exe");

                    for (int j = batchArray.Count; j-- > 0;)
                    {
                        procName = ((JObject)batchArray[j])["process_name"].ToString();

                        if (excludeProcesses.Contains(procName.ToLower()))
                        {
                            batchArray[j].Remove();
                        }
                        else
                        {
                            var PropertyComputerName    = new JProperty("computer_name", AgentArray.GetValue(i, 2) == null ? "N/A" : AgentArray.GetValue(i, 2).ToString());
                            var PropertyOperatingSystem = new JProperty("operating_system", AgentArray.GetValue(i, 3) == null ? "N/A" : AgentArray.GetValue(i, 3).ToString());

                            ((JObject)batchArray[j]).AddFirst(PropertyOperatingSystem);
                            ((JObject)batchArray[j]).AddFirst(PropertyComputerName);
                        }
                    }

                    batch_string = batchArray.ToString();

                    threats      = Newtonsoft.Json.JsonConvert.DeserializeObject(batch_string, JsonSettings);
                    rowCountTemp = (int)threats.Count;
                    results.Append(batchArray.ToString().TrimStart('[').TrimEnd(']', '\r', '\n')).Append(",");
                    rowCount = rowCount + rowCountTemp;
                }
                stopWatch.Stop();
                formMsg.Hide();

                // results.ToString().TrimEnd(',', ' ');
                results.Length--;
                results.Append("]");

                threats = Newtonsoft.Json.JsonConvert.DeserializeObject(results.ToString(), JsonSettings);

                #endregion

                #region Parse attribute headers
                JArray ja = JArray.Parse(results.ToString());

                // Stop processing if no data found
                if (ja.Count == 0)
                {
                    (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Cells[1, 1] = "No process data found";
                    (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A2", "A2").Select();
                    (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Columns.AutoFit();
                    formMsg.Hide();
                    return;
                }

                Dictionary <string, object>           dictObj          = ja[0].ToObject <Dictionary <string, object> >();
                List <KeyValuePair <string, string> > AttribCollection = new List <KeyValuePair <string, string> >();
                int AttribNo = 0;

                for (int index = 0; index < dictObj.Count; index++)
                {
                    var    Level1   = dictObj.ElementAt(index);
                    string dataType = "String";
                    dataType = eHelper.GetDataType(Level1);

                    if (dataType == "Object")
                    {
                        foreach (KeyValuePair <string, object> Level2 in ((JObject)Level1.Value).ToObject <Dictionary <string, object> >())
                        {
                            dataType = eHelper.GetDataType(Level2);
                            if (dataType == "Object")
                            {
                                foreach (KeyValuePair <string, object> Level3 in ((JObject)Level2.Value).ToObject <Dictionary <string, object> >())
                                {
                                    dataType = eHelper.GetDataType(Level3);
                                    AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>(Level1.Key + "." + Level2.Key + "." + Level3.Key, dataType));
                                    AttribNo++;
                                    AddFormatter(AttribNo - 1, dataType, Level1.Key + "." + Level2.Key + "." + Level3.Key);
                                }
                            }
                            else
                            {
                                AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>(Level1.Key + "." + Level2.Key, dataType));
                                AttribNo++;
                                AddFormatter(AttribNo - 1, dataType, Level1.Key + "." + Level2.Key);
                            }
                        }
                    }
                    else if (Level1.Key == "computer_name")
                    {
                        AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>("computer_name", "Reference"));
                        AttribNo++;
                        AddFormatter(AttribNo - 1, "Reference", "computer_name");
                    }
                    else if (Level1.Key == "operating_system")
                    {
                        AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>("operating_system", "Reference"));
                        AttribNo++;
                        AddFormatter(AttribNo - 1, "Reference", "operating_system");
                    }
                    else
                    {
                        AttribCollection.Insert(AttribNo, new KeyValuePair <string, string>(Level1.Key, dataType));
                        AttribNo++;
                        AddFormatter(AttribNo - 1, dataType, Level1.Key);
                    }
                }
                colCount = AttribCollection.Count;
                #endregion

                #endregion

                #region Create Headings
                // Create headings
                // =================================================================================================================
                Excel.Range titleRow = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A1", eHelper.ExcelColumnLetter(colCount - 1) + "1");
                titleRow.Select();
                titleRow.RowHeight      = 33;
                titleRow.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(r_color, g_color, b_color));

                Excel.Range rowSeparator = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A3", eHelper.ExcelColumnLetter(colCount - 1) + "3");
                rowSeparator.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).Color     = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(r_color, g_color, b_color)); //
                rowSeparator.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = 1;                                                                                              // xlContinuous
                rowSeparator.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).Weight    = 4;                                                                                              // xlThick
                #endregion

                #region Write data
                // Write all the data rows
                // =================================================================================================================
                string[,] dataBlock = new string[rowCount, colCount];
                dynamic temp = "";

                for (int i = 0; i < rowCount; i++)
                {
                    for (int j = 0; j < AttribCollection.Count; j++)
                    {
                        try
                        {
                            string[] prop = AttribCollection[j].Key.Split('.');

                            if (prop.Length == 1)
                            {
                                temp = (threats[i][prop[0]] == null) ? "null" : threats[i][prop[0]].ToString();
                            }
                            else if (prop.Length == 2)
                            {
                                temp = (threats[i][prop[0]][prop[1]] == null) ? "null" : threats[i][prop[0]][prop[1]].ToString();
                            }
                            else if (prop.Length == 3)
                            {
                                temp = (threats[i][prop[0]][prop[1]][prop[2]] == null) ? "null" : threats[i][prop[0]][prop[1]][prop[2]].ToString();
                            }
                            else if (prop.Length == 4)
                            {
                                temp = (threats[i][prop[0]][prop[1]][prop[2]][prop[3]] == null) ? "null" : threats[i][prop[0]][prop[1]][prop[2]][prop[3]].ToString();
                            }

                            if (prop[0] == "installed_date")
                            {
                                if (temp == "null")
                                {
                                    temp = "";
                                }
                                else
                                {
                                    DateTime d2 = DateTime.Parse(temp, null, System.Globalization.DateTimeStyles.RoundtripKind);
                                    temp = "=DATE(" + d2.ToString("yyyy,MM,dd") + ")+TIME(" + d2.ToString("HH,mm,ss") + ")";
                                }
                            }

                            dataBlock[i, j] = temp;
                        }
                        catch { }
                    }
                }

                Excel.Range range;
                range = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A5", Missing.Value);

                if (threats.Count > 0)
                {
                    range = range.Resize[rowCount, colCount];
                    range.Cells.ClearFormats();
                    // Writes the array into Excel
                    // This is probably the single thing that sped up the report the most, by writing array
                    range.Value     = dataBlock;
                    range.Font.Size = "10";
                    range.RowHeight = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A2", "A2").Height;
                }
                #endregion

                #region Column Headers
                // Column Headers
                // =================================================================================================================
                eHelper.WriteHeaders("Process Data", colCount, rowCount, stopWatch);

                // This block writes the column headers
                string hd = "";
                for (int m = 0; m < AttribCollection.Count; m++)
                {
                    TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
                    hd = textInfo.ToTitleCase(AttribCollection[m].Key).Replace('_', ' ');
                    (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Cells[4, m + 1] = hd;
                }
                #endregion

                #region Formatting
                // Create the data filter
                // =================================================================================================================
                Excel.Range range2;
                range2 = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A4", Missing.Value);
                range2 = range2.Resize[rowCount + 1, colCount];
                range2.Select();
                // range2.AutoFilter("1", "<>", Excel.XlAutoFilterOperator.xlOr, "", true);
                range2.AutoFilter(1, Type.Missing, Excel.XlAutoFilterOperator.xlOr, Type.Missing, true);

                // Format number columns
                // =================================================================================================================
                for (int i = 0; i < integerCol.Count; i++)
                {
                    Excel.Range rangeInt;
                    rangeInt = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range(eHelper.ExcelColumnLetter((int)integerCol[i]) + "5", eHelper.ExcelColumnLetter((int)integerCol[i]) + (rowCount + 5).ToString());
                    rangeInt.NumberFormat = "0";
                    rangeInt.Cells.HorizontalAlignment = -4152; // Right align the number
                    rangeInt.Value = rangeInt.Value;            // Strange technique and workaround to get numbers into Excel. Otherwise, Excel sees them as Text
                }

                // Format date time columns
                // =================================================================================================================
                for (int j = 0; j < dateTimeCol.Count; j++)
                {
                    Excel.Range rangeTime;
                    rangeTime = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range(eHelper.ExcelColumnLetter((int)dateTimeCol[j]) + "5", eHelper.ExcelColumnLetter((int)dateTimeCol[j]) + (rowCount + 5).ToString());
                    rangeTime.NumberFormat = "[$-409]yyyy/mm/dd hh:mm AM/PM;@";
                    rangeTime.Cells.HorizontalAlignment = -4152; // Right align the Time
                    rangeTime.Value = rangeTime.Value;           // Strange technique and workaround to get numbers into Excel. Otherwise, Excel sees them as Text
                }

                // Format reference columns
                // =================================================================================================================
                for (int k = 0; k < referenceCol.Count; k++)
                {
                    Excel.Range rangeReference;
                    rangeReference = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range(eHelper.ExcelColumnLetter((int)referenceCol[k]) + "5", eHelper.ExcelColumnLetter((int)referenceCol[k]) + (rowCount + 4).ToString());
                    rangeReference.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(r_color_ref, g_color_ref, b_color_ref));
                    rangeReference.Formula        = rangeReference.Value;

                    rangeReference = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range(eHelper.ExcelColumnLetter((int)referenceCol[k]) + "4", eHelper.ExcelColumnLetter((int)referenceCol[k]) + "4");
                    rangeReference.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(r_color_refh, g_color_refh, b_color_refh));
                    // rangeReference.Value = rangeReference.Value;
                }

                if (referenceCol.Count > 0)
                {
                    Excel.Range rangeReference;
                    rangeReference                = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("E2", "E2");
                    rangeReference.Value          = "Reference lookup data";
                    rangeReference.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(r_color_refh, g_color_refh, b_color_refh));
                }


                // Autofit column width
                // Formats the column width nicely to see the content, but not too wide and limit to maximum of 80
                // =================================================================================================================
                (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.Columns.AutoFit();
                for (int i = 0; i < colCount; i++)
                {
                    Excel.Range rangeCol;
                    rangeCol = (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range(eHelper.ExcelColumnLetter(i) + "1", eHelper.ExcelColumnLetter(i) + "1");
                    if (Convert.ToInt32(rangeCol.ColumnWidth) > maxColumnWidth)
                    {
                        rangeCol.ColumnWidth = maxColumnWidth;
                    }
                }

                // Place the cursor in cell A2 - which is at the start of the document
                // =================================================================================================================
                (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.get_Range("A2", "A2").Select();
                #endregion


                formMsg.Message("Creating pivot tables and charts for the process data...", "", allowCancel: false);

                (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ScreenUpdating = false;
                GenerateReport();
                (ADXAddinModule.CurrentInstance as AddinModule).ExcelApp.ScreenUpdating = true;

                formMsg.Hide();

                // This is saved for viewing in the Show API window
                Globals.ApiResults = JArray.Parse(results.ToString()).ToString();
            }
            catch (Exception ex)
            {
                formMsg.Hide();
                MessageBox.Show(ex.Message, "Error extracting Process data", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 41
0
        public static string GetDatabasePath(string backend, Options options, bool autoCreate = true, bool anyUsername = false)
        {
            if (options == null)
                options = new Options(new Dictionary<string, string>());

            if (!string.IsNullOrEmpty(options.Dbpath))
                return options.Dbpath;
         
            var folder = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Duplicati");
            if (!System.IO.Directory.Exists(folder))
                System.IO.Directory.CreateDirectory(folder);
                
            var file = System.IO.Path.Combine(folder, "dbconfig.json");
            List<BackendEntry> configs;
            if (!System.IO.File.Exists(file))
                configs = new List<BackendEntry>();
            else
                configs = Newtonsoft.Json.JsonConvert.DeserializeObject<List<BackendEntry>>(System.IO.File.ReadAllText(file, System.Text.Encoding.UTF8));
            
            var uri = new Library.Utility.Uri(backend);
            string server = uri.Host;
            string path = uri.Path;
            string type = uri.Scheme;
            int port = uri.Port;
            string username = uri.Username;
            string password = uri.Password;
            string prefix = options.Prefix;
            
            if (username == null || password == null)
            {
                var sopts = DynamicLoader.BackendLoader.GetSupportedCommands(backend);
                var ropts = new Dictionary<string, string>(options.RawOptions);
                foreach(var k in uri.QueryParameters.AllKeys)
                    ropts[k] = uri.QueryParameters[k];
                
                if (sopts != null)
                {
                    foreach(var o in sopts)
                    {
                        if (username == null && o.Aliases != null && o.Aliases.Contains("auth-username", StringComparer.InvariantCultureIgnoreCase) && ropts.ContainsKey(o.Name))
                            username = ropts[o.Name];
                        if (password == null && o.Aliases != null && o.Aliases.Contains("auth-password", StringComparer.InvariantCultureIgnoreCase) && ropts.ContainsKey(o.Name))
                            password = ropts[o.Name];
                    }
                
                    foreach(var o in sopts)
                    {
                        if (username == null && o.Name.Equals("auth-username", StringComparison.InvariantCultureIgnoreCase) && ropts.ContainsKey("auth-username"))
                            username = ropts["auth-username"];
                        if (password == null && o.Name.Equals("auth-password", StringComparison.InvariantCultureIgnoreCase) && ropts.ContainsKey("auth-password"))
                            password = ropts["auth-password"];
                    }
                }
            }
            
            if (password != null)
                password = Library.Utility.Utility.ByteArrayAsHexString(System.Security.Cryptography.SHA256.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(password + "!" + uri.Scheme + "!" + uri.HostAndPath)));
                
            //Now find the one that matches :)
            var matches = (from n in configs
                where 
                    n.Type == type && 
                    //n.Passwordhash == password && 
                    n.Username == username && 
                    n.Port == port && 
                    n.Server == server && 
                    n.Path == path && 
                    n.Prefix == prefix
                select n).ToList();
            
            if (matches.Count > 1)
                throw new Exception(string.Format("Multiple sources found for: {0}", backend));
            
            // Re-select
            if (matches.Count == 0 && anyUsername && string.IsNullOrEmpty(username))
            {
                matches = (from n in configs
                    where 
                        n.Type == type && 
                        n.Port == port && 
                        n.Server == server && 
                        n.Path == path && 
                        n.Prefix == prefix
                    select n).ToList();
                    
                if (matches.Count > 1)
                    throw new Exception(String.Format("Multiple sources found for \"{0}\", try supplying --{1}", backend, "auth-username"));
            }
            
            if (matches.Count == 0 && !autoCreate)
                return null;
            
            if (matches.Count == 0)
            {
                var backupname = options.BackupName;
                if (string.IsNullOrEmpty(backupname) || backupname == Options.DefaultBackupName)
                    backupname = GenerateRandomName();
                else
                {
                    foreach(var c in System.IO.Path.GetInvalidFileNameChars())
                        backupname = backupname.Replace(c.ToString(), "");
                }
                
                var newpath = System.IO.Path.Combine(folder, backupname + ".sqlite");
                int max_tries = 100;
                while (System.IO.File.Exists(newpath) && max_tries-- > 0)
                    newpath = System.IO.Path.Combine(folder, GenerateRandomName());
                
                if (System.IO.File.Exists(newpath))
                    throw new Exception("Unable to find a unique name for the database, please use --dbpath");
                
                //Create a new one, add it to the list, and save it
                configs.Add(new BackendEntry() {
                    Type = type,
                    Server = server,
                    Path = path,
                    Prefix = prefix,
                    Username = username,
                    //Passwordhash = password,
                    Port = port,
                    Databasepath = newpath, 
                    ParameterFile = null
                });
                
                var settings = new Newtonsoft.Json.JsonSerializerSettings();
                settings.Formatting = Newtonsoft.Json.Formatting.Indented;
                System.IO.File.WriteAllText(file, Newtonsoft.Json.JsonConvert.SerializeObject(configs, settings), System.Text.Encoding.UTF8);
                
                return newpath;
            }
            else
            {
                return matches[0].Databasepath;
            }
            
        }
        public async Task <IActionResult> Post([FromBody] FinanceLoanDocumentUIViewModel vm)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (vm == null || (vm.DocType != FinanceDocTypeViewModel.DocType_BorrowFrom &&
                               vm.DocType != FinanceDocTypeViewModel.DocType_LendTo))
            {
                return(BadRequest("No data is inputted"));
            }
            if (vm.HID <= 0)
            {
                return(BadRequest("Not HID inputted"));
            }

            String usrName = String.Empty;

            if (Startup.UnitTestMode)
            {
                usrName = UnitTestUtility.UnitTestUser;
            }
            else
            {
                var usrObj = HIHAPIUtility.GetUserClaim(this);
                usrName = usrObj.Value;
            }
            if (String.IsNullOrEmpty(usrName))
            {
                return(BadRequest("User cannot recognize"));
            }

            // Check the items
            if (vm.Items.Count != 1)
            {
                return(BadRequest("Only one item doc is supported by far"));
            }
            if (vm.AccountVM == null || vm.AccountVM.ExtraInfo_Loan == null)
            {
                return(BadRequest("No account info!"));
            }
            if (vm.AccountVM.ExtraInfo_Loan.LoanTmpDocs.Count <= 0)
            {
                return(BadRequest("No template docs defined!"));
            }
            else
            {
                foreach (var tdoc in vm.AccountVM.ExtraInfo_Loan.LoanTmpDocs)
                {
                    if (!tdoc.ControlCenterID.HasValue && !tdoc.OrderID.HasValue)
                    {
                        return(BadRequest("Either control center or order shall be specified in Loan Template doc"));
                    }
                    if (tdoc.TranAmount <= 0)
                    {
                        return(BadRequest("Amount is zero!"));
                    }
                }
            }

            // Update the database
            SqlConnection  conn        = null;
            SqlCommand     cmd         = null;
            SqlDataReader  reader      = null;
            SqlTransaction tran        = null;
            String         queryString = "";
            Int32          nNewDocID   = -1;
            String         strErrMsg   = "";
            HttpStatusCode errorCode   = HttpStatusCode.OK;

            try
            {
                using (conn = new SqlConnection(Startup.DBConnectionString))
                {
                    await conn.OpenAsync();

                    // Check Home assignment with current user
                    try
                    {
                        HIHAPIUtility.CheckHIDAssignment(conn, vm.HID, usrName);
                    }
                    catch (Exception)
                    {
                        errorCode = HttpStatusCode.BadRequest;
                        throw;
                    }

                    tran = conn.BeginTransaction();

                    // First, create the doc header => nNewDocID
                    queryString = HIHDBUtility.GetFinDocHeaderInsertString();
                    cmd         = new SqlCommand(queryString, conn)
                    {
                        Transaction = tran
                    };

                    HIHDBUtility.BindFinDocHeaderInsertParameter(cmd, vm, usrName);
                    SqlParameter idparam = cmd.Parameters.AddWithValue("@Identity", SqlDbType.Int);
                    idparam.Direction = ParameterDirection.Output;

                    Int32 nRst = await cmd.ExecuteNonQueryAsync();

                    nNewDocID = (Int32)idparam.Value;
                    cmd.Dispose();
                    cmd = null;

                    // Then, creating the items
                    foreach (FinanceDocumentItemUIViewModel ivm in vm.Items)
                    {
                        if (vm.DocType == FinanceDocTypeViewModel.DocType_BorrowFrom)
                        {
                            ivm.TranType = FinanceTranTypeViewModel.TranType_BorrowFrom;
                        }
                        else if (vm.DocType == FinanceDocTypeViewModel.DocType_LendTo)
                        {
                            ivm.TranType = FinanceTranTypeViewModel.TranType_LendTo;
                        }

                        queryString = HIHDBUtility.GetFinDocItemInsertString();
                        cmd         = new SqlCommand(queryString, conn)
                        {
                            Transaction = tran
                        };
                        HIHDBUtility.BindFinDocItemInsertParameter(cmd, ivm, nNewDocID);

                        await cmd.ExecuteNonQueryAsync();

                        cmd.Dispose();
                        cmd = null;

                        // Tags
                        if (ivm.TagTerms.Count > 0)
                        {
                            // Create tags
                            foreach (var term in ivm.TagTerms)
                            {
                                queryString = HIHDBUtility.GetTagInsertString();

                                cmd = new SqlCommand(queryString, conn, tran);

                                HIHDBUtility.BindTagInsertParameter(cmd, vm.HID, HIHTagTypeEnum.FinanceDocumentItem, nNewDocID, term, ivm.ItemID);

                                await cmd.ExecuteNonQueryAsync();

                                cmd.Dispose();
                                cmd = null;
                            }
                        }
                    }

                    // Third, go to the account creation => nNewAccountID
                    queryString = HIHDBUtility.GetFinanceAccountHeaderInsertString();

                    cmd = new SqlCommand(queryString, conn)
                    {
                        Transaction = tran
                    };
                    HIHDBUtility.BindFinAccountInsertParameter(cmd, vm.AccountVM, usrName);

                    SqlParameter idparam2 = cmd.Parameters.AddWithValue("@Identity", SqlDbType.Int);
                    idparam2.Direction = ParameterDirection.Output;

                    nRst = await cmd.ExecuteNonQueryAsync();

                    Int32 nNewAccountID = (Int32)idparam2.Value;
                    cmd.Dispose();
                    cmd = null;

                    // 3a. Create another item to loan document
                    var nMaxItemID = vm.Items.Max(item => item.ItemID);
                    foreach (FinanceDocumentItemUIViewModel ivm in vm.Items)
                    {
                        ivm.ItemID    = ++nMaxItemID;
                        ivm.AccountID = nNewAccountID;
                        if (vm.DocType == FinanceDocTypeViewModel.DocType_BorrowFrom)
                        {
                            ivm.TranType = FinanceTranTypeViewModel.TranType_OpeningLiability;
                        }
                        else if (vm.DocType == FinanceDocTypeViewModel.DocType_LendTo)
                        {
                            ivm.TranType = FinanceTranTypeViewModel.TranType_OpeningAsset;
                        }

                        queryString = HIHDBUtility.GetFinDocItemInsertString();
                        SqlCommand cmd2 = new SqlCommand(queryString, conn)
                        {
                            Transaction = tran
                        };
                        HIHDBUtility.BindFinDocItemInsertParameter(cmd2, ivm, nNewDocID);

                        await cmd2.ExecuteNonQueryAsync();

                        cmd2.Dispose();
                        cmd2 = null;
                    }

                    // Fourth, creat the Loan part
                    queryString = HIHDBUtility.GetFinanceAccountLoanInsertString();
                    cmd         = new SqlCommand(queryString, conn)
                    {
                        Transaction = tran
                    };

                    HIHDBUtility.BindFinAccountLoanInsertParameter(cmd, vm.AccountVM.ExtraInfo_Loan, nNewDocID, nNewAccountID, usrName);
                    nRst = await cmd.ExecuteNonQueryAsync();

                    cmd.Dispose();
                    cmd = null;

                    // Fifth, create template docs
                    foreach (FinanceTmpDocLoanViewModel avm in vm.AccountVM.ExtraInfo_Loan.LoanTmpDocs)
                    {
                        queryString = HIHDBUtility.GetFinanceTmpDocLoanInsertString();

                        cmd = new SqlCommand(queryString, conn)
                        {
                            Transaction = tran
                        };

                        HIHDBUtility.BindFinTmpDocLoanParameter(cmd, avm, nNewAccountID, usrName);
                        await cmd.ExecuteNonQueryAsync();

                        cmd.Dispose();
                        cmd = null;
                    }

                    tran.Commit();

                    // Update the buffer
                    // Account list
                    var cacheKey = String.Format(CacheKeys.FinAccountList, vm.HID, null);
                    this._cache.Remove(cacheKey);
                }
            }
            catch (Exception exp)
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine(exp.Message);
#endif

                if (tran != null)
                {
                    tran.Rollback();
                }

                strErrMsg = exp.Message;
                if (errorCode == HttpStatusCode.OK)
                {
                    errorCode = HttpStatusCode.InternalServerError;
                }
            }
            finally
            {
                if (tran != null)
                {
                    tran.Dispose();
                    tran = null;
                }
                if (reader != null)
                {
                    reader.Dispose();
                    reader = null;
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                    cmd = null;
                }
                if (conn != null)
                {
                    conn.Dispose();
                    conn = null;
                }
            }

            if (errorCode != HttpStatusCode.OK)
            {
                switch (errorCode)
                {
                case HttpStatusCode.Unauthorized:
                    return(Unauthorized());

                case HttpStatusCode.NotFound:
                    return(NotFound());

                case HttpStatusCode.BadRequest:
                    return(BadRequest(strErrMsg));

                default:
                    return(StatusCode(500, strErrMsg));
                }
            }

            vm.ID = nNewDocID;
            var setting = new Newtonsoft.Json.JsonSerializerSettings
            {
                DateFormatString = HIHAPIConstants.DateFormatPattern,
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };

            return(new JsonResult(vm, setting));
        }
Ejemplo n.º 43
0
        /// <summary> Initialization function for this storage provider. </summary>
        /// <see cref="IProvider.Init"/>
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            Name = name;
            serviceId = providerRuntime.ServiceId.ToString();

            if (!config.Properties.ContainsKey(DATA_CONNECTION_STRING) || string.IsNullOrWhiteSpace(config.Properties[DATA_CONNECTION_STRING]))
                throw new ArgumentException("DataConnectionString property not set");

            dataConnectionString = config.Properties["DataConnectionString"];

            if (config.Properties.ContainsKey(TABLE_NAME_PROPERTY))
                tableName = config.Properties[TABLE_NAME_PROPERTY];

            isDeleteStateOnClear = config.Properties.ContainsKey(DELETE_ON_CLEAR_PROPERTY) &&
                "true".Equals(config.Properties[DELETE_ON_CLEAR_PROPERTY], StringComparison.OrdinalIgnoreCase);

            Log = providerRuntime.GetLogger("Storage.AzureTableStorage." + id);

            var initMsg = string.Format("Init: Name={0} ServiceId={1} Table={2} DeleteStateOnClear={3}",
                Name, serviceId, tableName, isDeleteStateOnClear);

            if (config.Properties.ContainsKey(USE_JSON_FORMAT_PROPERTY))
                useJsonFormat = "true".Equals(config.Properties[USE_JSON_FORMAT_PROPERTY], StringComparison.OrdinalIgnoreCase);
            
            if (useJsonFormat)
            {
                jsonSettings = new Newtonsoft.Json.JsonSerializerSettings();
                jsonSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All;
            }
            initMsg = String.Format("{0} UseJsonFormat={1}", initMsg, useJsonFormat);

            Log.Info((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, initMsg);
            Log.Info((int)AzureProviderErrorCode.AzureTableProvider_ParamConnectionString, "AzureTableStorage Provider is using DataConnectionString: {0}", ConfigUtilities.PrintDataConnectionInfo(dataConnectionString));
            tableDataManager = new GrainStateTableDataManager(tableName, dataConnectionString, Log);
            return tableDataManager.InitTableAsync();
        }
Ejemplo n.º 44
0
        static void Main(string[] args)
        {
            bool isAuthenticated = authenticateRS();

            while (!isAuthenticated)
            {
                Console.WriteLine("Failed to authenticate to RightScale API - try again? (Y/n)");
                string retry = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(retry) || retry.ToLower().StartsWith("y"))
                {
                    isAuthenticated = authenticateRS();
                }
                else
                {
                    Console.WriteLine("Exiting process.  Press any key to continue...");
                    Console.ReadKey();
                    return;
                }
            }

            if (isAuthenticated)
            {
                Console.WriteLine("Successfully authenticated to the RightScale API");
            }
            else
            {
                Console.WriteLine("Cannot authenticate to RS API - Press any key to continue...");
                Console.ReadKey();
                return;
            }

            string manifestLocation = @"Manifests/Windows3Tier.manifest.json";

            Console.WriteLine();
            Console.WriteLine("Use default manifest (" + manifestLocation + ") (Y/n)");

            ConsoleKeyInfo defaultResponse = Console.ReadKey();
            if (defaultResponse.KeyChar.ToString().ToLower().StartsWith("y") || defaultResponse.Key == ConsoleKey.Enter)
            {
                Console.WriteLine();
                Console.WriteLine("Reading Default Manifest.");
                Console.WriteLine();
            }
            else
            {
                bool fileExists = false;
                while (!fileExists)
                {
                    Console.WriteLine();
                    Console.WriteLine("Input manifest path:");
                    manifestLocation = Console.ReadLine();
                    if (System.IO.File.Exists(manifestLocation))
                    {
                        fileExists = true;
                    }
                    else
                    {
                        Console.WriteLine();
                        Console.WriteLine("File " + manifestLocation + " does not exist or is inaccessible--enter another path? (Y/n)");
                        ConsoleKeyInfo retryResponse = Console.ReadKey();
                        if (retryResponse.KeyChar.ToString().ToLower() != "y" && retryResponse.Key != ConsoleKey.Enter)
                        {
                            Console.WriteLine("Exiting per request... press any key...");
                            Console.ReadKey();
                            return;
                        }
                    }
                }
            }
            Console.WriteLine();
            Console.WriteLine("Ready to Proceed? (Y/n)");

            ConsoleKeyInfo readyResponse = Console.ReadKey();

            if (readyResponse.KeyChar.ToString().ToLower() != "y" && readyResponse.Key != ConsoleKey.Enter)
            {
                Console.WriteLine("Exiting per request... press any key...");
                Console.ReadKey();
                return;
            }

            string manifestContents = string.Empty;

            using (System.IO.StreamReader sr = new System.IO.StreamReader(manifestLocation))
            {
                manifestContents = sr.ReadToEnd();
            }

            Newtonsoft.Json.JsonSerializerSettings jsettings = new Newtonsoft.Json.JsonSerializerSettings();
            jsettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto;
            jsettings.TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full;

            Dictionary<string, object> inputs = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(manifestContents, jsettings);

            if (!string.IsNullOrWhiteSpace(rsAuthKey))
            {
                inputs.Add("rsOauthRefreshToken", rsAuthKey);
            }
            else if (!string.IsNullOrWhiteSpace(rsEmail) && !string.IsNullOrWhiteSpace(rsAccountNo) && !string.IsNullOrWhiteSpace(rsPassword))
            {
                inputs.Add("rsUsername", rsEmail);
                inputs.Add("rsPassword", rsPassword);
                inputs.Add("rsAccountNo", rsAccountNo);
            }

            //add a default deployment description if it doesn't exist
            if (!inputs.ContainsKey("deploymentDescription"))
            {
                inputs.Add("deploymentDescription", "Created via Windows Workflow Foundation and RightScale.netClient at " + DateTime.Now.ToString());
            }

            Activity workflow1 = new Windows3TierWorkflow();

            WorkflowInvoker.Invoke(workflow1, inputs);
        }
Ejemplo n.º 45
0
        public static string GetDatabasePath(string backend, Options options, bool autoCreate = true, bool anyUsername = false)
        {
            if (options == null)
            {
                options = new Options(new Dictionary <string, string>());
            }

            if (!string.IsNullOrEmpty(options.Dbpath))
            {
                return(options.Dbpath);
            }

            var folder = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Duplicati");

            if (!System.IO.Directory.Exists(folder))
            {
                System.IO.Directory.CreateDirectory(folder);
            }

            var file = System.IO.Path.Combine(folder, "dbconfig.json");
            List <BackendEntry> configs;

            if (!System.IO.File.Exists(file))
            {
                configs = new List <BackendEntry>();
            }
            else
            {
                configs = Newtonsoft.Json.JsonConvert.DeserializeObject <List <BackendEntry> >(System.IO.File.ReadAllText(file, System.Text.Encoding.UTF8));
            }

            var    uri      = new Library.Utility.Uri(backend);
            string server   = uri.Host;
            string path     = uri.Path;
            string type     = uri.Scheme;
            int    port     = uri.Port;
            string username = uri.Username;
            string password = uri.Password;
            string prefix   = options.Prefix;

            if (username == null || password == null)
            {
                var sopts = DynamicLoader.BackendLoader.GetSupportedCommands(backend);
                var ropts = new Dictionary <string, string>(options.RawOptions);
                foreach (var k in uri.QueryParameters.AllKeys)
                {
                    ropts[k] = uri.QueryParameters[k];
                }

                if (sopts != null)
                {
                    foreach (var o in sopts)
                    {
                        if (username == null && o.Aliases != null && o.Aliases.Contains("auth-username", StringComparer.InvariantCultureIgnoreCase) && ropts.ContainsKey(o.Name))
                        {
                            username = ropts[o.Name];
                        }
                        if (password == null && o.Aliases != null && o.Aliases.Contains("auth-password", StringComparer.InvariantCultureIgnoreCase) && ropts.ContainsKey(o.Name))
                        {
                            password = ropts[o.Name];
                        }
                    }

                    foreach (var o in sopts)
                    {
                        if (username == null && o.Name.Equals("auth-username", StringComparison.InvariantCultureIgnoreCase) && ropts.ContainsKey("auth-username"))
                        {
                            username = ropts["auth-username"];
                        }
                        if (password == null && o.Name.Equals("auth-password", StringComparison.InvariantCultureIgnoreCase) && ropts.ContainsKey("auth-password"))
                        {
                            password = ropts["auth-password"];
                        }
                    }
                }
            }

            if (password != null)
            {
                password = Library.Utility.Utility.ByteArrayAsHexString(System.Security.Cryptography.SHA256.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(password + "!" + uri.Scheme + "!" + uri.HostAndPath)));
            }

            //Now find the one that matches :)
            var matches = (from n in configs
                           where
                           n.Type == type &&
                           //n.Passwordhash == password &&
                           n.Username == username &&
                           n.Port == port &&
                           n.Server == server &&
                           n.Path == path &&
                           n.Prefix == prefix
                           select n).ToList();

            if (matches.Count > 1)
            {
                throw new Exception(string.Format("Multiple sources found for: {0}", backend));
            }

            // Re-select
            if (matches.Count == 0 && anyUsername && string.IsNullOrEmpty(username))
            {
                matches = (from n in configs
                           where
                           n.Type == type &&
                           n.Port == port &&
                           n.Server == server &&
                           n.Path == path &&
                           n.Prefix == prefix
                           select n).ToList();

                if (matches.Count > 1)
                {
                    throw new Exception(String.Format("Multiple sources found for \"{0}\", try supplying --{1}", backend, "auth-username"));
                }
            }

            if (matches.Count == 0 && !autoCreate)
            {
                return(null);
            }

            if (matches.Count == 0)
            {
                var backupname = options.BackupName;
                if (string.IsNullOrEmpty(backupname) || backupname == Options.DefaultBackupName)
                {
                    backupname = GenerateRandomName();
                }
                else
                {
                    foreach (var c in System.IO.Path.GetInvalidFileNameChars())
                    {
                        backupname = backupname.Replace(c.ToString(), "");
                    }
                }

                var newpath   = System.IO.Path.Combine(folder, backupname + ".sqlite");
                int max_tries = 100;
                while (System.IO.File.Exists(newpath) && max_tries-- > 0)
                {
                    newpath = System.IO.Path.Combine(folder, GenerateRandomName());
                }

                if (System.IO.File.Exists(newpath))
                {
                    throw new Exception("Unable to find a unique name for the database, please use --dbpath");
                }

                //Create a new one, add it to the list, and save it
                configs.Add(new BackendEntry()
                {
                    Type     = type,
                    Server   = server,
                    Path     = path,
                    Prefix   = prefix,
                    Username = username,
                    //Passwordhash = password,
                    Port          = port,
                    Databasepath  = newpath,
                    ParameterFile = null
                });

                var settings = new Newtonsoft.Json.JsonSerializerSettings();
                settings.Formatting = Newtonsoft.Json.Formatting.Indented;
                System.IO.File.WriteAllText(file, Newtonsoft.Json.JsonConvert.SerializeObject(configs, settings), System.Text.Encoding.UTF8);

                return(newpath);
            }
            else
            {
                return(matches[0].Databasepath);
            }
        }
Ejemplo n.º 46
0
        Init(string cwd, string settingsJson)
        {
            FileLog.logPath = System.IO.Path.Combine(cwd, "debug.log");
            System.IO.File.Delete(FileLog.logPath);
            Local.jsonSerializerSettings = new Newtonsoft.Json
                                           .JsonSerializerSettings
            {
                DateParseHandling = Newtonsoft.Json.DateParseHandling.None,
                Formatting        = Newtonsoft.Json.Formatting.Indented
            };
            Local.state = Local.jsonParseDict2(
                new System.Text.RegularExpressions.Regex(
                    @"```\w*?\n([\S\s]*?)\n```"
                    ).Match(
                    System.IO.File.ReadAllText(
                        System.IO.Path.Combine(cwd, "README.md")
                        )
                    ).Groups[1].ToString()
                );
            Local.cheat_enginevalidation_off = (
                state["cheat_enginevalidation_off"] != ""
                );
            Local.cheat_mechcomponentsize_1 = (
                state["cheat_mechcomponentsize_1"] != ""
                );
            Local.cheat_pilotabilitycooldown_0 = (
                state["cheat_pilotabilitycooldown_0"] != ""
                );
            try
            {
                foreach (var item in Local.jsonParseDict2(
                             System.IO.File.ReadAllText(
                                 System.IO.Path.Combine(cwd, "settings.json")
                                 )
                             ))
                {
                    Local.state.setItem(item.Key, item.Value);
                }
            }
            catch (Exception err)
            {
                Local.debugLog("settings.json", err);
            }
            System.IO.File.WriteAllText(
                System.IO.Path.Combine(cwd, "settings.json"),
                Local.jsonStringify(Local.state)
                );
            Local.stateChangedAfter();
            var harmony = HarmonyInstance.Create(
                "com.github.kaizhu256.RoguetechCheat"
                );

            harmony.PatchAll(Assembly.GetExecutingAssembly());
            // cheat_enginevalidation_off
            if (Local.state.getItem("cheat_enginevalidation_off") != "")
            {
                object engineSettings;
                engineSettings = typeof(MechEngineer.Control).GetField(
                    "settings",
                    BindingFlags.NonPublic | BindingFlags.Static
                    ).GetValue(null);
                // EngineFeature.settings => Control.settings.Engine
                engineSettings = engineSettings.GetType().GetField(
                    "Engine",
                    BindingFlags.Instance | BindingFlags.Public
                    ).GetValue(engineSettings);
                // set AllowMixingHeatSinkTypes
                Traverse.Create(engineSettings).Field(
                    "AllowMixingHeatSinkTypes"
                    ).SetValue(true);
                // set EnforceRulesForAdditionalInternalHeatSinks
                Traverse.Create(engineSettings).Field(
                    "EnforceRulesForAdditionalInternalHeatSinks"
                    ).SetValue(false);
                // set LimitEngineCoresToTonnage
                Traverse.Create(engineSettings).Field(
                    "LimitEngineCoresToTonnage"
                    ).SetValue(false);
            }
        }
        public async Task <IActionResult> Get([FromRoute] int id, [FromQuery] Int32 hid = 0)
        {
            if (hid <= 0)
            {
                return(BadRequest("Not HID inputted"));
            }

            String usrName = String.Empty;

            if (Startup.UnitTestMode)
            {
                usrName = UnitTestUtility.UnitTestUser;
            }
            else
            {
                var usrObj = HIHAPIUtility.GetUserClaim(this);
                usrName = usrObj.Value;
            }
            if (String.IsNullOrEmpty(usrName))
            {
                return(BadRequest("User cannot recognize"));
            }

            FinanceLoanDocumentUIViewModel vm = new FinanceLoanDocumentUIViewModel();
            SqlConnection  conn        = null;
            SqlCommand     cmd         = null;
            SqlDataReader  reader      = null;
            String         queryString = "";
            String         strErrMsg   = "";
            HttpStatusCode errorCode   = HttpStatusCode.OK;

            try
            {
                queryString = HIHDBUtility.GetFinanceDocLoanQueryString(id, hid);

                using (conn = new SqlConnection(Startup.DBConnectionString))
                {
                    await conn.OpenAsync();

                    // Check Home assignment with current user
                    try
                    {
                        HIHAPIUtility.CheckHIDAssignment(conn, hid, usrName);
                    }
                    catch (Exception)
                    {
                        errorCode = HttpStatusCode.BadRequest;
                        throw;
                    }

                    cmd    = new SqlCommand(queryString, conn);
                    reader = cmd.ExecuteReader();

                    if (!reader.HasRows)
                    {
                        errorCode = HttpStatusCode.NotFound;
                        throw new Exception();
                    }

                    // Header
                    while (reader.Read())
                    {
                        HIHDBUtility.FinDocHeader_DB2VM(reader, vm);
                    }
                    reader.NextResult();

                    // Items
                    while (reader.Read())
                    {
                        FinanceDocumentItemUIViewModel itemvm = new FinanceDocumentItemUIViewModel();
                        HIHDBUtility.FinDocItem_DB2VM(reader, itemvm);

                        vm.Items.Add(itemvm);
                    }
                    reader.NextResult();

                    // Account
                    while (reader.Read())
                    {
                        FinanceAccountUIViewModel vmAccount = new FinanceAccountUIViewModel();
                        Int32 aidx = 0;
                        aidx = HIHDBUtility.FinAccountHeader_DB2VM(reader, vmAccount, aidx);
                        vmAccount.ExtraInfo_Loan = new FinanceAccountExtLoanViewModel();
                        HIHDBUtility.FinAccountLoan_DB2VM(reader, vmAccount.ExtraInfo_Loan, aidx);

                        vm.AccountVM = vmAccount;
                    }
                    reader.NextResult();

                    // Tmp docs
                    while (reader.Read())
                    {
                        FinanceTmpDocLoanViewModel loanvm = new FinanceTmpDocLoanViewModel();
                        HIHDBUtility.FinTmpDocLoan_DB2VM(reader, loanvm);
                        vm.AccountVM.ExtraInfo_Loan.LoanTmpDocs.Add(loanvm);
                    }
                    reader.NextResult();

                    // Tag
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            Int32  itemID = reader.GetInt32(0);
                            String sterm  = reader.GetString(1);

                            foreach (var vitem in vm.Items)
                            {
                                if (vitem.ItemID == itemID)
                                {
                                    vitem.TagTerms.Add(sterm);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine(exp.Message);
                strErrMsg = exp.Message;
                if (errorCode == HttpStatusCode.OK)
                {
                    errorCode = HttpStatusCode.InternalServerError;
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                    reader = null;
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                    cmd = null;
                }
                if (conn != null)
                {
                    conn.Dispose();
                    conn = null;
                }
            }

            if (errorCode != HttpStatusCode.OK)
            {
                switch (errorCode)
                {
                case HttpStatusCode.Unauthorized:
                    return(Unauthorized());

                case HttpStatusCode.NotFound:
                    return(NotFound());

                case HttpStatusCode.BadRequest:
                    return(BadRequest(strErrMsg));

                default:
                    return(StatusCode(500, strErrMsg));
                }
            }

            var setting = new Newtonsoft.Json.JsonSerializerSettings
            {
                DateFormatString = HIHAPIConstants.DateFormatPattern,
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };

            return(new JsonResult(vm, setting));
        }
Ejemplo n.º 48
0
        public override object Request(string method, string uri, string payload)
        {
            if (method == "GET")
            {
                var id = uri.Split(':')[2];
                var app =uri.Split(':')[1];
                var service = uri.Split(':')[0];
                object result = null;
                if (cache.ContainsKey(uri))
                {
                    return (cache[uri]);
                }

                Thread.Sleep((int)new Random().Next(0, 3000));
                using (StreamReader sr = new StreamReader("resources/sampleentity.json"))
                {
                    var settings = new Newtonsoft.Json.JsonSerializerSettings();
                   var json = sr.ReadToEnd();
                   json = json.Replace("{{id}}", id);
                   json = json.Replace("{{service}}", service);
                   json = json.Replace("{{app}}", app);
                   json = json.Replace("{{uri}}", uri);
                    var r  = JObject.Parse(json);

                    result = Newtonsoft.Json.JsonConvert.SerializeObject(r["node"]);
                }
                if (cache.ContainsKey(uri))
                {
                    cache[uri] = result;
                }
                else
                {
                    cache.Add(uri, result);
                }
                return result;

            }
            if(method == "PUT") {
                JObject json = JObject.Parse(payload);
                if (cache.ContainsKey(uri))
                {
                    object obj = (object)cache[uri];
                    IDictionary data = null;
                    if (obj.GetType() == typeof(string))
                    {
                        data = (IDictionary)JObject.Parse((string)obj);
                    }
                    else
                    {
                        data = (IDictionary)obj;
                    }
                    foreach(KeyValuePair<string, JToken> o in json)
                    {
                        if (data.Contains(o.Key))
                        {
                            data[o.Key] = o.Value.ToString();
                        }
                        else
                        {
                            data.Add(o.Key, o.Value.ToString());
                        }
                    }
                    if (obj.GetType() == typeof(string))
                    {
                        cache[uri] = data;
                    }
                    return cache[uri];
                }
            }
            if (method == "FOLLOW")
            {
                if (cache.ContainsKey(uri))
                {
                    IDictionary data = null;
                    var obj = cache[uri];
                    if (obj.GetType() == typeof(string))
                    {
                        data = (IDictionary)JObject.Parse((string)obj);
                    }
                    else
                    {
                        data = (IDictionary)data;
                    }
                    if (data.Contains("following"))
                    {
                        data["following"] = !((bool)data["following"]);
                    }
                    else
                    {
                        data.Add("following", true);
                    }
                    return cache[uri];
                }
            }
            return null;
        }