Пример #1
0
        public static string ToJSON(object target)
        {
            if (target == null)
            {
                return("null");
            }
            var type       = target.GetType();
            var _attribute = type.GetCustomAttributes(false).OfType <JSONClassAttribute>().FirstOrDefault(x => !string.IsNullOrEmpty(x.Advocate));

            if (_attribute != null)
            {
                var _property = type.GetProperty(_attribute.Advocate);
                if (_property == null)
                {
                    throw new Exception("The Advocate (" + _attribute.Advocate + ") doesn't exist on class (" + type.Name + ")");
                }
                return(ToJSON(_property.GetValue(target)));
            }
            var _typecode = Type.GetTypeCode(type);
            var isQuoted  = type.IsEnum || _typecode == TypeCode.String;
            var _string   = "";

            if (_typecode == TypeCode.Object)
            {
                if (target is DynamicObject dio)
                {
                    var dict = dio.GetDynamicMemberNames().ToDictionary(x => x, y => dio.TryGetMember(new DynamicAccess(y, true), out var result) ? result : null);
                    return(ToJSON(dict));
                }
                else if (target is IDictionary dict)
                {
                    var KeyPairs = (Keys : new object[dict.Count], Values : new object[dict.Count]);
                    dict.Keys.CopyTo(KeyPairs.Keys, 0);
                    dict.Values.CopyTo(KeyPairs.Values, 0);
                    return("{" + string.Join(",", KeyPairs.Keys.Zip(KeyPairs.Values, (k, v) => "\"" + k.ToString() + "\":" + ToJSON(v)).ToArray()) + "}");
                }
                else if (type.IsArray || type.GetInterface("ICollection") != null || type.GetInterface("IEnumerable") != null)
                {
                    var _l = new JSONBuilder();
                    foreach (var item in (ICollection)target)
                    {
                        _l.Add(ToJSON(item));
                    }
                    _string += "[" + string.Join(",", _l) + "]";
                }
                else
                {
                    return("{" + string.Join(",", GetAttributeDefinitions(type).Where(x => !x.IgnoreTo).Select(x =>
                    {
                        var Value = x.CustomConvertTo ? ((IJSONValueConverter)target).ConvertToJSON(x.Name, x.property.GetValue(target), x.property) : ToJSON(x.property.GetValue(target));
                        return "\"" + x.Name + "\":" + Value;
                    })) + "}");
                }
            }
            else
            {
                return((isQuoted ? "\"" : "") + (_typecode == TypeCode.Boolean ? target.ToString().ToLower() : target.ToString()) + (isQuoted ? "\"" : ""));
            }
            return(_string);
        }
Пример #2
0
        static void CreateDataset()
        {
            Console.Write("Checking dataset {0}...", datasetName);
            //In a production application, use more specific exception handling.
            try
            {
                //Create a POST web request to list all datasets
                HttpWebRequest request = DatasetRequest(datasetsUri, "POST", AccessToken);

                var datasets = GetAllDatasets().Datasets(datasetName);

                if (!datasets.Any())
                {
                    Console.Write("does not exist.\n");
                    Console.Write("Creating dataset {0}...", datasetName);
                    var tables = new List <object> {
                        new RealTimeVehicleHealthAnomalyReport()
                    };

                    string jsonString = JSONBuilder.CreateTableSchema(datasetName, tables);

                    PostRequest(request, jsonString);
                    //POST request using the json schema from Product
                    Console.Write("created.\n");
                }
                else
                {
                    Console.Write("exists.\n");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #3
0
        public bool Run()
        {
            // packet keys
            PacketKey   k   = new PacketKey();
            JSONBuilder kjb = new JSONBuilder();

            kjb.closeMe();
            k.addToJSON(kjb);

            Console.WriteLine(kjb.ToString());
            Console.WriteLine("====");

            // packets
            Packet p  = new Packet(new ComData("test"));
            string sp = p.Pack();

            Console.WriteLine(sp);

            Packet p2;

            Packet.Unpack(sp, out p2);

            Console.WriteLine(p2);

            return(true);
        }
Пример #4
0
        public string Pack()
        {
            JSONBuilder jb = new JSONBuilder();

            Key.addToJSON(jb);
            jb.addObject("Data", Data);
            jb.closeMe();
            return(jb.ToString());
        }
Пример #5
0
        //public static PacketKey responseKey(PacketKey original)
        //{
        //    var p = new PacketKey();
        //    p.parentValue = original.value;
        //    return p;
        //}

        //public bool isResponseOf(PacketKey other)
        //{
        //    return parentValue == other.value;
        //}

        public void addToJSON(JSONBuilder jb)
        {
            jb.beginItem();

            jb.addField("value");
            jb.addPrimitive(value.ToString());

            jb.endItem();
        }
Пример #6
0
    private StringBuilder bufar; // Contains an array of rows

    public static void Main()
    {
        JSONBuilder jb = new JSONBuilder();

        jb.AddRow();
        jb.Put("Greeting", "Hello");
        jb.AddRow();
        jb.Put("Greeting", "World!");
        Console.WriteLine(jb.Build());
    }
Пример #7
0
 /// <summary>
 /// Check that the sortcode_accountNumber are valid
 /// </summary>
 /// <param name="sortcode">the sortcode to match and validate</param>
 /// <param name="accountNumber">the account number to validate</param>
 /// <returns>Y = true : N = fails</returns>
 public HttpResponseMessage Get(string sortcode, string accountNumber)
 {
     // start a process to validate
     //Services.ModulusWeightService service = new Services.ModulusWeightService();
     if (_modulusWeightService == null)
     {
         return(Request.CreateResponse(HttpStatusCode.NotFound));
     }
     return(Request.CreateResponse(JSONBuilder.ToJSON(_modulusWeightService.Validate(sortcode, accountNumber), _modulusWeightService.ExceptionRulesNotApplied)));
 }
        public override string Serialize()
        {
            var builder = new JSONBuilder();

            builder.WriteKeyValuePair(FEE_FIELD_KEY, Fee);
            builder.WriteKeyValuePair(DIVIDEND_ASSET_FIELD_KEY, DividendAsset);
            builder.WriteKeyValuePair(ACCOUNT_FIELD_KEY, Account);
            builder.WriteKeyValuePair(AMOUNTS_FIELD_KEY, Amounts);
            builder.WriteKeyValuePair(EXTENSIONS_FIELD_KEY, Extensions);
            return(builder.Build());
        }
Пример #9
0
        /// <summary>
        /// Post the rows to Power BI.
        /// </summary>
        private void PostRows(string TableName, DataTable TableData)
        {
            HttpWebRequest request;

            request = GetDatasetRequest(String.Format("{0}/{1}/tables/{2}/rows", datasetsUri, datasetId, TableName), "POST", GetAccessToken());
            string strJasonRows = string.Format("{0}\"rows\":", "{");

            strJasonRows += JSONBuilder.ConvertDataTableTojSonString(TableData);
            strJasonRows += "}";
            PostRequest(request, strJasonRows);
            Log.WriteMessage("Post request completed");
        }
Пример #10
0
        public override string Serialize()
        {
            var builder = new JSONBuilder();

            builder.WriteKeyValuePair(FEE_FIELD_KEY, Fee);
            builder.WriteKeyValuePair(FEE_PAYING_ACCOUNT_FIELD_KEY, FeePayingAccount);
            builder.WriteKeyValuePair(EXPIRATION_TIME_FIELD_KEY, DateTimeConverter.ConvertTo(ExpirationTime));
            builder.WriteKeyValuePair(PROPOSED_OPS_FIELD_KEY, ProposedOperations);
            builder.WriteOptionalStructKeyValuePair(REVIEW_PERIOD_SECONDS_FIELD_KEY, ReviewPeriodSeconds);
            builder.WriteKeyValuePair(EXTENSIONS_FIELD_KEY, Extensions);
            return(builder.Build());
        }
Пример #11
0
        public override string Serialize()
        {
            var builder = new JSONBuilder();

            builder.WriteKeyValuePair(FEE_FIELD_KEY, Fee);
            builder.WriteKeyValuePair(FROM_FIELD_KEY, From);
            builder.WriteKeyValuePair(TO_FIELD_KEY, To);
            builder.WriteKeyValuePair(AMOUNT_FIELD_KEY, Amount);
            builder.WriteOptionalClassKeyValuePair(MEMO_FIELD_KEY, Memo);
            builder.WriteKeyValuePair(EXTENSIONS_FIELD_KEY, Extensions);
            return(builder.Build());
        }
Пример #12
0
 public void addToJSON(JSONBuilder jb)
 {
     jb.addString("DataType", DataType);
     if (Value == null)
     {
         jb.addNull("Value");
     }
     else
     {
         jb.addObject("Value", Value);
     }
     jb.closeMe();
 }
Пример #13
0
        /// <summary>
        /// Creates datasets in Power BI
        /// </summary>
        /// <param name="TableName">string</param>
        /// <returns>bool, true if dataset created</returns>
        internal bool CreateDatasets(string TableName, XmlNode xnData, out string[] NewDataset)
        {
            DataSet        dsData = new DataSet();
            SqlDataAdapter objData;

            if (TableName.Contains(","))
            {
                string[] sarrTables = TableName.Split(',');

                foreach (string sTableName in sarrTables)
                {
                    //Fetch columns from XML
                    string sColumns = xnData.SelectSingleNode("./JobMetadata[@Datasetname='" + sTableName + "']").Attributes["Columns"].Value;
                    sColumns = BuildSQLColumn(sColumns);
                    objData  = new SqlDataAdapter("SELECT " + sColumns + " FROM [" + sTableName + "] T1 ", ConnectionString);
                    objData.Fill(dsData, sTableName);
                    Log.WriteMessage("Filling the dataset");
                }
            }
            else
            {
                //Fetch columns from XML
                string sColumns = xnData.SelectSingleNode("./JobMetadata[@Datasetname='" + TableName + "']").Attributes["Columns"].Value;
                sColumns = BuildSQLColumn(sColumns);

                objData = new SqlDataAdapter("SELECT " + sColumns + " FROM [" + TableName + "] T1 ", ConnectionString);
                objData.Fill(dsData, TableName);
                Log.WriteMessage("Filling the dataset");
            }

            //Create a POST web request to list all datasets
            HttpWebRequest request = GetDatasetRequest(datasetsUri, "POST", GetAccessToken());

            Log.WriteMessage("Posting request using Json Schema");
            string strJason        = JSONBuilder.GetJsonSchema(dsData, PowerBIDatasetName);
            string responseContent = PostRequest(request, strJason);

            //Get list from response
            if (responseContent != "")
            {
                NewDataset = responseContent.Split(',');
            }
            else
            {
                NewDataset = null;
            }

            request = null;

            return(true);
        }
Пример #14
0
        public void SaveToFile(String filename)
        {
            if (File.Exists(filename))
            {
                File.Delete(filename);
            }
            DeactivateHandle();
            JSONBuilder builder = new JSONBuilder();

            foreach (ButtonHandle bh in handles)
            {
                builder.addAction(bh.ToAction());
            }
            File.WriteAllText(filename, builder.toString);
        }
Пример #15
0
        public string pack()
        {
            JSONBuilder jb = new JSONBuilder();

            jb.beginItem();

            jb.addField("flavour");
            jb.addPrimitive(flavour.ToString());

            jb.addField("key");
            key.addToJSON(jb);

            if (flavour != Flavour.ECHO)
            {
                jb.addField("data");
                data.addToJSON(jb);
            }

            jb.endItem();

            return(jb.ToString());
        }
Пример #16
0
        public bool Run()
        {
            // Cursor and Keyframes
            // too - move to unit tests
            //ArmCursor ac = new ArmCursor(Vector3.UnitX, Quaternion.Identity);
            //KeyFrame kf = new KeyFrame(ac, (float)Math.PI);
            //JSONBuilder jkf = new JSONBuilder();
            //ComData cd1 = new ComData(kf);
            //cd1.addToJSON(jkf);
            //Console.WriteLine(jkf.ToString());

            //ComData cd1b = new ComData("");
            //cd1b.fillFromJSON(new JSONDecoder(jkf.ToString()));
            //KeyFrame kf2 = new KeyFrame();
            //Console.WriteLine(cd1b.TryParse(ref kf2));

            Angle[] a =
            {
                new Angle(0.1f),
                new Angle(0.2f),
                new Angle(0.3f),
                new Angle(0.4f)
            };
            JSONBuilder           ja = new JSONBuilder();
            JSONableArray <Angle> aa = new JSONableArray <Angle>(a, (str) => { return(new Angle(float.Parse(str))); });
            ComData cd2 = new ComData(aa);

            cd2.addToJSON(ja);
            Console.WriteLine(ja.ToString());

            ComData cd2b = new ComData("");

            cd2b.fillFromJSON(new JSONDecoder(ja.ToString()));
            JSONableArray <Angle> aa2 = new JSONableArray <Angle>((str) => { return(new Angle(float.Parse(str))); });

            Console.WriteLine(cd2b.TryParse(ref aa2));

            return(true);
        }
Пример #17
0
        /// <summary>
        /// convert data from an input file to a new format and output to a new file
        /// this function could be broken down into smaller functions
        /// i.e. getData, convertData, writeData functions
        /// </summary>
        /// <param name="inputFile"></param>
        /// <param name="outputFile"></param>
        /// <param name="convertTo"></param>
        static void ConvertData(string inputFile, string outputFile, string convertTo)
        {
            // initialise variables
            CSVService inputService = null;
            IService <string, string, string> outputService = null;
            IBuilder  builder   = null;
            Converter converter = null;

            // get data
            inputService = new CSVService(inputFile);
            var lines = inputService.GetAllData();

            // create builder and output services dependent on new format required
            switch (convertTo.ToLower())
            {
            case "xml":
                builder       = new XMLBuilder("root", "entity");
                outputService = new XMLService(outputFile);
                break;

            case "json":
                builder       = new JSONBuilder();
                outputService = new JSONService(outputFile);
                break;

            default:
                throw new ArgumentNullException("Invalid file format to convert to");
            }

            // do the conversion
            converter = new Converter(builder);
            var data = converter.ConvertCSV(lines.headings, lines.data);

            // write the new file
            outputService.WriteData(data);
            WriteLine($"Created {convertTo} file: {outputFile}");
        }
        private void ParseLog(object logFile)
        {
            UploadController up_controller = null;

            System.Globalization.CultureInfo before = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture =
                new System.Globalization.CultureInfo("en-US");
            GridRow row = new GridRow(logFile as string, "")
            {
                BgWorker = new System.ComponentModel.BackgroundWorker()
                {
                    WorkerReportsProgress = true
                }
            };

            row.Metadata.FromConsole = true;

            FileInfo fInfo = new FileInfo(row.Location);

            if (!fInfo.Exists)
            {
                throw new CancellationException(row, new FileNotFoundException("File does not exist", fInfo.FullName));
            }
            //Upload Process
            Task <string> DREITask   = null;
            Task <string> DRRHTask   = null;
            Task <string> RaidarTask = null;

            string[] uploadresult = new string[3] {
                "", "", ""
            };
            try
            {
                SettingsContainer settings = new SettingsContainer(Properties.Settings.Default);
                Parser            control  = new Parser(settings);

                if (fInfo.Extension.Equals(".evtc", StringComparison.OrdinalIgnoreCase) ||
                    fInfo.Name.EndsWith(".evtc.zip", StringComparison.OrdinalIgnoreCase))
                {
                    //Process evtc here
                    ParsedLog log = control.ParseLog(row, fInfo.FullName);
                    Console.Write("Log Parsed\n");
                    bool uploadAuthorized = !Properties.Settings.Default.SkipFailedTries || (Properties.Settings.Default.SkipFailedTries && log.LogData.Success);
                    if (Properties.Settings.Default.UploadToDPSReports && uploadAuthorized)
                    {
                        Console.Write("Uploading to DPSReports using EI\n");
                        if (up_controller == null)
                        {
                            up_controller = new UploadController();
                        }
                        DREITask = Task.Factory.StartNew(() => up_controller.UploadDPSReportsEI(fInfo));
                        if (DREITask != null)
                        {
                            while (!DREITask.IsCompleted)
                            {
                                System.Threading.Thread.Sleep(100);
                            }
                            uploadresult[0] = DREITask.Result;
                        }
                        else
                        {
                            uploadresult[0] = "Failed to Define Upload Task";
                        }
                    }
                    if (Properties.Settings.Default.UploadToDPSReportsRH && uploadAuthorized)
                    {
                        Console.Write("Uploading to DPSReports using RH\n");
                        if (up_controller == null)
                        {
                            up_controller = new UploadController();
                        }
                        DRRHTask = Task.Factory.StartNew(() => up_controller.UploadDPSReportsRH(fInfo));
                        if (DRRHTask != null)
                        {
                            while (!DRRHTask.IsCompleted)
                            {
                                System.Threading.Thread.Sleep(100);
                            }
                            uploadresult[1] = DRRHTask.Result;
                        }
                        else
                        {
                            uploadresult[1] = "Failed to Define Upload Task";
                        }
                    }
                    if (Properties.Settings.Default.UploadToRaidar && uploadAuthorized)
                    {
                        Console.Write("Uploading to Raidar\n");
                        if (up_controller == null)
                        {
                            up_controller = new UploadController();
                        }
                        RaidarTask = Task.Factory.StartNew(() => up_controller.UploadRaidar(fInfo));
                        if (RaidarTask != null)
                        {
                            while (!RaidarTask.IsCompleted)
                            {
                                System.Threading.Thread.Sleep(100);
                            }
                            uploadresult[2] = RaidarTask.Result;
                        }
                        else
                        {
                            uploadresult[2] = "Failed to Define Upload Task";
                        }
                    }
                    if (Properties.Settings.Default.SkipFailedTries)
                    {
                        if (!log.LogData.Success)
                        {
                            throw new SkipException();
                        }
                    }
                    //Creating File
                    //save location
                    DirectoryInfo saveDirectory;
                    if (Properties.Settings.Default.SaveAtOut || Properties.Settings.Default.OutLocation == null)
                    {
                        //Default save directory
                        saveDirectory = fInfo.Directory;
                    }
                    else
                    {
                        //Customised save directory
                        saveDirectory = new DirectoryInfo(Properties.Settings.Default.OutLocation);
                    }

                    if (saveDirectory == null)
                    {
                        throw new CancellationException(row, new InvalidDataException("Save Directory not found"));
                    }

                    string result = "fail";

                    if (log.LogData.Success)
                    {
                        result = "kill";
                    }

                    StatisticsCalculator          statisticsCalculator = new StatisticsCalculator(settings);
                    StatisticsCalculator.Switches switches             = new StatisticsCalculator.Switches();
                    if (Properties.Settings.Default.SaveOutHTML)
                    {
                        HTMLBuilder.UpdateStatisticSwitches(switches);
                    }
                    if (Properties.Settings.Default.SaveOutCSV)
                    {
                        CSVBuilder.UpdateStatisticSwitches(switches);
                    }
                    if (Properties.Settings.Default.SaveOutJSON)
                    {
                        JSONBuilder.UpdateStatisticSwitches(switches);
                    }
                    Statistics statistics = statisticsCalculator.CalculateStatistics(log, switches);
                    Console.Write("Statistics Computed\n");

                    string fName = fInfo.Name.Split('.')[0];
                    if (Properties.Settings.Default.SaveOutHTML)
                    {
                        string outputFile = Path.Combine(
                            saveDirectory.FullName,
                            $"{fName}_{log.FightData.Logic.Extension}_{result}.html"
                            );
                        using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                        {
                            using (StreamWriter sw = new StreamWriter(fs))
                            {
                                if (Properties.Settings.Default.NewHtmlMode)
                                {
                                    var builder = new HTMLBuilderNew(log, settings, statistics);
                                    builder.CreateHTML(sw, saveDirectory.FullName);
                                }
                                else
                                {
                                    var builder = new HTMLBuilder(log, settings, statistics, uploadresult);
                                    builder.CreateHTML(sw);
                                }
                            }
                        }
                    }
                    if (Properties.Settings.Default.SaveOutCSV)
                    {
                        string outputFile = Path.Combine(
                            saveDirectory.FullName,
                            $"{fName}_{log.FightData.Logic.Extension}_{result}.csv"
                            );
                        using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                        {
                            using (StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding(1252)))
                            {
                                var builder = new CSVBuilder(sw, ",", log, settings, statistics, uploadresult);
                                builder.CreateCSV();
                            }
                        }
                    }

                    if (Properties.Settings.Default.SaveOutJSON)
                    {
                        string outputFile = Path.Combine(
                            saveDirectory.FullName,
                            $"{fName}_{log.FightData.Logic.Extension}_{result}.json"
                            );
                        using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                        {
                            using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                            {
                                var builder = new JSONBuilder(sw, log, settings, statistics, false, uploadresult);
                                builder.CreateJSON();
                            }
                        }
                    }

                    Console.Write("Generation Done\n");
                }
                else
                {
                    Console.Error.Write("Not EVTC");
                    throw new CancellationException(row, new InvalidDataException("Not EVTC"));
                }
            }
            catch (SkipException s)
            {
                Console.Error.Write(s.Message);
            }
            catch (Exception ex) when(!System.Diagnostics.Debugger.IsAttached)
            {
                Console.Error.Write(ex.Message);
                throw new CancellationException(row, ex);
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = before;
            }
        }
Пример #19
0
 public void addToJSON(JSONBuilder jb)
 {
     jb.addPrimitive("Pos", Pos);
     jb.addPrimitive("Dir", Dir);
     jb.closeMe();
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            Master.HideAllFilters = true;
            if (RequestVars.Get("a", 0) == 1)
            {
                Response.Clear();
                switch (RequestVars.Get("t", 0))
                {
                case 1:                         //Remove
                    int propSurvReaID = RequestVars.Post("p", -1);
                    int userID        = RequestVars.Post("u", -1);
                    int sendType      = RequestVars.Post("s", -1);
                    if (propSurvReaID != -1 && userID != -1 && sendType != -1)
                    {
                        SQLDatabase sql  = new SQLDatabase();    sql.CommandTimeout = 120;
                        int         rows = sql.NonQuery(
                            @"DELETE FROM [tblNotificationUsers] WHERE [PropertySurveyReasonID] = @PropertySurveyReasonID AND [UserID] = @UserID AND [SendType] = @SendType",
                            new SQLParamList().Add("@PropertySurveyReasonID", propSurvReaID)
                            .Add("@UserID", userID)
                            .Add("@SendType", sendType)
                            );
                        if (!sql.HasError)
                        {
                            if (rows != 0)
                            {
                                Response.Write(new JSONBuilder().AddInt("s", 0));
                            }
                            else
                            {
                                Response.Write(new JSONBuilder().AddInt("s", 4).AddString("msg", "No matching records found. Refresh the page to see the most up to date information."));
                            }
                        }
                        else
                        {
                            Response.Write(new JSONBuilder().AddInt("s", 3).AddString("msg", "There was a problem contacting the database. Please try again. (ENM105)"));
                        }
                    }
                    else
                    {
                        Response.Write(new JSONBuilder().AddInt("s", 2).AddString("msg", "Invalid values specified."));
                    }
                    break;

                case 2:                         //Get user list
                    propSurvReaID = RequestVars.Get("p", -1);
                    if (propSurvReaID != -1)
                    {
                        SQLDatabase sql = new SQLDatabase();    sql.CommandTimeout = 120;
                        DataTable   dt  = sql.QueryDataTable(@"
SELECT [UserID],[FirstName],[LastName]
FROM [tblCOM_Users]
WHERE [UserID] NOT IN (SELECT [UserID] FROM [tblNotificationUsers] WHERE [PropertySurveyReasonID] = @PSRID )
	AND [Active] = 1
ORDER BY [FirstName], [LastName]",
                                                             new SqlParameter("@PSRID", propSurvReaID));

                        if (!sql.HasError)
                        {
                            JSONBuilder jb = new JSONBuilder().AddInt("s", 0);
                            jb.AddArray("ubh");
                            foreach (DataRow dr in dt.Rows)
                            {
                                jb.AddObject()
                                .AddInt("i", (int)dr["UserID"])
                                .AddString("n", dr["FirstName"].ToString() + " " + dr["LastName"].ToString())
                                .CloseObject();
                            }
                            jb.CloseArray();
                            Response.Write(jb);
                        }
                        else
                        {
                            Response.Write(new JSONBuilder().AddInt("s", 3).AddString("msg", "There was a problem contacting the database. Please try again. (ENM106)"));
                        }
                    }
                    else
                    {
                        Response.Write(new JSONBuilder().AddInt("s", 2).AddString("msg", "Invalid values specified."));
                    }
                    break;

                default:
                    Response.Write(new JSONBuilder().AddInt("s", 1).AddString("msg", "Invalid type specified."));
                    break;
                }
                Response.End();
                return;
            }

            if (!IsPostBack)
            {
                //Hide reason by default. Can only be shown if Property and Survey are changed.
                ddlReason.Visible = false;
            }
            else
            {
                lblReasonError.Text = String.Empty;
            }
        }
Пример #21
0
 public void addToJSON(JSONBuilder jb)
 {
     jb.addPrimitive("Key", value);
 }
Пример #22
0
        /// <summary>
        /// Invoked when a BackgroundWorker begins working.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BgWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            System.Globalization.CultureInfo before = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture =
                new System.Globalization.CultureInfo("en-US");
            BackgroundWorker bg            = sender as BackgroundWorker;
            GridRow          rowData       = e.Argument as GridRow;
            UploadController up_controller = null;

            e.Result = rowData;

            bg.ThrowIfCanceled(rowData);

            try
            {
                FileInfo fInfo = new FileInfo(rowData.Location);
                if (fInfo == null || !fInfo.Exists)
                {
                    bg.UpdateProgress(rowData, "File does not exist", 100);
                    e.Cancel = true;
                    throw new CancellationException(rowData);
                }
                //Upload Process
                Task <string> DREITask     = null;
                Task <string> DRRHTask     = null;
                Task <string> RaidarTask   = null;
                string[]      uploadresult = new string[3] {
                    "", "", ""
                };
                bg.UpdateProgress(rowData, " Working...", 0);

                SettingsContainer settings = new SettingsContainer(Properties.Settings.Default);
                Parser            parser   = new Parser(settings);

                if (fInfo.Extension.Equals(".evtc", StringComparison.OrdinalIgnoreCase) ||
                    fInfo.Name.EndsWith(".evtc.zip", StringComparison.OrdinalIgnoreCase))
                {
                    //Process evtc here
                    bg.UpdateProgress(rowData, "10% - Reading Binary...", 10);
                    ParsedLog log = parser.ParseLog(rowData, fInfo.FullName);
                    bg.ThrowIfCanceled(rowData);
                    bg.UpdateProgress(rowData, "35% - Data parsed", 35);
                    bool uploadAuthorized = !Properties.Settings.Default.SkipFailedTries || (Properties.Settings.Default.SkipFailedTries && log.LogData.Success);
                    if (Properties.Settings.Default.UploadToDPSReports && uploadAuthorized)
                    {
                        bg.UpdateProgress(rowData, " 40% - Uploading to DPSReports using EI...", 40);
                        if (up_controller == null)
                        {
                            up_controller = new UploadController();
                        }
                        DREITask = Task.Factory.StartNew(() => up_controller.UploadDPSReportsEI(fInfo));
                        if (DREITask != null)
                        {
                            while (!DREITask.IsCompleted)
                            {
                                System.Threading.Thread.Sleep(100);
                            }
                            uploadresult[0] = DREITask.Result;
                        }
                        else
                        {
                            uploadresult[0] = "Failed to Define Upload Task";
                        }
                    }
                    if (Properties.Settings.Default.UploadToDPSReportsRH && uploadAuthorized)
                    {
                        bg.UpdateProgress(rowData, " 40% - Uploading to DPSReports using RH...", 40);
                        if (up_controller == null)
                        {
                            up_controller = new UploadController();
                        }
                        DRRHTask = Task.Factory.StartNew(() => up_controller.UploadDPSReportsRH(fInfo));
                        if (DRRHTask != null)
                        {
                            while (!DRRHTask.IsCompleted)
                            {
                                System.Threading.Thread.Sleep(100);
                            }
                            uploadresult[1] = DRRHTask.Result;
                        }
                        else
                        {
                            uploadresult[1] = "Failed to Define Upload Task";
                        }
                    }
                    if (Properties.Settings.Default.UploadToRaidar && uploadAuthorized)
                    {
                        bg.UpdateProgress(rowData, " 40% - Uploading to Raidar...", 40);
                        if (up_controller == null)
                        {
                            up_controller = new UploadController();
                        }
                        RaidarTask = Task.Factory.StartNew(() => up_controller.UploadRaidar(fInfo));
                        if (RaidarTask != null)
                        {
                            while (!RaidarTask.IsCompleted)
                            {
                                System.Threading.Thread.Sleep(100);
                            }
                            uploadresult[2] = RaidarTask.Result;
                        }
                        else
                        {
                            uploadresult[2] = "Failed to Define Upload Task";
                        }
                    }
                    if (Properties.Settings.Default.SkipFailedTries)
                    {
                        if (!log.LogData.Success)
                        {
                            throw new SkipException();
                        }
                    }
                    //Creating File
                    //save location
                    DirectoryInfo saveDirectory;
                    if (Properties.Settings.Default.SaveAtOut || Properties.Settings.Default.OutLocation == null)
                    {
                        //Default save directory
                        saveDirectory = fInfo.Directory;
                    }
                    else
                    {
                        //Customised save directory
                        saveDirectory = new DirectoryInfo(Properties.Settings.Default.OutLocation);
                    }
                    if (saveDirectory == null)
                    {
                        throw new CancellationException(rowData, new Exception("Invalid save directory"));
                    }
                    string result = log.LogData.Success ? "kill" : "fail";

                    StatisticsCalculator          statisticsCalculator = new StatisticsCalculator(settings);
                    StatisticsCalculator.Switches switches             = new StatisticsCalculator.Switches();
                    if (Properties.Settings.Default.SaveOutHTML)
                    {
                        HTMLBuilder.UpdateStatisticSwitches(switches);
                    }
                    if (Properties.Settings.Default.SaveOutCSV)
                    {
                        CSVBuilder.UpdateStatisticSwitches(switches);
                    }
                    if (Properties.Settings.Default.SaveOutJSON)
                    {
                        JSONBuilder.UpdateStatisticSwitches(switches);
                    }
                    Statistics statistics = statisticsCalculator.CalculateStatistics(log, switches);
                    bg.UpdateProgress(rowData, "85% - Statistics computed", 85);
                    string fName = fInfo.Name.Split('.')[0];
                    bg.UpdateProgress(rowData, "90% - Creating File...", 90);
                    if (Properties.Settings.Default.SaveOutHTML)
                    {
                        string outputFile = Path.Combine(
                            saveDirectory.FullName,
                            $"{fName}_{log.FightData.Logic.Extension}_{result}.html"
                            );
                        rowData.LogLocation = outputFile;
                        using (var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                            using (var sw = new StreamWriter(fs))
                            {
                                if (Properties.Settings.Default.NewHtmlMode)
                                {
                                    var builder = new HTMLBuilderNew(log, settings, statistics);
                                    builder.CreateHTML(sw, saveDirectory.FullName);
                                }
                                else
                                {
                                    var builder = new HTMLBuilder(log, settings, statistics, uploadresult);
                                    builder.CreateHTML(sw);
                                }
                            }
                    }
                    if (Properties.Settings.Default.SaveOutCSV)
                    {
                        string outputFile = Path.Combine(
                            saveDirectory.FullName,
                            $"{fName}_{log.FightData.Logic.Extension}_{result}.csv"
                            );
                        string splitString = "";
                        if (rowData.LogLocation != null)
                        {
                            splitString = ",";
                        }
                        rowData.LogLocation += splitString + outputFile;
                        using (var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                            using (var sw = new StreamWriter(fs, Encoding.GetEncoding(1252)))
                            {
                                var builder = new CSVBuilder(sw, ",", log, settings, statistics, uploadresult);
                                builder.CreateCSV();
                            }
                    }
                    if (Properties.Settings.Default.SaveOutJSON)
                    {
                        string outputFile = Path.Combine(
                            saveDirectory.FullName,
                            $"{fName}_{log.FightData.Logic.Extension}_{result}.json"
                            );
                        string splitString = "";
                        if (rowData.LogLocation != null)
                        {
                            splitString = ",";
                        }
                        rowData.LogLocation += splitString + outputFile;
                        using (var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                            using (var sw = new StreamWriter(fs, Encoding.UTF8))
                            {
                                var builder = new JSONBuilder(sw, log, settings, statistics, false, uploadresult);
                                builder.CreateJSON();
                            }
                    }

                    bg.UpdateProgress(rowData, $"100% - Complete_{log.FightData.Logic.Extension}_{result}", 100);
                }
                else
                {
                    bg.UpdateProgress(rowData, "Not EVTC", 100);
                    e.Cancel = true;
                    Console.Error.Write("Not EVTC");
                    throw new CancellationException(rowData);
                }
            }
            catch (SkipException s)
            {
                Console.Write(s.Message);
                throw new CancellationException(rowData, s);
            }
            catch (Exception ex) when(!System.Diagnostics.Debugger.IsAttached)
            {
                Console.Error.Write(ex.Message);
                throw new CancellationException(rowData, ex);
            }
            finally
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = before;
            }
        }
Пример #23
0
 public void addToJSON(JSONBuilder jb)
 {
     jb.addPrimitive("Vec", vec);
     jb.addPrimitive("Mag", mag);
     jb.closeMe();
 }
Пример #24
0
 public void addToJSON(JSONBuilder jb)
 {
     jb.addObject("ArmCursor", Cursor);
     jb.addPrimitive("Time", Time);
     jb.closeMe();
 }