public void Example()
        {
            #region Usage
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;

                writer.WriteStartObject();
                writer.WritePropertyName("CPU");
                writer.WriteValue("Intel");
                writer.WritePropertyName("PSU");
                writer.WriteValue("500W");
                writer.WritePropertyName("Drives");
                writer.WriteStartArray();
                writer.WriteValue("DVD read/writer");
                writer.WriteComment("(broken)");
                writer.WriteValue("500 gigabyte hard drive");
                writer.WriteValue("200 gigabype hard drive");
                writer.WriteEnd();
                writer.WriteEndObject();
            }

            Console.WriteLine(sb.ToString());
            // {
            //   "CPU": "Intel",
            //   "PSU": "500W",
            //   "Drives": [
            //     "DVD read/writer"
            //     /*(broken)*/,
            //     "500 gigabyte hard drive",
            //     "200 gigabype hard drive"
            //   ]
            // }
            #endregion

            Assert.AreEqual(@"{
  ""CPU"": ""Intel"",
  ""PSU"": ""500W"",
  ""Drives"": [
    ""DVD read/writer""
    /*(broken)*/,
    ""500 gigabyte hard drive"",
    ""200 gigabype hard drive""
  ]
}", sb.ToString());
        }
        public void ReadingAndWritingJsonText()
        {
            #region ReadingAndWritingJsonText
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;

                writer.WriteStartObject();
                writer.WritePropertyName("CPU");
                writer.WriteValue("Intel");
                writer.WritePropertyName("PSU");
                writer.WriteValue("500W");
                writer.WritePropertyName("Drives");
                writer.WriteStartArray();
                writer.WriteValue("DVD read/writer");
                writer.WriteComment("(broken)");
                writer.WriteValue("500 gigabyte hard drive");
                writer.WriteValue("200 gigabype hard drive");
                writer.WriteEnd();
                writer.WriteEndObject();
            }

            // {
            //   "CPU": "Intel",
            //   "PSU": "500W",
            //   "Drives": [
            //     "DVD read/writer"
            //     /*(broken)*/,
            //     "500 gigabyte hard drive",
            //     "200 gigabype hard drive"
            //   ]
            // }
            #endregion
        }
        private void WriteJSON()
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;
                writer.WriteStartObject();

                writer.WritePropertyName("Server Directory");
                writer.WriteValue(serverDirectory);

                writer.WritePropertyName("Server Config Directory");
                writer.WriteValue(serverConfigDirectory);

                writer.WritePropertyName("Restart Enabled");
                writer.WriteValue(RestartInformation.Enabled);

                writer.WritePropertyName("SQL Backup");
                writer.WriteStartArray();
                writer.WriteValue(SQLBackup.Enabled);
                writer.WriteValue(SQLBackup.DumpDirectory);
                writer.WriteValue(SQLBackup.DatabaseName);
                writer.WriteValue(SQLBackup.Host);
                writer.WriteValue(SQLBackup.User);
                writer.WriteValue(SQLBackup.Password);
                writer.WriteValue(SQLBackup.BackupDirectory);
                writer.WriteValue(SQLBackup.BackupTimer);
                writer.WriteEnd();

                int count = 0;

                foreach (RestartData data in RestartInformation.Data)
                {
                    writer.WritePropertyName("Schedule Data " + count);
                    writer.WriteStartArray();
                    writer.WriteValue(data.RestartHour);
                    writer.WriteValue(data.RestartMinute);
                    writer.WriteValue(data.RestartType);
                    writer.WriteValue(data.MinuteWarning);
                    writer.WriteEnd();

                    count++;
                }

                count = 0;

                foreach (NodeCMD data in NodeCMDInformation.Data)
                {
                    writer.WritePropertyName("NodeCMD " + count);
                    writer.WriteStartArray();
                    writer.WriteValue(data.Directory);
                    writer.WriteValue(data.Arguments);
                    writer.WriteValue(data.Enabled);
                    writer.WriteEnd();

                    count++;
                }

                writer.WriteEndObject();
            }

            File.WriteAllText(jsonPath, sb.ToString());
        }
 public override void WriteEndDocument()
 {
     _writer.WriteEnd();
 }
Beispiel #5
0
        public void Run()
        {
            Regex typeRegex = new Regex("_\\d{4}");

            Console.WriteLine("Loading cff files...");
            foreach (var t in Assembly.GetExecutingAssembly().GetTypes())
            {
                if (t.Name.Length != 5)
                {
                    continue;
                }

                if (!typeRegex.IsMatch(t.Name))
                {
                    continue;
                }

                int id = Convert.ToInt32(t.Name.Substring(1, 4));

                using (Stream s = File.OpenRead(Path.Combine("cff", id.ToString().PadLeft(4, '0'))))
                    using (BinaryReader reader = new BinaryReader(s))
                    {
                        try
                        {
                            object o = reader.ReadStructure(t);
                            m_cffObjects.Add(id, o);
                            Console.WriteLine("Cff {0} loaded.", id);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Cff {0} failed to process: {1}.", id, e.Message);
                        }
                    }
            }

            Console.WriteLine("Creating HttpListener on 8080...");

            m_listener = new HttpListener();
            m_listener.Prefixes.Add("http://+:8080/");

            m_listener.Start();

            Console.WriteLine("Waiting for request...");
            Regex idRegex = new Regex("\\d{4}");

            while (true)
            {
                HttpListenerContext context = null;

                try
                {
                    context = m_listener.GetContext();
                    var request  = context.Request;
                    var response = context.Response;

                    string url = request.RawUrl.ToLower();

                    int index = url.IndexOf('?');
                    if (index > 0)
                    {
                        url = url.Substring(0, index);
                    }

                    url = Path.GetInvalidFileNameChars().Aggregate(url, (current, c) => current.Replace(new string(c, 1), ""));

                    if (url == "")
                    {
                        url = "index.html";
                    }

                    Console.WriteLine("Received request '{2}' from {0}:{1}.", request.RemoteEndPoint.Address, request.RemoteEndPoint.Port, url);

                    if (url.StartsWith("data") && idRegex.IsMatch(url))
                    {
                        int id = Convert.ToInt32(url.Substring(4, 4));
                        var o  = m_cffObjects[id];
                        var t  = o.GetType();

                        var entryFieldType = t.GetFields()[0];
                        var entryArray     = (Array)entryFieldType.GetValue(o);

                        StringBuilder builder = new StringBuilder(40960);
                        StringWriter  sw      = new StringWriter(builder);

                        using (JsonWriter writer = new JsonTextWriter(sw))
                        {
                            writer.WriteStartObject();

                            writer.WritePropertyName("draw");
                            writer.WriteValue(++m_drawGenerator);

                            writer.WritePropertyName("recordsTotal");
                            writer.WriteValue(entryArray.Length);

                            string search = request.QueryString["search[value]"];

                            List <object> entries = new List <object>(entryArray.Length);
                            for (int i = 0; i < entryArray.Length; i++)
                            {
                                if (FieldContains(search, entryArray.GetValue(i)))
                                {
                                    entries.Add(entryArray.GetValue(i));
                                }
                            }

                            writer.WritePropertyName("recordsFiltered");
                            writer.WriteValue(entries.Count);

                            writer.WritePropertyName("data");
                            writer.WriteStartArray();

                            int length = Convert.ToInt32(request.QueryString["length"]);
                            int start  = Convert.ToInt32(request.QueryString["start"]);
                            if (start < 0)
                            {
                                start = 0;
                            }

                            int end = start + length;
                            if (end > entries.Count)
                            {
                                end = entries.Count;
                            }

                            for (int i = start; i < end; i++)
                            {
                                writer.WriteStartArray();

                                var oa = entries[i];

                                foreach (var field in oa.GetType().GetFields())
                                {
                                    if (field.FieldType.Name.EndsWith("Container"))
                                    {
                                        var oc = field.GetValue(oa);

                                        foreach (var e in field.FieldType.GetFields())
                                        {
                                            var so = e.GetValue(oc);
                                            writer.WriteValue(GetValue(so));
                                        }

                                        continue;
                                    }

                                    writer.WriteValue(GetValue(field.GetValue(oa)));
                                }

                                writer.WriteEnd();
                            }

                            writer.WriteEnd();
                            writer.WriteEndObject();
                        }

                        byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
                        response.ContentType     = "application/json";
                        response.ContentLength64 = data.Length;
                        response.OutputStream.Write(data, 0, data.Length);
                    }
                    else if (idRegex.IsMatch(url))
                    {
                        int id = Convert.ToInt32(url);
                        var o  = m_cffObjects[id];
                        var t  = o.GetType();

                        var entryFieldType = t.GetFields()[0];
                        var entryArray     = (Array)entryFieldType.GetValue(o);

                        StringBuilder builder = new StringBuilder(4096);

                        foreach (var field in entryArray.GetType().GetElementType().GetFields())
                        {
                            var f = field;
                            if (f.FieldType.Name.EndsWith("Container"))
                            {
                                foreach (var e in f.FieldType.GetFields())
                                {
                                    builder.AppendFormat("<th>{0}</th>", e.Name);
                                }

                                continue;
                            }

                            builder.AppendFormat("<th>{0}</th>", f.Name);
                        }

                        string tableHeader = builder.ToString();

                        StringBuilder hrefBuilder = new StringBuilder(8096);

                        foreach (var cff in m_cffObjects.Keys)
                        {
                            hrefBuilder.Append(String.Format("<a href=\"{0}\">{0}</a> ", cff));
                        }

                        string templateHtml = "<head><link rel=\"stylesheet\" type=\"text/css\" href=\"jquery.dataTables.min.css\"><script type=\"text/javascript\" src=\"jquery.js\"></script><script type=\"text/javascript\" src=\"jquery.dataTables.js\"></script><script type=\"text/javascript\">$(document).ready(function() {$('#example').DataTable({\"processing\": true,\"serverSide\": true,\"ajax\": \"data{id}\"});});</script></head><body><div>{cffFiles}</div><div><table id=\"example\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr>{tableHeader}</tr></thead><tfoot><tr>{tableHeader}</tr></tfoot></table></div></body>";
                        string html         = templateHtml.Replace("{tableHeader}", tableHeader);
                        html = html.Replace("{id}", id.ToString());
                        html = html.Replace("{cffFiles}", hrefBuilder.ToString());

                        byte[] data = Encoding.UTF8.GetBytes(html);
                        response.ContentType     = "text/html";
                        response.ContentLength64 = data.Length;
                        response.OutputStream.Write(data, 0, data.Length);
                    }
                    else
                    {
                        switch (url)
                        {
                        default:
                        {
                            string extension = Path.GetExtension(url);
                            response.ContentType = MimeTypeMap.GetMimeType(extension);

                            byte[] data = File.ReadAllBytes(Path.Combine("data", url));
                            response.ContentLength64 = data.Length;
                            response.OutputStream.Write(data, 0, data.Length);
                            break;
                        }
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception failed to process request: '{0}'.", e.Message);
                }
                finally
                {
                    if (context != null)
                    {
                        context.Response.OutputStream.Close();
                    }
                }
            }
        }
Beispiel #6
0
        private void PopulateControls()
        {
            string featuredImageUrl = string.Empty;
            string markupTop        = string.Empty;
            string markupBottom     = string.Empty;

            featuredImageUrl = String.IsNullOrWhiteSpace(config.InstanceFeaturedImage) ? featuredImageUrl : WebUtils.GetRelativeSiteRoot() + config.InstanceFeaturedImage;
            markupTop        = displaySettings.ModuleInstanceMarkupTop;
            markupBottom     = displaySettings.ModuleInstanceMarkupBottom;

            strOutput.Append(markupTop);

            if (config.UseHeader && config.HeaderLocation == "InnerBodyPanel" && !String.IsNullOrWhiteSpace(config.HeaderContent) && !String.Equals(config.HeaderContent, "<p>&nbsp;</p>"))
            {
                try
                {
                    strOutput.Append(string.Format(displaySettings.HeaderContentFormat, config.HeaderContent));
                }
                catch (FormatException ex)
                {
                    log.ErrorFormat(markupErrorFormat, "HeaderContentFormat", moduleTitle, ex);
                }
            }
            StringBuilder  jsonString   = new StringBuilder();
            StringWriter   stringWriter = new StringWriter(jsonString);
            JsonTextWriter jsonWriter   = new JsonTextWriter(stringWriter);

            // http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateTimeZoneHandling.htm
            jsonWriter.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            // http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateFormatHandling.htm
            jsonWriter.DateFormatHandling = DateFormatHandling.IsoDateFormat;

            string jsonObjName = "sflexi" + module.ModuleId.ToString() + (config.IsGlobalView ? "Modules" : "Items");

            if (config.RenderJSONOfData)
            {
                jsonWriter.WriteRaw("var " + jsonObjName + " = ");
                if (config.JsonLabelObjects || config.IsGlobalView)
                {
                    jsonWriter.WriteStartObject();
                }
                else
                {
                    jsonWriter.WriteStartArray();
                }
            }

            List <IndexedStringBuilder> itemsMarkup = new List <IndexedStringBuilder>();
            //List<Item> categorizedItems = new List<Item>();
            bool usingGlobalViewMarkup = !String.IsNullOrWhiteSpace(displaySettings.GlobalViewMarkup);
            int  currentModuleID       = -1;

            foreach (Item item in items)
            {
                bool itemIsEditable = isEditable || WebUser.IsInRoles(item.EditRoles);
                bool itemIsViewable = WebUser.IsInRoles(item.ViewRoles) || itemIsEditable;
                if (!itemIsViewable)
                {
                    continue;
                }

                //int itemCount = 0;
                //StringBuilder content = new StringBuilder();
                IndexedStringBuilder content = new IndexedStringBuilder();

                ModuleConfiguration itemModuleConfig = new ModuleConfiguration(module);
                item.ModuleFriendlyName = itemModuleConfig.ModuleFriendlyName;
                if (String.IsNullOrWhiteSpace(itemModuleConfig.ModuleFriendlyName))
                {
                    Module itemModule = new Module(item.ModuleGuid);
                    if (itemModule != null)
                    {
                        item.ModuleFriendlyName = itemModule.ModuleTitle;
                    }
                }

                if (config.IsGlobalView)
                {
                    content.SortOrder1 = itemModuleConfig.GlobalViewSortOrder;
                    content.SortOrder2 = item.SortOrder;
                }
                else
                {
                    content.SortOrder1 = item.SortOrder;
                }


                List <ItemFieldValue> fieldValues = ItemFieldValue.GetItemValues(item.ItemGuid);

                //using item.ModuleID here because if we are using a 'global view' we need to be sure the item edit link uses the correct module id.
                string itemEditUrl  = WebUtils.GetSiteRoot() + "/SuperFlexi/Edit.aspx?pageid=" + pageId + "&mid=" + item.ModuleID + "&itemid=" + item.ItemID;
                string itemEditLink = itemIsEditable ? String.Format(displaySettings.ItemEditLinkFormat, itemEditUrl) : string.Empty;

                if (config.RenderJSONOfData)
                {
                    if (config.IsGlobalView)
                    {
                        if (currentModuleID != item.ModuleID)
                        {
                            if (currentModuleID != -1)
                            {
                                jsonWriter.WriteEndObject();
                                jsonWriter.WriteEndObject();
                            }

                            currentModuleID = item.ModuleID;

                            //always label objects in globalview
                            jsonWriter.WritePropertyName("m" + currentModuleID.ToString());
                            jsonWriter.WriteStartObject();
                            jsonWriter.WritePropertyName("Module");
                            jsonWriter.WriteValue(item.ModuleFriendlyName);
                            jsonWriter.WritePropertyName("Items");
                            jsonWriter.WriteStartObject();
                        }
                    }
                    if (config.JsonLabelObjects || config.IsGlobalView)
                    {
                        jsonWriter.WritePropertyName("i" + item.ItemID.ToString());
                    }
                    jsonWriter.WriteStartObject();
                    jsonWriter.WritePropertyName("ItemId");
                    jsonWriter.WriteValue(item.ItemID.ToString());
                    jsonWriter.WritePropertyName("SortOrder");
                    jsonWriter.WriteValue(item.SortOrder.ToString());
                    if (IsEditable)
                    {
                        jsonWriter.WritePropertyName("EditUrl");
                        jsonWriter.WriteValue(itemEditUrl);
                    }
                }
                content.Append(displaySettings.ItemMarkup);

                foreach (Field field in fields)
                {
                    if (String.IsNullOrWhiteSpace(field.Token))
                    {
                        field.Token = "$_NONE_$";                                         //just in case someone has loaded the database with fields without using a source file.
                    }
                    bool fieldValueFound = false;

                    foreach (ItemFieldValue fieldValue in fieldValues)
                    {
                        if (field.FieldGuid == fieldValue.FieldGuid)
                        {
                            fieldValueFound = true;

                            if (String.IsNullOrWhiteSpace(fieldValue.FieldValue) ||
                                fieldValue.FieldValue.StartsWith("&deleted&") ||
                                fieldValue.FieldValue.StartsWith("&amp;deleted&amp;") ||
                                fieldValue.FieldValue.StartsWith("<p>&deleted&</p>") ||
                                fieldValue.FieldValue.StartsWith("<p>&amp;deleted&amp;</p>"))
                            {
                                content.Replace("^" + field.Token + "^", string.Empty);
                                content.Replace("^" + field.Token, string.Empty);
                                content.Replace(field.Token + "^", string.Empty);
                                content.Replace(field.Token, string.Empty);
                            }
                            else
                            {
                                if (IsDateField(field))
                                {
                                    DateTime dateTime = new DateTime();
                                    if (DateTime.TryParse(fieldValue.FieldValue, out dateTime))
                                    {
                                        /// ^field.Token is used when we don't want the preTokenString and postTokenString to be used
                                        content.Replace("^" + field.Token + "^", dateTime.ToString(field.DateFormat));
                                        content.Replace("^" + field.Token, dateTime.ToString(field.DateFormat) + field.PostTokenString);
                                        content.Replace(field.Token + "^", field.PreTokenString + dateTime.ToString(field.DateFormat));
                                        content.Replace(field.Token, field.PreTokenString + dateTime.ToString(field.DateFormat) + field.PostTokenString);
                                    }
                                }

                                if (IsCheckBoxListField(field) || IsRadioButtonListField(field))
                                {
                                    foreach (CheckBoxListMarkup cblm in config.CheckBoxListMarkups)
                                    {
                                        if (cblm.Field == field.Name)
                                        {
                                            StringBuilder cblmContent = new StringBuilder();

                                            List <string> values = fieldValue.FieldValue.SplitOnCharAndTrim(';');
                                            if (values.Count > 0)
                                            {
                                                foreach (string value in values)
                                                {
                                                    //why did we use _ValueItemID_ here instead of _ItemID_?
                                                    cblmContent.Append(cblm.Markup.Replace(field.Token, value).Replace("$_ValueItemID_$", item.ItemID.ToString()) + cblm.Separator);
                                                    cblm.SelectedValues.Add(new CheckBoxListMarkup.SelectedValue {
                                                        Value = value, ItemID = item.ItemID
                                                    });
                                                    //cblm.SelectedValues.Add(fieldValue);
                                                }
                                            }
                                            cblmContent.Length -= cblm.Separator.Length;
                                            content.Replace(cblm.Token, cblmContent.ToString());
                                        }
                                    }
                                }
                                //else
                                //{
                                /// ^field.Token is used when we don't want the preTokenString and postTokenString to be used


                                content.Replace("^" + field.Token + "^", fieldValue.FieldValue);
                                content.Replace("^" + field.Token, fieldValue.FieldValue + field.PostTokenString);
                                content.Replace(field.Token + "^", field.PreTokenString + fieldValue.FieldValue);
                                content.Replace(field.Token, field.PreTokenString + fieldValue.FieldValue + field.PostTokenString);
                                //}
                            }
                            //if (!String.IsNullOrWhiteSpace(field.LinkedField))
                            //{
                            //    Field linkedField = fields.Find(delegate(Field f) { return f.Name == field.LinkedField; });
                            //    if (linkedField != null)
                            //    {
                            //        ItemFieldValue linkedValue = fieldValues.Find(delegate(ItemFieldValue fv) { return fv.FieldGuid == linkedField.FieldGuid; });
                            //        content.Replace(linkedField.Token, linkedValue.FieldValue);
                            //    }
                            //}

                            if (config.RenderJSONOfData)
                            {
                                jsonWriter.WritePropertyName(field.Name);
                                //if (IsDateField(field))
                                //{
                                //    DateTime dateTime = new DateTime();
                                //    if (DateTime.TryParse(fieldValue.FieldValue, out dateTime))
                                //    {
                                //        jsonWriter.WriteValue(dateTime);
                                //    }

                                //}
                                //else
                                //{
                                jsonWriter.WriteValue(fieldValue.FieldValue);
                                //}
                            }
                        }
                    }

                    if (!fieldValueFound)
                    {
                        content.Replace(field.Token, field.DefaultValue);
                    }
                }

                if (config.RenderJSONOfData)
                {
                    //if (config.IsGlobalView)
                    //{
                    //    jsonWriter.WriteEndObject();
                    //}
                    jsonWriter.WriteEndObject();
                }

                content.Replace("$_EditLink_$", itemEditLink);
                content.Replace("$_ItemID_$", item.ItemID.ToString());
                content.Replace("$_SortOrder_$", item.SortOrder.ToString());

                if (!String.IsNullOrWhiteSpace(content))
                {
                    itemsMarkup.Add(content);
                }
            }
            if (config.DescendingSort)
            {
                itemsMarkup.Sort(delegate(IndexedStringBuilder a, IndexedStringBuilder b)
                {
                    int xdiff = b.SortOrder1.CompareTo(a.SortOrder1);
                    if (xdiff != 0)
                    {
                        return(xdiff);
                    }
                    else
                    {
                        return(b.SortOrder2.CompareTo(a.SortOrder2));
                    }
                });
            }
            else
            {
                itemsMarkup.Sort(delegate(IndexedStringBuilder a, IndexedStringBuilder b)
                {
                    int xdiff = a.SortOrder1.CompareTo(b.SortOrder1);
                    if (xdiff != 0)
                    {
                        return(xdiff);
                    }
                    else
                    {
                        return(a.SortOrder2.CompareTo(b.SortOrder2));
                    }
                });
            }
            StringBuilder allItems = new StringBuilder();

            if (displaySettings.ItemsPerGroup == -1)
            {
                foreach (IndexedStringBuilder sb in itemsMarkup)
                {
                    //allItems.Append(displaySettings.GlobalViewModuleGroupMarkup.Replace("$_ModuleGroupName_$", sb.GroupName));
                    allItems.Append(sb.ToString());
                }
                if (usingGlobalViewMarkup)
                {
                    strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, displaySettings.GlobalViewMarkup.Replace("$_ModuleGroups_$", allItems.ToString()));
                }
                else
                {
                    strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, allItems.ToString());
                }
            }
            else
            {
                int itemIndex = 0;

                decimal totalGroupCount = Math.Ceiling(itemsMarkup.Count / Convert.ToDecimal(displaySettings.ItemsPerGroup));

                if (totalGroupCount < 1 && itemsMarkup.Count > 0)
                {
                    totalGroupCount = 1;
                }

                int currentGroup            = 1;
                List <StringBuilder> groups = new List <StringBuilder>();
                while (currentGroup <= totalGroupCount && itemIndex < itemsMarkup.Count)
                {
                    StringBuilder group = new StringBuilder();
                    group.Append(displaySettings.ItemsRepeaterMarkup);
                    //group.SortOrder1 = itemsMarkup[itemIndex].SortOrder1;
                    //group.SortOrder2 = itemsMarkup[itemIndex].SortOrder2;
                    //group.GroupName = itemsMarkup[itemIndex].GroupName;
                    for (int i = 0; i < displaySettings.ItemsPerGroup; i++)
                    {
                        if (itemIndex < itemsMarkup.Count)
                        {
                            group.Replace("$_Items[" + i.ToString() + "]_$", itemsMarkup[itemIndex].ToString());
                            itemIndex++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    groups.Add(group);
                    currentGroup++;
                }

                //groups.Sort(delegate (IndexedStringBuilder a, IndexedStringBuilder b) {
                //    int xdiff = a.SortOrder1.CompareTo(b.SortOrder1);
                //    if (xdiff != 0) return xdiff;
                //    else return a.SortOrder2.CompareTo(b.SortOrder2);
                //});

                foreach (StringBuilder group in groups)
                {
                    allItems.Append(group.ToString());
                }

                strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, Regex.Replace(allItems.ToString(), @"(\$_Items\[[0-9]+\]_\$)", string.Empty, RegexOptions.Multiline));
            }



            //strOutput.Append(displaySettings.ItemListMarkupBottom);
            if (config.RenderJSONOfData)
            {
                if (config.JsonLabelObjects || config.IsGlobalView)
                {
                    jsonWriter.WriteEndObject();

                    if (config.IsGlobalView)
                    {
                        jsonWriter.WriteEndObject();
                        jsonWriter.WriteEnd();
                    }
                }
                else
                {
                    jsonWriter.WriteEndArray();
                }

                MarkupScript jsonScript = new MarkupScript();

                jsonWriter.Close();
                stringWriter.Close();

                jsonScript.RawScript  = stringWriter.ToString();
                jsonScript.Position   = config.JsonRenderLocation;
                jsonScript.ScriptName = "sflexi" + module.ModuleId.ToString() + config.MarkupDefinitionName.ToCleanFileName() + "-JSON";

                List <MarkupScript> scripts = new List <MarkupScript>();
                scripts.Add(jsonScript);

                SuperFlexiHelpers.SetupScripts(scripts, config, displaySettings, IsEditable, IsPostBack, ClientID, ModuleId, PageId, Page, this);
            }

            if (config.UseFooter && config.FooterLocation == "InnerBodyPanel" && !String.IsNullOrWhiteSpace(config.FooterContent) && !String.Equals(config.FooterContent, "<p>&nbsp;</p>"))
            {
                try
                {
                    strOutput.AppendFormat(displaySettings.FooterContentFormat, config.FooterContent);
                }
                catch (System.FormatException ex)
                {
                    log.ErrorFormat(markupErrorFormat, "FooterContentFormat", moduleTitle, ex);
                }
            }

            strOutput.Append(markupBottom);

            SuperFlexiHelpers.ReplaceStaticTokens(strOutput, config, isEditable, displaySettings, module.ModuleId, pageSettings, siteSettings, out strOutput);

            //this is for displaying all of the selected values from the items outside of the items themselves
            foreach (CheckBoxListMarkup cblm in config.CheckBoxListMarkups)
            {
                StringBuilder cblmContent = new StringBuilder();

                if (fields.Count > 0 && cblm.SelectedValues.Count > 0)
                {
                    Field theField = fields.Where(field => field.Name == cblm.Field).Single();
                    if (theField != null)
                    {
                        List <CheckBoxListMarkup.SelectedValue> distinctSelectedValues = new List <CheckBoxListMarkup.SelectedValue>();
                        foreach (CheckBoxListMarkup.SelectedValue selectedValue in cblm.SelectedValues)
                        {
                            CheckBoxListMarkup.SelectedValue match = distinctSelectedValues.Find(i => i.Value == selectedValue.Value);
                            if (match == null)
                            {
                                distinctSelectedValues.Add(selectedValue);
                            }
                            else
                            {
                                match.Count++;
                            }
                        }
                        //var selectedValues = cblm.SelectedValues.GroupBy(selectedValue => selectedValue.Value)
                        //    .Select(distinctSelectedValue => new { Value = distinctSelectedValue.Key, Count = distinctSelectedValue.Count(), ItemID = distinctSelectedValue.ItemID })
                        //    .OrderBy(x => x.Value);
                        foreach (CheckBoxListMarkup.SelectedValue value in distinctSelectedValues)
                        {
                            cblmContent.Append(cblm.Markup.Replace(theField.Token, value.Value).Replace("$_ValueItemID_$", value.ItemID.ToString()) + cblm.Separator);
                            cblmContent.Replace("$_CBLValueCount_$", value.Count.ToString());
                        }
                    }

                    if (cblmContent.Length >= cblm.Separator.Length)
                    {
                        cblmContent.Length -= cblm.Separator.Length;
                    }

                    strOutput.Replace(cblm.Token, cblmContent.ToString());
                }

                strOutput.Replace(cblm.Token, string.Empty);
            }
            theLit.Text = strOutput.ToString();
        }
Beispiel #7
0
        /// <summary>
        /// 获取EXCEL表里的数据
        /// </summary>
        /// <param name="fPath"></param>
        /// <param name="tableName"></param>
        /// <param name="mobiles"></param>
        /// <returns></returns>
        private string GetExcelTableData(string fPath, string tableName)
        {
            StringBuilder sb      = new StringBuilder();
            StringWriter  sw      = new StringWriter(sb);
            string        strConn = string.Empty;

            strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fPath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";

            OleDbConnection conn = new OleDbConnection(strConn);

            conn.Open();
            string           strExcel  = "";
            OleDbDataAdapter myCommand = null;
            DataSet          ds        = null;

            strExcel  = "select * from [" + tableName + "]";
            myCommand = new OleDbDataAdapter(strExcel, strConn);
            ds        = new DataSet();
            myCommand.Fill(ds, "table1");
            myCommand.Dispose();
            conn.Close();
            conn.Dispose();

            if (ds == null || ds.Tables.Count == 0 || ds.Tables[0] == null)
            {
                return(string.Empty);
            }

            DataTable dt = ds.Tables[0];

            if (dt.Rows.Count > 0)
            {
                using (JsonWriter jsonWriter = new JsonTextWriter(sw))
                {
                    jsonWriter.WriteStartArray();

                    jsonWriter.WriteStartArray();
                    foreach (DataColumn dc in dt.Columns)
                    {
                        jsonWriter.WriteValue(dc.ColumnName);
                    }
                    jsonWriter.WriteEndArray();

                    foreach (DataRow dr in dt.Rows)
                    {
                        jsonWriter.WriteStartArray();
                        int i = 0;
                        for (; i < dr.ItemArray.Length; i++)
                        {
                            jsonWriter.WriteValue(dr[i].ToString());
                        }
                        jsonWriter.WriteEndArray();
                    }


                    jsonWriter.WriteEnd();
                }
            }

            dt.Dispose();

            return(sb.ToString());
        }
Beispiel #8
0
    static void SaveJson()
    {
        var path = EditorUtility.SaveFilePanel(
            "Save thing as JSON",
            "",
            "" + ".png",
            "json");

        if (path.Length != 0)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw)) {
                writer.Formatting = Formatting.Indented;

                writer.WriteStartObject();
                writer.WritePropertyName("n");
                writer.WriteValue("Thing Name");
                //**TODO add inc */
                writer.WritePropertyName("p");
                writer.WriteStartArray();

                GameObject[] allGameObjects = GameObject.FindGameObjectsWithTag("Part");
                foreach (GameObject o in allGameObjects)
                {
                    float px = o.transform.position.x;
                    float py = o.transform.position.y;
                    float pz = o.transform.position.z;

                    float sx = o.transform.localScale.x;
                    float sy = o.transform.localScale.y;
                    float sz = o.transform.localScale.z;

                    float rx = o.transform.localEulerAngles.x;
                    float ry = o.transform.localEulerAngles.y;
                    float rz = o.transform.localEulerAngles.z;

                    Color c = o.transform.GetChild(0).GetComponent <Renderer>().sharedMaterial.GetColor("_Color");

                    float cx = c.r;
                    float cy = c.g;
                    float cz = c.b;

                    writer.WriteStartObject();
                    writer.WritePropertyName("b");
                    writer.WriteValue(Int32.Parse(o.name));

                    writer.WritePropertyName("s");
                    writer.WriteStartArray();
                    //loop
                    Part part = o.GetComponent <Part>();
                    foreach (State state in part.states)
                    {
                        Debug.Log(state);
                        Debug.Log(state.position.x);
                        writer.WriteStartObject();
                        writer.WritePropertyName("p");
                        writer.WriteStartArray();
                        writer.WriteValue(state.position.x);
                        writer.WriteValue(state.position.y);
                        writer.WriteValue(state.position.z);
                        writer.WriteEnd();

                        writer.WritePropertyName("r");
                        writer.WriteStartArray();
                        writer.WriteValue(state.rotation.x);
                        writer.WriteValue(state.rotation.y);
                        writer.WriteValue(state.rotation.z);
                        writer.WriteEnd();

                        writer.WritePropertyName("s");
                        writer.WriteStartArray();
                        writer.WriteValue(state.scale.x);
                        writer.WriteValue(state.scale.y);
                        writer.WriteValue(state.scale.z);
                        writer.WriteEnd();

                        writer.WritePropertyName("c");
                        writer.WriteStartArray();
                        writer.WriteValue(state.color.r);
                        writer.WriteValue(state.color.g);
                        writer.WriteValue(state.color.b);
                        writer.WriteEnd();

                        writer.WritePropertyName("b");
                        writer.WriteStartArray();
                        foreach (string script in state.scripts)
                        {
                            writer.WriteValue(script);
                        }
                        writer.WriteEndArray();
                        writer.WriteEndObject();
                    }
                    writer.WriteEndArray();
                    writer.WriteEndObject();
                }
                writer.WriteEndObject();
            }
            StreamWriter streamWriter = new StreamWriter(path);
            streamWriter.WriteLine(sb.ToString());
            streamWriter.Close();
        }
    }
Beispiel #9
0
        private string WriteProperty(PropertyInfo pi, Stack <Type> typeStack)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            Type pType    = pi.PropertyType;
            bool required = true;

            if (pType.IsGenericType && pType.GetGenericTypeDefinition() == typeof(System.Nullable <>))
            {
                required = false;
                pType    = pType.GetGenericArguments().First();
            }

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                var memberProperties = pi.GetCustomAttribute <MemberPropertiesAttribute>();

                var typeValue = memberProperties != null?Helpers.MapSwaggerType(pType, typeStack, memberProperties.TypeSizeNote) : Helpers.MapSwaggerType(pType, typeStack);

                //If the Name property in DataContract is defined for this property type, use that name instead.
                //Needed for cases where a DataContract uses another DataContract as a return type for a member.
                var dcName = Helpers.GetDataContractNamePropertyValue(pType);

                if (!string.IsNullOrEmpty(dcName))
                {
                    typeValue = dcName;
                    if (memberProperties != null && !string.IsNullOrEmpty(memberProperties.TypeSizeNote))
                    {
                        typeValue = string.Format("{0}({1})", dcName, memberProperties.TypeSizeNote);
                    }
                }


                writer.WriteStartObject();

                writer.WritePropertyName("type");
                writer.WriteValue(typeValue);

                writer.WritePropertyName("required");
                writer.WriteValue(required);

                DescriptionAttribute description = pi.GetCustomAttribute <DescriptionAttribute>();
                if (description != null)
                {
                    writer.WritePropertyName("description");
                    writer.WriteValue(description.Description);
                }
                else
                {
                    if (memberProperties != null)
                    {
                        writer.WritePropertyName("description");
                        writer.WriteValue(memberProperties.Description);
                    }
                }

                if (Helpers.MapSwaggerType(pType, typeStack) == "array")
                {
                    writer.WritePropertyName("items");
                    writer.WriteStartObject();
                    writer.WritePropertyName("$ref");
                    writer.WriteValue(Helpers.MapElementType(pType, typeStack));
                }

                if (pType.IsEnum)
                {
                    writer.WritePropertyName("enum");
                    writer.WriteStartArray();
                    foreach (string value in pType.GetEnumNames())
                    {
                        writer.WriteValue(value);
                    }
                    writer.WriteEndArray();
                }

                writer.WriteEnd();
            }
            return(sb.ToString());
        }
Beispiel #10
0
        private void SalvaAssistenciaTecnica(Domain.Model.Conta assistencia)
        {
            StringBuilder sb = null;
            StringWriter  sw = null;
            JsonWriter    wt = null;

            try
            {
                var reqInserir = new RestRequest();

                reqInserir.AddHeader("Content-Type", "application/json");
                reqInserir.AddHeader("Accept", "application/json");
                reqInserir.AddHeader("accept-language", "pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4,es;q=0.2");
                reqInserir.AddHeader("Cookie", token);
                reqInserir.AddHeader("X-CSRF-Token", csrf_token);
                reqInserir.Resource      = "/api/auth/technical-support/{crm_id}";
                reqInserir.Method        = Method.PUT;
                reqInserir.RequestFormat = DataFormat.Json;
                reqInserir.AddParameter("crm_id", assistencia.CodigoMatriz, ParameterType.UrlSegment);

                reqInserir.OnBeforeDeserialization = resp =>
                {
                    resp.ContentType = "application/json";
                };

                sb = new StringBuilder();
                sw = new StringWriter(sb);

                wt = new JsonTextWriter(sw);

                wt.Formatting = Formatting.Indented;
                wt.WriteStartObject();
                wt.WritePropertyName("title");
                wt.WriteValue(assistencia.NomeFantasia);

                wt.WritePropertyName("field_email");
                wt.WriteStartObject();
                wt.WritePropertyName("und");
                wt.WriteStartArray();
                wt.WriteStartObject();
                wt.WritePropertyName("email");
                wt.WriteValue(assistencia.Email);
                wt.WriteEndObject();
                wt.WriteEndArray();
                wt.WriteEndObject();

                wt.WritePropertyName("field_address");
                wt.WriteStartObject();
                wt.WritePropertyName("und");
                wt.WriteStartArray();
                wt.WriteStartObject();
                wt.WritePropertyName("organisation_name");
                wt.WriteValue(assistencia.Nome);
                wt.WritePropertyName("country");
                wt.WriteValue("BR");
                wt.WritePropertyName("administrative_area");
                var estado = (new Domain.Servicos.RepositoryService()).Estado.ObterPor(assistencia.Endereco1Estadoid.Id);
                wt.WriteValue(estado.SiglaUF);

                wt.WritePropertyName("locality");
                wt.WriteValue(assistencia.Endereco1Municipioid.Name);
                wt.WritePropertyName("postal_code");
                wt.WriteValue(assistencia.Endereco1CEP);
                wt.WritePropertyName("thoroughfare");
                wt.WriteValue(assistencia.Endereco1Rua + ", " + assistencia.Endereco1Numero + " " + assistencia.Endereco1Complemento);
                wt.WritePropertyName("premise");
                wt.WriteValue(assistencia.Endereco1Bairro);
                wt.WritePropertyName("phone_number");
                wt.WriteValue(assistencia.Telefone);
                wt.WriteEndObject();
                wt.WriteEndArray();
                wt.WriteEndObject();

                #region products_related

                List <Product> produtos = ObterProtutos(assistencia);

                wt.WritePropertyName("products_related");
                wt.WriteStartArray();


                foreach (Product item in produtos.Take(10000))
                {
                    wt.WriteValue(item.Codigo);
                }

                wt.WriteEnd();

                #endregion

                wt.WriteEndObject();

                reqInserir.AddParameter("application/json", sw.ToString(), ParameterType.RequestBody);

                CreateLog("Enviado JSON de ATUALIZACAO \n" + sw.ToString());

                var resultado = ClienteRest.Execute <RespostaPut>(reqInserir);


                if (resultado == null)
                {
                    throw new ApplicationException("[Incluir Assistencia Tecnica] Mensagem de Retorno esta vazia!");
                }

                if (resultado.ErrorException != null)
                {
                    throw new ApplicationException("[Incluir Assistencia Tecnica] Mensagem de Retorno: " + resultado.ErrorException
                                                   + " \nRequest: " + sw.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
            finally
            {
                sb = null;

                wt.Close();

                sw.Close();
                sw.Dispose();
            }
        }
    /// <summary>
    /// 生成返回的Json数据
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    private string BuildResultJson(dotNetFlexGrid.DataHandlerResult data)
    {
        DataTable     dt = data.table;
        StringBuilder sb = new StringBuilder();

        StringWriter sw = new StringWriter(sb);
        //处理主键
        string key = string.Empty;

        if (dt.PrimaryKey.Length > 0)
        {
            key = dt.PrimaryKey[0].ColumnName;//第一个作为主键
        }
        else
        {
            //否则拿第一列作为主键
            key = dt.Columns[0].ColumnName;
        }
        using (JsonWriter jsonWriter = new JsonTextWriter(sw))
        {
            jsonWriter.Formatting = Formatting.Indented;
            jsonWriter.WriteStartObject();
            jsonWriter.WritePropertyName("page");
            jsonWriter.WriteValue(data.page.ToString());  //当前页
            jsonWriter.WritePropertyName("total");
            jsonWriter.WriteValue(data.total.ToString()); //总共的条数
            jsonWriter.WritePropertyName("rows");
            jsonWriter.WriteStartArray();
            foreach (DataRow dr in dt.Rows)
            {
                jsonWriter.WriteStartObject();
                jsonWriter.WritePropertyName("id");
                jsonWriter.WriteValue(dr[key].ToString());


                jsonWriter.WritePropertyName("cell");
                jsonWriter.WriteStartArray();
                foreach (string field in _FieldConfigs.Keys)
                {
                    string txt = string.Empty;
                    if (!_LocalDataColumnsDic.ContainsKey(field) &&
                        (_FieldConfigs[field]._ItemTemplate == null || _FieldConfigs[field]._ItemTemplate.Length == 0) &&
                        !data.FieldFormator.FormatorList.ContainsKey(field)
                        )
                    {
                        //产生默认的错误字段提示
                        txt = "<b>noset at " + field + "</b>";
                    }
                    else
                    {
                        if (data.FieldFormator.FormatorList.ContainsKey(field) &&
                            data.FieldFormator.FormatorList[field].handle != null)
                        {
                            bool isSuccess = false;
                            try
                            {
                                txt       = data.FieldFormator.FormatorList[field].handle(dr);
                                isSuccess = true;
                            }
                            catch (Exception ex)
                            {
                                txt = txt = "<b>formater error at " + field + "msg=" + ex.Message + "</b>";;
                            }

                            if (isSuccess && txt == null && _LocalDataColumnsDic.ContainsKey(field))
                            {
                                //处理器放弃处理,继续使用原来的数据
                                txt = dr[field].ToString();
                            }
                        }
                        else if (_LocalDataColumnsDic.ContainsKey(field)
                                 )
                        {
                            txt = dr[field].ToString();
                        }
                        else
                        {
                            txt = "<b>error at " + field + "</b>";
                        }
                        if (_FieldConfigs[field]._ItemTemplate != null && _FieldConfigs[field]._ItemTemplate.Length != 0)
                        {
                            //存在模板替换
                            txt = GetTemplateColumnValue(field, txt, dr, _FieldConfigs[field]._ItemTemplate);
                        }
                    }
                    jsonWriter.WriteValue(txt);
                }
                jsonWriter.WriteEndObject();
            }
            jsonWriter.WriteEnd();
            jsonWriter.WriteEndObject();
        }

        return(sb.ToString());
    }
Beispiel #12
0
        public HttpResponseMessage Post([FromBody] PutModel value)
        {
            HttpResponseMessage result = null;
            var    appSettings         = ConfigurationManager.AppSettings;
            string SourcePath          = appSettings["CourseDirectory"] + value.source;
            string TargetPath          = appSettings["CourseDirectory"] + value.target;

            if (value.action == "CourseVideoMove")
            {
                StringBuilder sb = new StringBuilder();
                StringWriter  sw = new StringWriter(sb);
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.WriteStartObject();
                    //video+pic
                    writer.WritePropertyName("video");
                    if (File.Exists(SourcePath + value.ProjectId + ".mp4") && File.Exists(SourcePath + value.ProjectId + ".jpg"))
                    {
                        //建目录
                        if (Directory.Exists(TargetPath))
                        {
                            if (File.Exists(TargetPath + @"raw.mp4"))
                            {
                                File.Delete(TargetPath + @"raw.mp4");
                            }
                            if (File.Exists(TargetPath + @"rip.mp4"))
                            {
                                File.Delete(TargetPath + @"rip.mp4");
                            }
                            if (File.Exists(TargetPath + @"raw.jpg"))
                            {
                                File.Delete(TargetPath + @"raw.jpg");
                            }
                        }
                        else
                        {
                            Directory.CreateDirectory(TargetPath);
                        }
                        File.Move(SourcePath + value.ProjectId + ".mp4", TargetPath + "raw.mp4");
                        writer.WriteValue("1");
                        //pic
                        writer.WritePropertyName("pic");
                        File.Move(SourcePath + value.ProjectId + ".jpg", TargetPath + "raw.jpg");
                        writer.WriteValue("1");
                        //doc
                        writer.WritePropertyName("doc");
                        if (File.Exists(SourcePath + value.ProjectId + ".zip"))
                        {
                            if (File.Exists(TargetPath + @"slide0.zip"))
                            {
                                File.Delete(TargetPath + @"slide0.zip");
                            }
                            File.Move(SourcePath + value.ProjectId + ".zip", TargetPath + "slide0.zip");
                            writer.WriteValue("1");
                        }
                        else
                        {
                            writer.WriteValue("0");
                        }
                    }
                    else
                    {
                        writer.WriteValue("0");
                    }
                    writer.WriteEnd();
                    //writer.WriteEndObject();
                }
                result         = new HttpResponseMessage(HttpStatusCode.Accepted);
                result.Content = new StringContent(sb.ToString(), System.Text.Encoding.GetEncoding("UTF-8"), "application/json");
            }
            else if (value.action == "CourseFileCopy")
            {
                StringBuilder sb = new StringBuilder();
                StringWriter  sw = new StringWriter(sb);
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.WriteStartObject();
                    //video+pic
                    writer.WritePropertyName("video");
                    if (File.Exists(SourcePath + "raw" + ".mp4") && File.Exists(SourcePath + "raw" + ".jpg"))
                    {
                        //建目录
                        if (Directory.Exists(TargetPath))
                        {
                            if (File.Exists(TargetPath + @"raw.mp4"))
                            {
                                File.Delete(TargetPath + @"raw.mp4");
                            }
                            if (File.Exists(TargetPath + @"rip.mp4"))
                            {
                                File.Delete(TargetPath + @"rip.mp4");
                            }
                            if (File.Exists(TargetPath + @"raw.jpg"))
                            {
                                File.Delete(TargetPath + @"raw.jpg");
                            }
                        }
                        else
                        {
                            Directory.CreateDirectory(TargetPath);
                        }
                        File.Copy(SourcePath + "raw" + ".mp4", TargetPath + "raw.mp4");
                        writer.WriteValue("1");
                        //pic
                        writer.WritePropertyName("pic");
                        File.Copy(SourcePath + "raw" + ".jpg", TargetPath + "raw.jpg");
                        writer.WriteValue("1");
                        //doc
                        writer.WritePropertyName("doc");
                        if (File.Exists(SourcePath + "slide0" + ".zip"))
                        {
                            if (File.Exists(TargetPath + @"slide0.zip"))
                            {
                                File.Delete(TargetPath + @"slide0.zip");
                            }
                            File.Copy(SourcePath + "slide0" + ".zip", TargetPath + "slide0.zip");
                            writer.WriteValue("1");
                        }
                        else
                        {
                            writer.WriteValue("0");
                        }
                    }
                    else
                    {
                        writer.WriteValue("0");
                    }
                    writer.WriteEnd();
                    //writer.WriteEndObject();
                }
                result         = new HttpResponseMessage(HttpStatusCode.Accepted);
                result.Content = new StringContent(sb.ToString(), System.Text.Encoding.GetEncoding("UTF-8"), "application/json");
            }
            else if (value.action == "JsonBackup")
            {
                StringBuilder sb = new StringBuilder();
                StringWriter  sw = new StringWriter(sb);
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.WriteStartObject();
                    writer.WritePropertyName("json");
                    if (File.Exists(SourcePath + "captions.json"))
                    {
                        try
                        {
                            File.Copy(SourcePath + "captions.json", SourcePath + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_") + "captions_backup.json");
                            File.Copy(SourcePath + "captions_auto.json", SourcePath + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_") + "captions_auto_backup.json");
                        }
                        catch (Exception e)
                        {
                            result         = new HttpResponseMessage(HttpStatusCode.Accepted);
                            result.Content = new StringContent(e.ToString(), System.Text.Encoding.GetEncoding("UTF-8"), "application/json");
                        }
                        writer.WriteValue("1");
                    }
                    else
                    {
                        writer.WriteValue("0");
                    }
                    writer.WriteEnd();
                }
                result         = new HttpResponseMessage(HttpStatusCode.Accepted);
                result.Content = new StringContent(sb.ToString(), System.Text.Encoding.GetEncoding("UTF-8"), "application/json");
            }
            else if (value.action == "CourseDirectoryRename")
            {
            }
            else
            {
            }
            return(result);
        }
Beispiel #13
0
        /// <summary>
        /// Crawl and write news & comments in json format.
        /// </summary>
        /// <param name="news">news list</param>
        /// <returns>Json string.</returns>
        private string CrawlAsJson(IList <NewsItem> news)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Newtonsoft.Json.Formatting.Indented;
                if (0 == news.Count)
                {
                    return(string.Empty);
                }

                writer.WriteStartObject();
                writer.WritePropertyName("root");
                writer.WriteStartObject();
                writer.WritePropertyName("item");
                writer.WriteStartArray();
                Dictionary <string, string> properties = new Dictionary <string, string>();
                foreach (var newsItem in news)
                {
                    writer.WriteStartObject();

                    properties.Add("title", newsItem.Title);
                    properties.Add("baseurl", newsItem.BaseUrl);
                    properties.Add("keywords", newsItem.Keywords);
                    properties.Add("summary", newsItem.Summary);
                    properties.Add("firstpara", newsItem.FirstPara);
                    properties.Add("bodytext", newsItem.BodyText);
                    WriteSequentialProperties(writer, properties);
                    properties.Clear();

                    #region Comments
                    IList <Comment> comments = newsItem.Comments;// GetComments(newsItem, commentCount);
                    writer.WritePropertyName("comment");
                    writer.WriteStartArray();
                    if (null != comments && comments.Count > 0)
                    {
                        foreach (var comment in comments)
                        {
                            writer.WriteStartObject();

                            properties.Add("text", comment.Cotent);
                            properties.Add("vote", comment.Vote.ToString());
                            WriteSequentialProperties(writer, properties);

                            writer.WriteEnd();
                        }
                    }
                    writer.WriteEndArray();
                    #endregion  // end of Comments

                    writer.WriteEndObject();
                }

                writer.WriteEndArray();
                writer.WriteEnd();
                writer.WriteEndObject();
            }

            return(sw.GetStringBuilder().ToString());
        }
 public override void WriteEnd() => jsonTextWriter.WriteEnd();
Beispiel #15
0
        public async Task ExportToJson(string tableName, TextWriter writer, Action <int> progress = null)
        {
            try
            {
                var table = storageContext.GetTableReference(tableName);

                var existsTable = await table.ExistsAsync();

                if (!existsTable)
                {
                    var message = $"Table '{tableName}' does not exist";
                    throw new FileNotFoundException(message);
                }

                var tableQuery = new TableQuery <DynamicTableEntity>();
                TableContinuationToken tableContinuationToken = null;
                var querySegmentIndex = 0;

                JsonWriter wr = new JsonTextWriter(writer);

                // prepare the array in result
                wr.WriteStartArray();

                // download the pages
                do
                {
                    // query the data
                    var queryResponse = await table.ExecuteQuerySegmentedAsync(tableQuery, tableContinuationToken, null, null);

                    var queryResponseEntitiesCount = queryResponse.Results.Count;

                    // move to next segment
                    tableContinuationToken = queryResponse.ContinuationToken;

                    // process the segment
                    ++querySegmentIndex;
                    progress?.Invoke(queryResponseEntitiesCount);

                    // do the backup
                    foreach (var entity in queryResponse.Results)
                    {
                        wr.WriteStartObject();
                        wr.WritePropertyName(TableConstants.RowKey);
                        wr.WriteValue(entity.RowKey);
                        wr.WritePropertyName(TableConstants.PartitionKey);
                        wr.WriteValue(entity.PartitionKey);
                        wr.WritePropertyName(TableConstants.Properties);
                        wr.WriteStartArray();
                        foreach (var propertyKvp in entity.Properties)
                        {
                            wr.WriteStartObject();
                            wr.WritePropertyName(TableConstants.PropertyName);
                            wr.WriteValue(propertyKvp.Key);
                            wr.WritePropertyName(TableConstants.PropertyType);
                            wr.WriteValue(propertyKvp.Value.PropertyType);
                            wr.WritePropertyName(TableConstants.PropertyValue);
                            wr.WriteValue(GetPropertyValue(propertyKvp.Value.PropertyType, propertyKvp.Value));
                            wr.WriteEndObject();
                        }
                        wr.WriteEnd();
                        wr.WriteEndObject();
                    }
                }while (tableContinuationToken != null);

                // finishe the export
                wr.WriteEnd();
                wr.Flush();
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #16
0
        public int modifyProduct(ref string desc)
        {
            if (licenseId == 0)
            {
                return(INVALIDLICID);
            }
            if (productName == "" || licenseForm == 0)
            {
                return(NSETPRODUCT);
            }

            //拼接json数据
            StringBuilder jProduct = new StringBuilder();
            StringWriter  sw       = new StringWriter(jProduct);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;

                writer.WriteStartObject();
                writer.WritePropertyName("licenseId");
                writer.WriteValue(licenseId);
                if (productName != "")
                {
                    writer.WritePropertyName("productName");
                    writer.WriteValue(productName);
                }
                writer.WritePropertyName("licenseForm");
                writer.WriteStartArray();
                if (licenseForm == cloud)
                {
                    writer.WriteValue(cloud);
                }
                else if (licenseForm == slock)
                {
                    writer.WriteValue(slock);
                }
                else if (licenseForm == cldAndSlk)
                {
                    writer.WriteValue(cloud);
                    writer.WriteValue(slock);
                }
                writer.WriteEnd();
                if (moduleInfo.Count != 0)
                {
                    string module = module2Json();
                    writer.WritePropertyName("modules");
                    writer.WriteValue(module);
                }
                if (raw != "")
                {
                    writer.WritePropertyName("raw");
                    writer.WriteValue(raw);
                }
                if (pub != "")
                {
                    writer.WritePropertyName("pub");
                    writer.WriteValue(pub);
                }
                if (rom != "")
                {
                    writer.WritePropertyName("rom");
                    writer.WriteValue(rom);
                }
                writer.WriteEndObject();
            }
            //调用公共算法类
            algorithm ALG         = new algorithm();
            string    proJsonInfo = jProduct.ToString();
            string    retJson     = ALG.senseCloudRequest(API.ModifyProduct, proJsonInfo, Dev.Appid, Dev.Secret);
            //解析JSON返回值
            JObject jobj = JObject.Parse(retJson);
            int     ret  = Convert.ToInt32(jobj["code"].ToString());

            desc = jobj["desc"].ToString();
            return(ret);
        }
        public void Path()
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            string text = "Hello world.";

            byte[] data = Encoding.UTF8.GetBytes(text);

            using (JsonTextWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;

                writer.WriteStartArray();
                Assert.AreEqual("", writer.Path);
                writer.WriteStartObject();
                Assert.AreEqual("[0]", writer.Path);
                writer.WritePropertyName("Property1");
                Assert.AreEqual("[0].Property1", writer.Path);
                writer.WriteStartArray();
                Assert.AreEqual("[0].Property1", writer.Path);
                writer.WriteValue(1);
                Assert.AreEqual("[0].Property1[0]", writer.Path);
                writer.WriteStartArray();
                Assert.AreEqual("[0].Property1[1]", writer.Path);
                writer.WriteStartArray();
                Assert.AreEqual("[0].Property1[1][0]", writer.Path);
                writer.WriteStartArray();
                Assert.AreEqual("[0].Property1[1][0][0]", writer.Path);
                writer.WriteEndObject();
                Assert.AreEqual("[0]", writer.Path);
                writer.WriteStartObject();
                Assert.AreEqual("[1]", writer.Path);
                writer.WritePropertyName("Property2");
                Assert.AreEqual("[1].Property2", writer.Path);
                writer.WriteStartConstructor("Constructor1");
                Assert.AreEqual("[1].Property2", writer.Path);
                writer.WriteNull();
                Assert.AreEqual("[1].Property2[0]", writer.Path);
                writer.WriteStartArray();
                Assert.AreEqual("[1].Property2[1]", writer.Path);
                writer.WriteValue(1);
                Assert.AreEqual("[1].Property2[1][0]", writer.Path);
                writer.WriteEnd();
                Assert.AreEqual("[1].Property2[1]", writer.Path);
                writer.WriteEndObject();
                Assert.AreEqual("[1]", writer.Path);
                writer.WriteEndArray();
                Assert.AreEqual("", writer.Path);
            }

            Assert.AreEqual(@"[
  {
    ""Property1"": [
      1,
      [
        [
          []
        ]
      ]
    ]
  },
  {
    ""Property2"": new Constructor1(
      null,
      [
        1
      ]
    )
  }
]", sb.ToString());
        }
Beispiel #18
0
        private string WriteQuery(
            IEnumerable <Field> fields,
            ReadFrom readFrom,
            IContext context,
            int from = 0,
            int size = 10
            )
        {
            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            using (var writer = new JsonTextWriter(sw)) {
                writer.WriteStartObject();

                writer.WritePropertyName("from");
                writer.WriteValue(from);
                writer.WritePropertyName("size");
                writer.WriteValue(size);

                writer.WritePropertyName("_source");
                writer.WriteStartObject();
                writer.WritePropertyName("includes");
                writer.WriteStartArray();
                foreach (var field in fields)
                {
                    writer.WriteValue(readFrom == ReadFrom.Input ? field.Name : field.Alias.ToLower());
                }
                writer.WriteEndArray();
                writer.WriteEndObject();

                if (readFrom == ReadFrom.Input)
                {
                    if (context.Entity.Filter.Any(f => f.Value != "*"))
                    {
                        writer.WritePropertyName("query");
                        writer.WriteStartObject();
                        writer.WritePropertyName("constant_score");
                        writer.WriteStartObject();
                        writer.WritePropertyName("filter");
                        writer.WriteStartObject();
                        writer.WritePropertyName("bool");
                        writer.WriteStartObject();
                        writer.WritePropertyName("must");
                        writer.WriteStartArray();

                        foreach (var filter in context.Entity.Filter.Where(f =>
                                                                           (f.Expression != string.Empty && f.Expression != "*") ||
                                                                           (f.Value != "*" && f.Value != string.Empty))
                                 )
                        {
                            writer.WriteStartObject();

                            switch (filter.Type)
                            {
                            case "facet":
                                if (filter.Value.Contains(","))
                                {
                                    writer.WritePropertyName("terms");
                                    writer.WriteStartObject();
                                    writer.WritePropertyName(filter.LeftField.Name);

                                    writer.WriteStartArray();     // values
                                    foreach (var value in filter.Value.Split(','))
                                    {
                                        writer.WriteValue(value);
                                    }
                                    writer.WriteEndArray();     //values

                                    writer.WriteEndObject();
                                }
                                else
                                {
                                    writer.WritePropertyName("term");
                                    writer.WriteStartObject();
                                    writer.WritePropertyName(filter.LeftField.Name);
                                    writer.WriteValue(filter.Value);
                                    writer.WriteEndObject();
                                }
                                break;

                            case "range":
                                break;

                            default:     //search
                                if (filter.Expression == string.Empty)
                                {
                                    if (_isQueryString.IsMatch(filter.Value))
                                    {
                                        // query_string query
                                        writer.WritePropertyName("query_string");
                                        writer.WriteStartObject();     // query_string

                                        writer.WritePropertyName("query");
                                        writer.WriteValue(filter.Value);

                                        writer.WritePropertyName("default_field");
                                        writer.WriteValue(filter.LeftField.Name);

                                        writer.WritePropertyName("analyze_wildcard");
                                        writer.WriteValue(true);

                                        writer.WritePropertyName("default_operator");
                                        writer.WriteValue("AND");

                                        writer.WriteEnd();     // query_string
                                    }
                                    else
                                    {
                                        // match query
                                        writer.WritePropertyName("match");
                                        writer.WriteStartObject();     // match

                                        writer.WritePropertyName(filter.LeftField.Name);
                                        writer.WriteStartObject();     // field name

                                        writer.WritePropertyName("query");
                                        writer.WriteValue(filter.Value);

                                        writer.WritePropertyName("operator");
                                        writer.WriteValue(filter.Continuation.ToLower());

                                        writer.WriteEndObject();     // field name
                                        writer.WriteEndObject();     // match
                                    }
                                }
                                else
                                {
                                    writer.WritePropertyName("query_string");
                                    writer.WriteStartObject();     // query_string

                                    writer.WritePropertyName("query");
                                    writer.WriteValue(filter.Expression);

                                    if (filter.Field != string.Empty)
                                    {
                                        writer.WritePropertyName("default_field");
                                        writer.WriteValue(filter.LeftField.Name);
                                    }

                                    writer.WritePropertyName("analyze_wildcard");
                                    writer.WriteValue(true);

                                    writer.WritePropertyName("default_operator");
                                    writer.WriteValue("AND");

                                    writer.WriteEnd();     // query_string
                                }

                                break;
                            }
                            writer.WriteEndObject(); //must
                        }

                        writer.WriteEndArray();
                        writer.WriteEndObject(); //bool
                        writer.WriteEndObject(); //filter
                        writer.WriteEndObject(); //constant_score
                        writer.WriteEndObject(); //query
                    }
                }
                else
                {
                    writer.WritePropertyName("query");
                    writer.WriteStartObject();
                    writer.WritePropertyName("constant_score");
                    writer.WriteStartObject();
                    writer.WritePropertyName("filter");
                    writer.WriteStartObject();
                    writer.WritePropertyName("term");
                    writer.WriteStartObject();
                    writer.WritePropertyName("tfldeleted");
                    writer.WriteValue(false);
                    writer.WriteEndObject();
                    writer.WriteEndObject();
                    writer.WriteEndObject();
                    writer.WriteEndObject();
                }

                if (context.Entity.Order.Any())
                {
                    writer.WritePropertyName("sort");
                    writer.WriteStartArray();

                    foreach (var orderBy in context.Entity.Order)
                    {
                        Field field;
                        if (context.Entity.TryGetField(orderBy.Field, out field))
                        {
                            var name = _readFrom == ReadFrom.Input ? field.SortField.ToLower() : field.Alias.ToLower();
                            writer.WriteStartObject();
                            writer.WritePropertyName(name);
                            writer.WriteStartObject();
                            writer.WritePropertyName("order");
                            writer.WriteValue(orderBy.Sort);
                            writer.WriteEndObject();
                            writer.WriteEndObject();
                        }
                    }

                    writer.WriteEndArray();
                }

                if (_readFrom == ReadFrom.Input && context.Entity.Filter.Any(f => f.Type == "facet"))
                {
                    writer.WritePropertyName("aggs");
                    writer.WriteStartObject();
                    foreach (var filter in context.Entity.Filter.Where(f => f.Type == "facet"))
                    {
                        writer.WritePropertyName(filter.Key);
                        writer.WriteStartObject();

                        writer.WritePropertyName("terms");
                        writer.WriteStartObject();
                        writer.WritePropertyName("field");
                        writer.WriteValue(filter.LeftField.Name);
                        writer.WritePropertyName("size");
                        writer.WriteValue(filter.Size);
                        writer.WritePropertyName("min_doc_count");
                        writer.WriteValue(filter.Min);

                        writer.WritePropertyName("order");
                        writer.WriteStartObject();
                        writer.WritePropertyName(filter.OrderBy);
                        writer.WriteValue(filter.Order);
                        writer.WriteEndObject(); //order


                        writer.WriteEndObject(); // terms

                        writer.WriteEndObject(); // the field name + _filter
                    }
                    writer.WriteEndObject();     //aggs
                }


                writer.WriteEndObject();
                writer.Flush();
                return(sb.ToString());
            }
        }
Beispiel #19
0
        private static void DbMode(ArgsParser parser)
        {
            if (parser
                .Keys("p", "port").Value(out var port, 8000)
                .Keys("d", "database").Value(out var connectionString, "Server=localhost;Trusted_Connection=True;")
                .Keys("f", "flush").Value(out var flush, 1000)
                .Keys("s", "sleep").Value(out var sleep, 0)
                .Result() != null)
            {
                return;
            }

            var serializer = new JsonSerializer();

            var listener = new HttpServer(IPAddress.Any, port);

            listener.OnGet += (sender, args) =>
            {
                Console.WriteLine("Connected");

                args.Response.SendChunked = true;
                using (var streamWriter = new StreamWriter(args.Response.OutputStream))
                {
                    using (var connection = new SqlConnection(connectionString))
                    {
                        connection.Open();

                        new SqlCommand("USE InfinityLists;", connection).ExecuteNonQuery();

                        using (var reader = new SqlCommand("SELECT Id, Name, Delta FROM Data", connection).ExecuteReader())
                        {
                            using (var jsonWriter = new JsonTextWriter(streamWriter))
                            {
                                var counter = 0;

                                jsonWriter.WriteStartArray();
                                while (reader.Read())
                                {
                                    serializer.Serialize(jsonWriter, new DataItem
                                    {
                                        Id    = reader.GetInt32(0),
                                        Name  = reader.GetString(1),
                                        Delta = reader.GetDouble(2),
                                    });

                                    counter += 1;
                                    if (counter % flush == 0)
                                    {
                                        jsonWriter.Flush();
                                    }

                                    if (sleep > 0)
                                    {
                                        Thread.Sleep(sleep);
                                    }
                                }
                                jsonWriter.WriteEnd();
                            }
                        }
                    }
                }

                Console.WriteLine("Finished");
            };

            listener.Start();
            Console.WriteLine("Listening...");

            for (;;)
            {
                Console.ReadLine();
            }
        }
Beispiel #20
0
        public object Post([FromBody] dynamic req)
        {
            try
            {
                var request = Utils.parseXJSON(JObject.Parse(req.xjson.ToString()));

                if (!AuthOk((Guid)request["sessionId"], (String)request["authToken"]))
                {
                    return(NoAuthResponse());
                }

                var database = Program.BuhtaConfig.GetDatabase(request["database"].ToString());
                if (database == null)
                {
                    return(new ResponseObject()
                    {
                        error = $"invalid database '{request["database"]}'"
                    });
                }

                DbConnection conn;

                if (database.Dialect == "mssql")
                {
                    conn = new SqlConnection(database.ConnectionString);
                }
                else
                if (database.Dialect == "mysql")
                {
                    conn = new MySqlConnection(database.ConnectionString);
                }
                else
                if (database.Dialect == "postgres")
                {
                    conn = new NpgsqlConnection(database.ConnectionString);
                }
                else
                {
                    return(new ResponseObject()
                    {
                        error = $"invalid database sql dialect '{database.Dialect}'"
                    });
                }


                try
                {
                    using (conn)
                    {
                        conn.Open();

                        StringBuilder sb = new StringBuilder();
                        StringWriter  sw = new StringWriter(sb);

                        using (JsonWriter jsonWriter = new JsonTextWriter(sw))
                        {
                            //ctx.WriteString(`{ "rowsets":[`);
                            jsonWriter.WriteStartObject();
                            jsonWriter.WritePropertyName("rowsets");
                            jsonWriter.WriteStartArray();

                            foreach (string sql in request["sql"])
                            {
                                using (var cmd = conn.CreateCommand())
                                {
                                    cmd.CommandText = sql;
                                    var reader = cmd.ExecuteReader();
                                    if (reader.FieldCount == 0)
                                    {
                                        reader.Dispose();
                                        cmd.Dispose();
                                        continue;
                                    }

                                    jsonWriter.WriteStartObject();
                                    jsonWriter.WritePropertyName("columns");
                                    jsonWriter.WriteStartArray();
                                    for (int col = 0; col < reader.FieldCount; col++)
                                    {
                                        jsonWriter.WriteStartObject();
                                        jsonWriter.WritePropertyName("name");

                                        jsonWriter.WriteValue(reader.GetName(col));

                                        jsonWriter.WritePropertyName("type");
                                        jsonWriter.WriteValue(reader.GetDataTypeName(col));
                                        jsonWriter.WriteEndObject();
                                    }
                                    jsonWriter.WriteEnd();
                                    jsonWriter.WritePropertyName("rows");
                                    jsonWriter.WriteStartArray();
                                    while (true)
                                    {
                                        //jsonWriter.WriteStartArray();
                                        while (reader.Read())
                                        {
                                            jsonWriter.WriteStartArray();
                                            #region for
                                            for (int colIndex = 0; colIndex < reader.FieldCount; colIndex++)
                                            {
                                                var value = reader[colIndex];
                                                //reader.GetDataTypeName(37)
                                                if (value is DBNull)
                                                {
                                                    jsonWriter.WriteStartObject();
                                                    jsonWriter.WritePropertyName("t");
                                                    jsonWriter.WriteValue("N");
                                                    jsonWriter.WriteEndObject();
                                                }
                                                else
                                                if (value is Array && (value as Array).Length == 16 && database.Dialect == "mysql")  // это guid в mysql
                                                {
                                                    var guid = new Guid(value as byte[]);
                                                    //jsonWriter.WriteValue("<Guid>" + Convert.ToBase64String(guid.ToByteArray()));
                                                    jsonWriter.WriteValue("<Guid>" + guid);
                                                }
                                                else
                                                if (reader.GetDataTypeName(colIndex) == "BIT" && database.Dialect == "mysql")  // это boolean в mysql
                                                {
                                                    jsonWriter.WriteValue((UInt64)value != 0);
                                                }
                                                else
                                                if (value is Array)  // это BLOB
                                                {
                                                    jsonWriter.WriteValue("<ArrayBuffer>" + Convert.ToBase64String((byte[])value));
                                                }
                                                else
                                                if (value is Guid)
                                                {
                                                    //jsonWriter.WriteValue("<Guid>" + Convert.ToBase64String(((Guid)value).ToByteArray()));
                                                    jsonWriter.WriteValue("<Guid>" + value);
                                                }
                                                else
                                                if (value is DateTime)
                                                {
                                                    var date = (DateTime)value;
                                                    //jsonWriter.WriteStartObject();
                                                    //jsonWriter.WritePropertyName("t");
                                                    //jsonWriter.WriteValue("D");
                                                    //jsonWriter.WritePropertyName("v");
                                                    if (date.TimeOfDay == TimeSpan.Zero)
                                                    {
                                                        jsonWriter.WriteValue("<Date>" + (date).ToString("yyyy-MM-dd"));
                                                    }
                                                    else
                                                    if (date.Year == 0 && date.Month == 1 && date.Day == 1)
                                                    {
                                                        jsonWriter.WriteValue("<Time>" + (date).ToString("HH:mm:ss.fff"));
                                                    }
                                                    else
                                                    {
                                                        jsonWriter.WriteValue("<Date>" + (date).ToString("yyyy-MM-dd HH:mm:ss.fff"));
                                                    }
                                                    //jsonWriter.WriteEndObject();
                                                }
                                                else
                                                if (value is TimeSpan)
                                                {
                                                    jsonWriter.WriteStartObject();
                                                    jsonWriter.WritePropertyName("t");
                                                    jsonWriter.WriteValue("T");

                                                    jsonWriter.WritePropertyName("h");
                                                    jsonWriter.WriteValue(((TimeSpan)value).Hours);
                                                    jsonWriter.WritePropertyName("m");
                                                    jsonWriter.WriteValue(((TimeSpan)value).Minutes);
                                                    jsonWriter.WritePropertyName("s");
                                                    jsonWriter.WriteValue(((TimeSpan)value).Seconds);
                                                    jsonWriter.WritePropertyName("ms");
                                                    jsonWriter.WriteValue(((TimeSpan)value).Milliseconds);

                                                    jsonWriter.WriteEndObject();
                                                }
                                                else
                                                {
                                                    jsonWriter.WriteValue(value);
                                                }

                                                //Console.WriteLine(String.Format("{0}", reader[0]));
                                            }
                                            #endregion
                                            jsonWriter.WriteEnd();
                                        }
                                        //jsonWriter.WriteEnd();
                                        //if (database.Dialect != "mssql" || !reader.NextResult())
                                        if (!reader.NextResult())
                                        {
                                            break;
                                        }
                                        else
                                        {
                                            jsonWriter.WriteEnd();
                                            jsonWriter.WriteEndObject();

                                            jsonWriter.WriteStartObject();
                                            jsonWriter.WritePropertyName("columns");
                                            jsonWriter.WriteStartArray();
                                            for (int col = 0; col < reader.FieldCount; col++)
                                            {
                                                jsonWriter.WriteStartObject();
                                                jsonWriter.WritePropertyName("name");
                                                jsonWriter.WriteValue(reader.GetColumnSchema()[col].ColumnName);
                                                jsonWriter.WritePropertyName("type");
                                                jsonWriter.WriteValue(reader.GetColumnSchema()[col].DataTypeName);
                                                jsonWriter.WriteEndObject();
                                            }
                                            jsonWriter.WriteEnd();
                                            jsonWriter.WritePropertyName("rows");
                                            jsonWriter.WriteStartArray();
                                        }
                                        //Console.WriteLine("----- NEXT ------");
                                    }
                                    jsonWriter.WriteEnd();
                                    jsonWriter.WriteEndObject();
                                    reader.Dispose();
                                    cmd.Dispose();
                                }
                            }
                            jsonWriter.WriteEnd();
                            jsonWriter.WriteEndObject();
                        }
                        //Console.WriteLine("req: " + json);
                        //Console.WriteLine("abs: " + sb.ToString());

                        return(new ResponseObject()
                        {
                            compressed = Utils.CompressToByteArray(sb.ToString())
                        });
                        //return new ResponseObject() { json = sb.ToString() };
                    }
                }
                catch (Exception e)
                {
                    return(new ResponseObject()
                    {
                        error = Utf16ToUtf8(e.Message)
                    });
                }
            }
            catch (Exception e)
            {
                return(new { error = e.Message });
            }
        }
        public string WriteProgramToString(SimProgram program)
        {
            var sw     = new StringWriter();
            var writer = new JsonTextWriter(sw);

            writer.WriteStartObject();

            //write config
            writer.WritePropertyName("ProgramConfig");
            writer.WriteStartObject();

            writer.WritePropertyName("Name");
            writer.WriteValue(program.ProgramConfig.Name);

            writer.WritePropertyName("TelemetryUpdateFrequency");
            writer.WriteValue(program.ProgramConfig.TelemetryUpdateFrequency);

            writer.WritePropertyName("StartCondition");
            writer.WriteValue(program.ProgramConfig.StartCondition.ToString());

            writer.WritePropertyName("EndCondition");
            writer.WriteStartArray();
            writer.WriteValue(program.ProgramConfig.EndCondition.Condition.ToString());
            writer.WriteValue(program.ProgramConfig.EndCondition.Count);
            writer.WriteEndArray();

            writer.WritePropertyName("LogPitDelta");
            writer.WriteValue(program.ProgramConfig.LogPitDelta);

            writer.WritePropertyName("LogTireWear");
            writer.WriteValue(program.ProgramConfig.LogTireWear);

            writer.WritePropertyName("Telemetry");
            writer.WriteStartArray();
            foreach (var telemetry in program.ProgramConfig.Telemetry)
            {
                writer.WriteValue(telemetry);
            }
            writer.WriteEndArray();

            writer.WriteEndObject();
            //config written

            //write debrief
            writer.WritePropertyName("ProgramDebrief");
            writer.WriteStartObject();

            writer.WritePropertyName("AvgLapTime");
            writer.WriteValue(program.ProgramDebrief.AvgLapTime);

            writer.WritePropertyName("AvgSectorTimes");
            writer.WriteStartArray();
            foreach (var sector in program.ProgramDebrief.AvgSectorTimes)
            {
                writer.WriteValue(sector);
            }
            writer.WriteEndArray();

            writer.WritePropertyName("AvgLFWearPrLap");
            writer.WriteValue(program.ProgramDebrief.AvgLFWearPrLap);
            writer.WritePropertyName("AvgRFWearPrLap");
            writer.WriteValue(program.ProgramDebrief.AvgRFWearPrLap);
            writer.WritePropertyName("AvgLRWearPrLap");
            writer.WriteValue(program.ProgramDebrief.AvgLRWearPrLap);
            writer.WritePropertyName("AvgRRWearPrLap");
            writer.WriteValue(program.ProgramDebrief.AvgRRWearPrLap);

            writer.WritePropertyName("AvgFuelUsagePrLap");
            writer.WriteValue(program.ProgramDebrief.AvgFuelUsagePrLap);

            writer.WritePropertyName("MaxPitDeltaWithStall");
            writer.WriteValue(program.ProgramDebrief.MaxPitDeltaWithStall);

            writer.WriteEndObject();
            //debrief written

            //data
            writer.WritePropertyName("ProgramData");

            writer.WriteStartObject();

            writer.WritePropertyName("SetupName");
            writer.WriteValue(program.SetupName);

            writer.WritePropertyName("Driver");

            writer.WriteStartObject();

            writer.WritePropertyName("Name");
            writer.WriteValue(program.Driver.DriverName);

            writer.WritePropertyName("Id");
            writer.WriteValue(program.Driver.GlobalUserId);

            writer.WriteEndObject();

            if (program.CompletedLaps.Count > 0)
            {
                writer.WritePropertyName("Track");
                //track object
                writer.WriteStartObject();
                var track = program.CompletedLaps[0].Track;
                writer.WritePropertyName("Name");
                writer.WriteValue(track.Name);
                writer.WritePropertyName("DisplayName");
                writer.WriteValue(track.DisplayName);
                writer.WritePropertyName("Length");
                writer.WriteValue(track.Length);
                writer.WritePropertyName("Sectors");

                writer.WriteStartArray();
                foreach (var sector in track.Sectors)
                {
                    writer.WriteStartObject();
                    writer.WritePropertyName("Number");
                    writer.WriteValue(sector.Number);
                    writer.WritePropertyName("MetersUntilSectorStarts");
                    writer.WriteValue(sector.MetersUntilSectorStarts);
                    writer.WritePropertyName("PctOfTrack");
                    writer.WriteValue(sector.PctOfTrack);
                    writer.WriteEndObject();
                }
                writer.WriteEndArray();
                //end of track object
                writer.WriteEndObject();

                var car = program.CompletedLaps[0].Car;
                writer.WritePropertyName("Car");
                writer.WriteValue(car.Name);

                writer.WritePropertyName("CompletedLaps");
                writer.WriteStartArray();
                foreach (var lap in program.CompletedLaps)
                {
                    //lap object
                    writer.WriteStartObject();
                    writer.WritePropertyName("LapNumber");
                    writer.WriteValue(lap.LapNumber);

                    writer.WritePropertyName("Time");
                    //time object
                    writer.WriteStartObject();
                    writer.WritePropertyName("Lap");
                    writer.WriteValue(lap.Time.LapTime);
                    writer.WritePropertyName("Sectors");
                    writer.WriteStartArray();
                    foreach (var sector in lap.Time.SectorTimes)
                    {
                        writer.WriteValue(sector);
                    }
                    writer.WriteEndArray();
                    //end of time object
                    writer.WriteEndObject();

                    writer.WritePropertyName("FuelAtStart");
                    writer.WriteValue(lap.FuelInTankAtStart);
                    writer.WritePropertyName("FuelAtFinish");
                    writer.WriteValue(lap.FuelInTankAtFinish);
                    writer.WritePropertyName("FuelUsed");
                    writer.WriteValue(lap.FuelUsed);

                    writer.WritePropertyName("Incidents");
                    writer.WriteValue(lap.Incidents);

                    writer.WritePropertyName("AirTemp");
                    writer.WriteValue(lap.AirTemp);
                    writer.WritePropertyName("TrackTemp");
                    writer.WriteValue(lap.TrackTemp);

                    if (program.ProgramConfig.LogPitDelta && lap.Pit != null)
                    {
                        writer.WritePropertyName("PitDelta");
                        writer.WriteValue(lap.Pit.PitDeltaSeconds);
                        writer.WritePropertyName("WasInStall");
                        writer.WriteValue(lap.Pit.WasInStall);
                    }

                    if (program.ProgramConfig.LogTireWear && lap.Pit != null && lap.Pit.Tire != null)
                    {
                        writer.WritePropertyName("Tires");
                        //tire object
                        writer.WriteStartObject();
                        writer.WritePropertyName("LFwearL");
                        writer.WriteValue(lap.Pit.Tire.LFwearL);
                        writer.WritePropertyName("LFwearM");
                        writer.WriteValue(lap.Pit.Tire.LFwearM);
                        writer.WritePropertyName("LFwearR");
                        writer.WriteValue(lap.Pit.Tire.LFwearR);

                        writer.WritePropertyName("RFwearL");
                        writer.WriteValue(lap.Pit.Tire.RFwearL);
                        writer.WritePropertyName("RFwearM");
                        writer.WriteValue(lap.Pit.Tire.RFwearM);
                        writer.WritePropertyName("RFwearR");
                        writer.WriteValue(lap.Pit.Tire.RFwearR);

                        writer.WritePropertyName("LRwearL");
                        writer.WriteValue(lap.Pit.Tire.LRwearL);
                        writer.WritePropertyName("LRwearM");
                        writer.WriteValue(lap.Pit.Tire.LRwearM);
                        writer.WritePropertyName("LRwearR");
                        writer.WriteValue(lap.Pit.Tire.LRwearR);

                        writer.WritePropertyName("RRwearL");
                        writer.WriteValue(lap.Pit.Tire.RRwearL);
                        writer.WritePropertyName("RRwearM");
                        writer.WriteValue(lap.Pit.Tire.RRwearM);
                        writer.WritePropertyName("RRwearR");
                        writer.WriteValue(lap.Pit.Tire.RRwearR);
                        //end of tire object
                        writer.WriteEndObject();
                    }

                    writer.WritePropertyName("Telemetry");
                    writer.WriteStartArray();
                    foreach (var value in ProgramConfig.GetTelemetryValuesIfInConfig(program.ProgramConfig.Telemetry, lap.Telemetry))
                    {
                        //telemetry object
                        writer.WriteStartObject();
                        foreach (var telemetry in value)
                        {
                            writer.WritePropertyName(telemetry.Key);
                            writer.WriteValue(telemetry.Value);
                        }
                        //end of telemetry object
                        writer.WriteEnd();
                    }
                    writer.WriteEndArray();
                    //end of lap object
                    writer.WriteEndObject();
                }
                writer.WriteEndArray();
            }

            writer.WriteEndObject();
            //data written

            writer.WriteEndObject();
            writer.Close();
            return(sw.ToString());
        }
Beispiel #22
0
        /// <summary>
        /// Writes the current settings to the file
        /// </summary>
        public void WriteSettings()
        {
            //Creates connection to the settings file
            using (var fs = File.Open(SettingsFile, FileMode.Create))
                using (var sw = new StreamWriter(fs))
                    using (var jw = new JsonTextWriter(sw))
                    {
                        //Set up json file formatting
                        jw.Formatting = Formatting.Indented;

                        //Start the base object
                        jw.WriteStartObject();

                        jw.WritePropertyName("channel");
                        jw.WriteValue(_channel);

                        jw.WritePropertyName("botusername");
                        jw.WriteValue(_botUsername);

                        jw.WritePropertyName("botpassword");
                        jw.WriteValue(_botPassword);

                        jw.WritePropertyName("pwentropy");
                        jw.WriteValue(_pwEntropy);

                        //Start writing commands
                        jw.WritePropertyName("commands");
                        jw.WriteStartArray();

                        foreach (var command in Commands.TextCommands)
                        {
                            jw.WriteStartObject();
                            jw.WritePropertyName("name");
                            jw.WriteValue(command.Key);

                            jw.WritePropertyName("response");
                            jw.WriteValue(command.Value);
                            jw.WriteEndObject();
                        }
                        //Finish writing commands
                        jw.WriteEnd();

                        //Start writing censors
                        jw.WritePropertyName("censored");
                        jw.WriteStartArray();

                        foreach (var command in Commands.Censored)
                        {
                            jw.WriteStartObject();
                            jw.WritePropertyName("search");
                            jw.WriteValue(command.Key);

                            jw.WritePropertyName("action");
                            jw.WriteValue(ActionToString(command.Value.Action));

                            jw.WritePropertyName("response");
                            jw.WriteValue(command.Value.Message);
                            jw.WriteEndObject();
                        }

                        //Finish writing censors
                        jw.WriteEnd();

                        //Start writing the perma-mods
                        jw.WritePropertyName("permamods");
                        jw.WriteStartArray();

                        foreach (var permamod in _permaMods)
                        {
                            jw.WriteValue(permamod);
                        }

                        //Finish writing perma-mods
                        jw.WriteEnd();

                        //End base object
                        jw.WriteEndObject();
                    }
        }
Beispiel #23
0
        protected override void CreateJsonForImport()
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;

                writer.WriteStartObject();
                writer.WritePropertyName("ImportGroups");
                writer.WriteStartArray();
                writer.WriteStartObject();
                writer.WritePropertyName("bReplaceExisting");
                writer.WriteValue("true");

                writer.WritePropertyName("ImportSettings");
                writer.WriteStartObject();
                writer.WritePropertyName("AnimSequenceImportData");
                writer.WriteStartObject();
                writer.WritePropertyName("bUseDefaultSampleRate");
                writer.WriteValue("True");
                writer.WritePropertyName("bImportMesh");
                writer.WriteValue("False");
                writer.WritePropertyName("AnimationLength");
                writer.WriteValue("FBXALIT_ExportedTime");
                writer.WritePropertyName("bRemoveRedundantKeys");
                writer.WriteValue("False");
                writer.WritePropertyName("bPreserveLocalTransform");
                writer.WriteValue("False");
                writer.WritePropertyName("bImportMorphTargets");
                writer.WriteValue("True");
                writer.WritePropertyName("bForceFrontXAxis");
                writer.WriteValue("False");
                writer.WritePropertyName("bSetMaterialDriveParameterOnCustomAttribute");
                writer.WriteValue("False");
                writer.WritePropertyName("bDeleteExistingMorphTargetCurves");
                writer.WriteValue("False");
                writer.WritePropertyName("bConvertSceneUnit");
                writer.WriteValue("False");
                writer.WritePropertyName("bDoNotImportCurveWithZero");
                writer.WriteValue("True");
                writer.WritePropertyName("bConvertScene");
                writer.WriteValue("True");
                writer.WritePropertyName("bImportCustomAttribute");
                writer.WriteValue("True");
                writer.WriteEnd();
                writer.WritePropertyName("bImportAnimations");
                writer.WriteValue("True");
                writer.WritePropertyName("MeshTypeToImport");
                writer.WriteValue("FBXIT_Animation");
                writer.WritePropertyName("Skeleton");
                writer.WriteValue("/Game/Animation_Asset/Skeletons/CHR_Main_Character_Skeleton.CHR_Main_Character_Skeleton");
                writer.WritePropertyName("bImportAsSkeletal");
                writer.WriteValue("True");
                writer.WritePropertyName("OriginalImportType");
                writer.WriteValue("FBXIT_SkeletalMesh");
                writer.WritePropertyName("bImportMaterials");
                writer.WriteValue("False");
                writer.WritePropertyName("SkeletalMeshImportData");
                writer.WriteStartObject();
                writer.WritePropertyName("bImportMeshesInBoneHierarchy");
                writer.WriteValue("False");
                writer.WriteEnd();
                writer.WriteEnd();

                writer.WritePropertyName("FileNames");
                writer.WriteStartArray();
                writer.WriteValue(this.GetFullPath());
                writer.WriteEnd();

                writer.WritePropertyName("GroupName");
                writer.WriteValue("LipSync");
                writer.WritePropertyName("DestinationPath");
                writer.WriteValue($"{this.currentObject.Ue4DestinationPath}");
                writer.WritePropertyName("FactoryName");
                writer.WriteValue("FbxFactory");
                writer.WritePropertyName("bSkipReadOnly");
                writer.WriteValue("false");
                writer.WriteEnd();
                writer.WriteEndObject();
            }

            using (StreamWriter fw = File.CreateText(Config.pathToFBXJsonFile))
            {
                fw.WriteLine(sb.ToString());
            }
        }
Beispiel #24
0
        public static string BuildErrorMapsJson(string filename, bool isForShell)
        {
            string errorMapsJson = null;

            ResourceManager rm = new ResourceManager(typeof(FaultCodes));

            PropertyInfo[] pis = typeof(FaultCodes).GetProperties(BindingFlags.Public | BindingFlags.Static);
            IEnumerable <KeyValuePair <string, string> > values =
                from pi in pis
                where pi.PropertyType == typeof(string)
                select new KeyValuePair <string, string>(
                    pi.Name,
                    rm.GetString(pi.Name));
            Dictionary <string, string> FaultCodesDictionary = values.ToDictionary(k => k.Key, v => v.Value);

            List <ExcelObject> lstExcelObject = ImportExcel(filename, isForShell);

            StringBuilder errorMapJsonString   = new StringBuilder();
            StringWriter  stringWriterInstance = new StringWriter(errorMapJsonString);

            using (JsonWriter writer = new JsonTextWriter(stringWriterInstance))
            {
                writer.Formatting = Formatting.Indented;
                writer.WriteStartObject();
                writer.WritePropertyName("SupplierErrorMapModel");
                writer.WriteStartObject();
                int i = 0;
                foreach (var excelObj in lstExcelObject)
                {
                    if (i == 0)
                    {
                        i++;
                        continue;
                    }

                    var supplierError = string.Empty;
                    try
                    {
                        var keyVal = FaultCodesDictionary.Single(f => f.Value == excelObj.ErrorCode);

                        if (!isForShell)
                        {
                            supplierError = excelObj?.SupplierError;
                            writer.WritePropertyName(supplierError); // writing supplier error code as key
                        }
                        else
                        {
                            supplierError = new Random().Next(1, 10).ToString() + keyVal.Value.ToString();
                            writer.WritePropertyName(supplierError); // writing supplier error code as key
                        }

                        writer.WriteStartObject();
                        writer.WritePropertyName("ErrorCode");
                        writer.WriteValue(keyVal.Value.ToString());
                        writer.WritePropertyName("ErrorResourceName");
                        writer.WriteValue(keyVal.Key.ToString());
                        writer.WritePropertyName("SupplierError");
                        writer.WriteValue(supplierError);
                        writer.WritePropertyName("HttpStatusCode");
                        writer.WriteValue(excelObj?.HttpStatusCode);
                        writer.WritePropertyName("Category");
                        writer.WriteValue(excelObj?.ErrorCategory);
                        writer.WritePropertyName("ErrorType");
                        writer.WriteValue(excelObj?.ErrorType);
                        writer.WriteEndObject();
                        i++;
                    }
                    catch (InvalidOperationException)
                    {
                        i++;
                        continue;
                    }
                }

                writer.WriteEnd();
                writer.WriteEndObject();
                Debug.WriteLine(stringWriterInstance);
                errorMapsJson = stringWriterInstance.ToString();
            }

            return(errorMapsJson);
        }
        /// <summary>
        /// Copies the selected items.
        /// </summary>
        public void Copy()
        {
            var selection = SelectedControls;

            if (selection.Count == 0)
            {
                Application.ClipboardText = string.Empty;
                return;
            }

            StringBuilder sb = new StringBuilder(256);
            StringWriter  sw = new StringWriter(sb, CultureInfo.InvariantCulture);

            using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.WriteStartObject();

                jsonWriter.WritePropertyName("Nodes");
                jsonWriter.WriteStartArray();

                for (int i = 0; i < selection.Count; i++)
                {
                    var node = selection[i] as SurfaceNode;
                    if (node == null)
                    {
                        continue;
                    }

                    jsonWriter.WriteStartObject();

                    jsonWriter.WritePropertyName("GroupID");
                    jsonWriter.WriteValue(node.GroupArchetype.GroupID);

                    jsonWriter.WritePropertyName("TypeID");
                    jsonWriter.WriteValue(node.Archetype.TypeID);

                    jsonWriter.WritePropertyName("ID");
                    jsonWriter.WriteValue(node.ID);

                    jsonWriter.WritePropertyName("X");
                    jsonWriter.WriteValue(node.Location.X);

                    jsonWriter.WritePropertyName("Y");
                    jsonWriter.WriteValue(node.Location.Y);

                    if (node.Values != null && node.Values.Length > 0)
                    {
                        jsonWriter.WritePropertyName("Values");
                        jsonWriter.WriteStartArray();

                        for (int j = 0; j < node.Values.Length; j++)
                        {
                            Utilities.Utils.WriteCommonValue(jsonWriter, node.Values[j]);
                        }

                        jsonWriter.WriteEndArray();
                    }

                    if (node.Elements != null && node.Elements.Count > 0)
                    {
                        jsonWriter.WritePropertyName("Boxes");
                        jsonWriter.WriteStartArray();

                        for (int j = 0; j < node.Elements.Count; j++)
                        {
                            if (node.Elements[j] is Box box)
                            {
                                jsonWriter.WriteStartObject();

                                jsonWriter.WritePropertyName("ID");
                                jsonWriter.WriteValue(box.ID);

                                jsonWriter.WritePropertyName("NodeIDs");
                                jsonWriter.WriteStartArray();

                                for (int k = 0; k < box.Connections.Count; k++)
                                {
                                    var target = box.Connections[k];
                                    jsonWriter.WriteValue(target.ParentNode.ID);
                                }

                                jsonWriter.WriteEndArray();

                                jsonWriter.WritePropertyName("BoxIDs");
                                jsonWriter.WriteStartArray();

                                for (int k = 0; k < box.Connections.Count; k++)
                                {
                                    var target = box.Connections[k];
                                    jsonWriter.WriteValue(target.ID);
                                }

                                jsonWriter.WriteEndArray();

                                jsonWriter.WriteEndObject();
                            }
                        }

                        jsonWriter.WriteEndArray();
                    }

                    jsonWriter.WriteEndObject();
                }

                jsonWriter.WriteEndArray();

                jsonWriter.WritePropertyName("Comments");
                jsonWriter.WriteStartArray();

                for (int i = 0; i < selection.Count; i++)
                {
                    var comment = selection[i] as SurfaceComment;
                    if (comment == null)
                    {
                        continue;
                    }

                    jsonWriter.WriteStartObject();

                    jsonWriter.WritePropertyName("Title");
                    jsonWriter.WriteValue(comment.Title);

                    jsonWriter.WritePropertyName("Color");
                    Utilities.Utils.WriteCommonValue(jsonWriter, comment.Color);

                    jsonWriter.WritePropertyName("Bounds");
                    Utilities.Utils.WriteCommonValue(jsonWriter, comment.Bounds);

                    jsonWriter.WriteEndObject();
                }

                jsonWriter.WriteEndArray();

                jsonWriter.WriteEnd();
            }

            Application.ClipboardText = sw.ToString();
        }
Beispiel #26
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);


            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            ProgramConfig = new ViewerConfiguration();

            string     logFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"ARKViewer.log");
            TextWriter logWriter   = null;

            //support quoted command line arguments which doesn't seem to be supported with Environment.GetCommandLineArgs()
            string[] commandArguments = Regex.Split(Environment.CommandLine.Trim(), " (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");

            //remove empty argument entries
            commandArguments = commandArguments.Where(a => string.IsNullOrEmpty(a) == false).ToArray();
            if (commandArguments.Length > 0)
            {
                logWriter = new StreamWriter(logFilename);
                logWriter.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} - ArkViewer Command Line Started: {commandArguments.Length}");

                int argIndex = 0;
                foreach (string arg in commandArguments)
                {
                    logWriter.WriteLine($"\tArg-{argIndex} = {arg}");
                    argIndex++;
                }
            }
            if (commandArguments != null && commandArguments.Length > 1)
            {
                //command line, load save game data for export
                string savePath     = "";
                string saveFilename = "";
                bool   shouldSort   = ProgramConfig.SortCommandLineExport;


                if (commandArguments.Length > 3)
                {
                    //ark save game specified
                    saveFilename = commandArguments[3].ToString().Trim().Replace("\"", "");
                    savePath     = Path.GetDirectoryName(saveFilename);
                }
                else
                {
                    //use last configured save
                    switch (ARKViewer.Program.ProgramConfig.Mode)
                    {
                    case ViewerModes.Mode_SinglePlayer:
                        if (ARKViewer.Program.ProgramConfig.SelectedFile.Length > 0)
                        {
                            savePath     = Path.GetFullPath(ARKViewer.Program.ProgramConfig.SelectedFile);
                            saveFilename = ARKViewer.Program.ProgramConfig.SelectedFile;
                        }

                        break;

                    case ViewerModes.Mode_Offline:
                        if (ARKViewer.Program.ProgramConfig.SelectedFile.Length > 0)
                        {
                            savePath     = Path.GetFullPath(ARKViewer.Program.ProgramConfig.SelectedFile);
                            saveFilename = ARKViewer.Program.ProgramConfig.SelectedFile;
                        }
                        break;

                    case ViewerModes.Mode_Ftp:
                        savePath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), ARKViewer.Program.ProgramConfig.SelectedServer);

                        if (ARKViewer.Program.ProgramConfig.SelectedFile.Length > 0)
                        {
                            saveFilename = Path.Combine(savePath, ARKViewer.Program.ProgramConfig.SelectedFile);
                        }
                        break;

                    default:

                        break;
                    }
                }


                if (File.Exists(saveFilename))
                {
                    try
                    {
                        ArkGameData      gd         = new ArkGameData(saveFilename, loadOnlyPropertiesInDomain: false);
                        List <TribeMap>  allTribes  = new List <TribeMap>();
                        List <PlayerMap> allPlayers = new List <PlayerMap>();

                        if (gd.Update(CancellationToken.None, null, true)?.Success == true)
                        {
                            gd.ApplyPreviousUpdate();

                            //get structures
                            if (commandArguments[1].ToString().Trim().ToLower() == "structures" || commandArguments[1].ToString().Trim().ToLower() == "tribes" || commandArguments[1].ToString().Trim().ToString() == "all")
                            {
                                if (gd.Structures != null && gd.Structures.Count() > 0)
                                {
                                    var structureTribes = gd.Structures.Where(s => s.OwnerName != null && s.TargetingTeam.GetValueOrDefault(0) != 0).Select(s => new TribeMap()
                                    {
                                        TribeId = s.TargetingTeam.GetValueOrDefault(0), TribeName = s.OwnerName
                                    }).Distinct().ToList();

                                    if (structureTribes != null)
                                    {
                                        if (gd.Tribes != null && gd.Tribes.Count() > 0)
                                        {
                                            var serverTribes = gd.Tribes.Where(t => structureTribes.LongCount(s => s.TribeId == t.Id) == 0 && t.Id != 0)
                                                               .Select(i => new TribeMap()
                                            {
                                                TribeId = i.Id, TribeName = i.Name, ContainsLog = i.Logs.Count() > 0
                                            });

                                            if (serverTribes != null)
                                            {
                                                structureTribes.AddRange(serverTribes.ToArray());
                                            }
                                        }
                                        allTribes = structureTribes.Distinct().ToList();
                                    }
                                    else
                                    {
                                        if (gd.Tribes != null && gd.Tribes.Count() > 0)
                                        {
                                            var serverTribes = gd.Tribes.Where(t => structureTribes.LongCount(s => s.TribeId == t.Id) == 0)
                                                               .Select(i => new TribeMap()
                                            {
                                                TribeId = i.Id, TribeName = i.Name
                                            });

                                            allTribes = serverTribes.Distinct().ToList();
                                        }
                                    }

                                    if (gd.Players != null && gd.Players.Count() > 0)
                                    {
                                        var serverPlayers = gd.Players.Select(i => new PlayerMap()
                                        {
                                            TribeId = (long)i.TribeId.GetValueOrDefault(0), PlayerId = (long)i.Id, PlayerName = i.CharacterName != null ? i.CharacterName : i.Name
                                        });
                                        if (serverPlayers != null)
                                        {
                                            foreach (var serverPlayer in serverPlayers.Where(p => p.TribeId == 0))
                                            {
                                                var testTribe = gd.Tribes.Where(t => t.MemberIds.Contains((int)serverPlayer.PlayerId)).FirstOrDefault();
                                                if (testTribe != null)
                                                {
                                                    serverPlayer.TribeId = testTribe.Id;
                                                }
                                            }

                                            allPlayers = serverPlayers.Where(p => p.TribeId != 0).ToList();
                                        }
                                    }

                                    var structurePlayers = gd.Structures.Where(s => s.TargetingTeam.GetValueOrDefault(0) != 0 && s.OwningPlayerName != null && allPlayers.LongCount(c => c.PlayerId == s.OwningPlayerId) == 0).Select(s => new PlayerMap()
                                    {
                                        TribeId = s.TargetingTeam.Value, PlayerId = (long)s.OwningPlayerId, PlayerName = s.OwningPlayerName
                                    }).Distinct().OrderBy(o => o.PlayerName).ToList();
                                    if (structurePlayers != null && structurePlayers.Count() > 0)
                                    {
                                        allPlayers.AddRange(structurePlayers.ToArray());
                                    }


                                    foreach (var tribe in allTribes)
                                    {
                                        int playerCount      = allPlayers.Count(p => p.TribeId == tribe.TribeId);
                                        int tribePlayerCount = gd.Tribes.Where(t => t.Id == tribe.TribeId).Select(m => m.Members).Count();

                                        tribe.PlayerCount    = playerCount > tribePlayerCount ? playerCount : tribePlayerCount;
                                        tribe.StructureCount = gd.Structures.LongCount(s => s.TargetingTeam.GetValueOrDefault(0) == tribe.TribeId);
                                        tribe.TameCount      = gd.TamedCreatures.LongCount(t => t.TargetingTeam == tribe.TribeId);

                                        var tribeTames = gd.NoRafts.Where(t => t.TargetingTeam == tribe.TribeId);
                                        if (tribeTames != null && tribeTames.Count() > 0)
                                        {
                                            TimeSpan noTime = new TimeSpan();

                                            var lastTamedCreature = tribeTames.Where(t => t.TamedAtTime != null).OrderBy(o => o?.TamedForApprox.GetValueOrDefault(noTime).TotalSeconds).FirstOrDefault();
                                            if (lastTamedCreature != null)
                                            {
                                                var tamedTime = lastTamedCreature.TamedForApprox.GetValueOrDefault(noTime);
                                                tribe.LastActive = DateTime.Now.Subtract(tamedTime);
                                            }
                                        }
                                        if (gd.Players != null && gd.Players.Count() > 0)
                                        {
                                            var tribePlayers = gd.Players.Where(p => p.TribeId == tribe.TribeId);
                                            if (tribePlayers != null && tribePlayers.Count() > 0)
                                            {
                                                var lastActivePlayer = tribePlayers.OrderBy(p => p.LastActiveTime).First();
                                                if (lastActivePlayer.LastActiveTime > tribe.LastActive)
                                                {
                                                    tribe.LastActive = lastActivePlayer.LastActiveTime;
                                                }
                                            }
                                        }

                                        if (gd.Tribes != null && gd.Tribes.Count() > 0)
                                        {
                                            var actualTribe = gd.Tribes.FirstOrDefault(t => t.Id == tribe.TribeId);
                                            if (actualTribe != null)
                                            {
                                                if (actualTribe.LastActiveTime > tribe.LastActive)
                                                {
                                                    tribe.LastActive = actualTribe.LastActiveTime;
                                                    tribe.TribeName  = actualTribe.Name;
                                                }
                                                //error reported by @mjfro2 - crash when tribe has no log data
                                                long logCount = actualTribe.Logs == null ? 0 : actualTribe.Logs.Count();
                                                tribe.ContainsLog = logCount > 0;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            gd = null;
                        }

                        string exportFilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        string exportFilename = "";

                        string commandOptionCheck = commandArguments[1].ToString().Trim().ToLower();

                        if (commandArguments.Length > 2)
                        {
                            //export filename
                            exportFilename = commandArguments[2].ToString().Trim().Replace("\"", "");

                            //use path only if "all"
                            if (commandOptionCheck == "all")
                            {
                                exportFilePath = Path.GetDirectoryName(exportFilename);
                                exportFilename = "";
                            }
                        }

                        if (commandOptionCheck == "wild" || commandOptionCheck == "all")
                        {
                            //Wild
                            exportFilename = exportFilename.Length > 0 ? exportFilename : Path.Combine(exportFilePath, "ARKViewer_Export_Wild.json");

                            using (FileStream fs = File.Create(exportFilename))
                            {
                                using (StreamWriter sw = new StreamWriter(fs))
                                {
                                    using (JsonTextWriter jw = new JsonTextWriter(sw))
                                    {
                                        var creatureList = shouldSort ? gd.WildCreatures.OrderBy(o => o.ClassName).Cast <ArkWildCreature>() : gd.WildCreatures;

                                        jw.WriteStartArray();

                                        //Creature, Sex, Lvl, Lat, Lon, HP, Stam, Weight, Speed, Food, Oxygen, Craft, C0, C1, C2, C3, C4, C5
                                        foreach (var creature in creatureList)
                                        {
                                            jw.WriteStartObject();

                                            jw.WritePropertyName("id");
                                            jw.WriteValue(creature.Id);

                                            jw.WritePropertyName("creature");
                                            jw.WriteValue(creature.ClassName);

                                            jw.WritePropertyName("sex");
                                            jw.WriteValue(creature.Gender);

                                            jw.WritePropertyName("lvl");
                                            jw.WriteValue(creature.BaseLevel);

                                            jw.WritePropertyName("lat");
                                            if (creature.Location != null && creature.Location.Latitude != null)
                                            {
                                                jw.WriteValue(creature.Location.Latitude);
                                            }
                                            else
                                            {
                                                jw.WriteValue(0);
                                            }

                                            jw.WritePropertyName("lon");
                                            if (creature.Location != null && creature.Location.Longitude != null)
                                            {
                                                jw.WriteValue(creature.Location.Longitude);
                                            }
                                            else
                                            {
                                                jw.WriteValue(0);
                                            }

                                            jw.WritePropertyName("hp");
                                            jw.WriteValue(creature.BaseStats[0]);

                                            jw.WritePropertyName("stam");
                                            jw.WriteValue(creature.BaseStats[1]);

                                            jw.WritePropertyName("melee");
                                            jw.WriteValue(creature.BaseStats[8]);

                                            jw.WritePropertyName("weight");
                                            jw.WriteValue(creature.BaseStats[7]);

                                            jw.WritePropertyName("speed");
                                            jw.WriteValue(creature.BaseStats[9]);

                                            jw.WritePropertyName("food");
                                            jw.WriteValue(creature.BaseStats[4]);

                                            jw.WritePropertyName("oxy");
                                            jw.WriteValue(creature.BaseStats[3]);

                                            jw.WritePropertyName("craft");
                                            jw.WriteValue(creature.BaseStats[11]);

                                            jw.WritePropertyName("c0");
                                            jw.WriteValue(creature.Colors[0]);

                                            jw.WritePropertyName("c1");
                                            jw.WriteValue(creature.Colors[1]);

                                            jw.WritePropertyName("c2");
                                            jw.WriteValue(creature.Colors[2]);

                                            jw.WritePropertyName("c3");
                                            jw.WriteValue(creature.Colors[3]);

                                            jw.WritePropertyName("c4");
                                            jw.WriteValue(creature.Colors[4]);

                                            jw.WritePropertyName("c5");
                                            jw.WriteValue(creature.Colors[5]);

                                            jw.WritePropertyName("ccc");
                                            if (creature.Location != null)
                                            {
                                                jw.WriteValue($"{creature.Location.X} {creature.Location.Y} {creature.Location.Z}");
                                            }
                                            else
                                            {
                                                jw.WriteValue("");
                                            }

                                            jw.WriteEnd();
                                        }

                                        jw.WriteEndArray();
                                    }
                                }
                            }
                        }
                        if (commandOptionCheck == "tamed" || commandOptionCheck == "all")
                        {
                            //Tamed
                            exportFilename = exportFilename.Length > 0 && commandOptionCheck != "all" ? exportFilename : Path.Combine(exportFilePath, "ARKViewer_Export_Tamed.json");

                            using (FileStream fs = File.Create(exportFilename))
                            {
                                using (StreamWriter sw = new StreamWriter(fs))
                                {
                                    using (JsonTextWriter jw = new JsonTextWriter(sw))
                                    {
                                        var creatureList = shouldSort ? gd.TamedCreatures.OrderBy(o => o.ClassName).Cast <ArkTamedCreature>() : gd.TamedCreatures;

                                        jw.WriteStartArray();

                                        foreach (var creature in creatureList)
                                        {
                                            jw.WriteStartObject();
                                            jw.WritePropertyName("id");
                                            jw.WriteValue(creature.Id);

                                            jw.WritePropertyName("tribeid");
                                            jw.WriteValue(creature.TargetingTeam);

                                            jw.WritePropertyName("tribe");
                                            jw.WriteValue(creature.TribeName);

                                            jw.WritePropertyName("tamer");
                                            jw.WriteValue(creature.TamerName);

                                            jw.WritePropertyName("imprinter");
                                            jw.WriteValue(creature.ImprinterName);


                                            jw.WritePropertyName("imprint");
                                            jw.WriteValue(creature.DinoImprintingQuality);

                                            jw.WritePropertyName("creature");
                                            jw.WriteValue(creature.ClassName);

                                            jw.WritePropertyName("name");
                                            jw.WriteValue(creature.Name != null ? creature.Name : "");


                                            jw.WritePropertyName("sex");
                                            jw.WriteValue(creature.Gender);

                                            jw.WritePropertyName("base");
                                            jw.WriteValue(creature.BaseLevel);


                                            jw.WritePropertyName("lvl");
                                            jw.WriteValue(creature.Level);

                                            jw.WritePropertyName("lat");
                                            if (creature.Location != null && creature.Location.Latitude != null)
                                            {
                                                jw.WriteValue(creature.Location.Latitude);
                                            }
                                            else
                                            {
                                                jw.WriteValue(0);
                                            }

                                            jw.WritePropertyName("lon");
                                            if (creature.Location != null && creature.Location.Longitude != null)
                                            {
                                                jw.WriteValue(creature.Location.Longitude);
                                            }
                                            else
                                            {
                                                jw.WriteValue(0);
                                            }

                                            jw.WritePropertyName("hp-w");
                                            jw.WriteValue(creature.BaseStats[0]);

                                            jw.WritePropertyName("stam-w");
                                            jw.WriteValue(creature.BaseStats[1]);

                                            jw.WritePropertyName("melee-w");
                                            jw.WriteValue(creature.BaseStats[8]);

                                            jw.WritePropertyName("weight-w");
                                            jw.WriteValue(creature.BaseStats[7]);

                                            jw.WritePropertyName("speed-w");
                                            jw.WriteValue(creature.BaseStats[9]);

                                            jw.WritePropertyName("food-w");
                                            jw.WriteValue(creature.BaseStats[4]);

                                            jw.WritePropertyName("oxy-w");
                                            jw.WriteValue(creature.BaseStats[3]);

                                            jw.WritePropertyName("craft-w");
                                            jw.WriteValue(creature.BaseStats[11]);

                                            jw.WritePropertyName("hp-t");
                                            jw.WriteValue(creature.TamedStats[0]);

                                            jw.WritePropertyName("stam-t");
                                            jw.WriteValue(creature.TamedStats[1]);

                                            jw.WritePropertyName("melee-t");
                                            jw.WriteValue(creature.TamedStats[8]);

                                            jw.WritePropertyName("weight-t");
                                            jw.WriteValue(creature.TamedStats[7]);

                                            jw.WritePropertyName("speed-t");
                                            jw.WriteValue(creature.TamedStats[9]);

                                            jw.WritePropertyName("food-t");
                                            jw.WriteValue(creature.TamedStats[4]);

                                            jw.WritePropertyName("oxy-t");
                                            jw.WriteValue(creature.TamedStats[3]);

                                            jw.WritePropertyName("craft-t");
                                            jw.WriteValue(creature.TamedStats[11]);


                                            jw.WritePropertyName("c0");
                                            jw.WriteValue(creature.Colors[0]);

                                            jw.WritePropertyName("c1");
                                            jw.WriteValue(creature.Colors[1]);

                                            jw.WritePropertyName("c2");
                                            jw.WriteValue(creature.Colors[2]);

                                            jw.WritePropertyName("c3");
                                            jw.WriteValue(creature.Colors[3]);

                                            jw.WritePropertyName("c4");
                                            jw.WriteValue(creature.Colors[4]);

                                            jw.WritePropertyName("c5");
                                            jw.WriteValue(creature.Colors[5]);

                                            jw.WritePropertyName("mut-f");
                                            jw.WriteValue(creature.RandomMutationsFemale);

                                            jw.WritePropertyName("mut-m");
                                            jw.WriteValue(creature.RandomMutationsMale);

                                            jw.WritePropertyName("cryo");
                                            jw.WriteValue(creature.IsCryo);

                                            jw.WritePropertyName("viv");
                                            jw.WriteValue(creature.IsVivarium);

                                            jw.WritePropertyName("ccc");
                                            if (creature.Location != null)
                                            {
                                                jw.WriteValue($"{creature.Location.X} {creature.Location.Y} {creature.Location.Z}");
                                            }
                                            else
                                            {
                                                jw.WriteValue("");
                                            }

                                            jw.WriteEnd();
                                        }

                                        jw.WriteEndArray();
                                    }
                                }
                            }
                        }

                        if (commandOptionCheck == "structures" || commandOptionCheck == "all")
                        {
                            //Structures
                            exportFilename = exportFilename.Length > 0 && commandOptionCheck != "all" ? exportFilename : Path.Combine(exportFilePath, "ARKViewer_Export_Structures.json");

                            //Player, Tribe, Structure, Lat, Lon
                            using (FileStream fs = File.Create(exportFilename))
                            {
                                using (StreamWriter sw = new StreamWriter(fs))
                                {
                                    using (JsonTextWriter jw = new JsonTextWriter(sw))
                                    {
                                        jw.WriteStartArray();

                                        foreach (var structure in gd.Structures)
                                        {
                                            jw.WriteStartObject();

                                            jw.WritePropertyName("tribeid");
                                            jw.WriteValue(structure.TargetingTeam.GetValueOrDefault(0));

                                            jw.WritePropertyName("playerid");
                                            if (structure.OwningPlayerId == structure.TargetingTeam.GetValueOrDefault(0))
                                            {
                                                jw.WriteValue(0);
                                            }
                                            else
                                            {
                                                jw.WriteValue(structure.OwningPlayerId.GetValueOrDefault(0));
                                            }


                                            jw.WritePropertyName("tribe");
                                            if (allTribes.Count(t => t.TribeId == structure.TargetingTeam.GetValueOrDefault(0)) > 0)
                                            {
                                                jw.WriteValue(allTribes.First(t => t.TribeId == structure.TargetingTeam.GetValueOrDefault(0)).TribeName);
                                            }
                                            else
                                            {
                                                jw.WriteValue("");
                                            }


                                            jw.WritePropertyName("player");
                                            jw.WriteValue(structure.OwningPlayerName == "null" ? "" : structure.OwningPlayerName);

                                            jw.WritePropertyName("struct");
                                            jw.WriteValue(structure.ClassName);

                                            jw.WritePropertyName("lat");
                                            if (structure.Location != null && structure.Location.Latitude != null)
                                            {
                                                jw.WriteValue(structure.Location.Latitude);
                                            }
                                            else
                                            {
                                                jw.WriteValue(0);
                                            }


                                            jw.WritePropertyName("lon");
                                            if (structure.Location != null && structure.Location.Longitude != null)
                                            {
                                                jw.WriteValue(structure.Location.Longitude);
                                            }
                                            else
                                            {
                                                jw.WriteValue(0);
                                            }

                                            jw.WritePropertyName("ccc");
                                            if (structure.Location != null)
                                            {
                                                jw.WriteValue($"{structure.Location.X} {structure.Location.Y} {structure.Location.Z}");
                                            }
                                            else
                                            {
                                                jw.WriteValue("");
                                            }


                                            jw.WriteEnd();
                                        }

                                        jw.WriteEndArray();
                                    }
                                }
                            }
                        }


                        if (commandOptionCheck == "tribes" || commandOptionCheck == "all")
                        {
                            //Tribes
                            exportFilename = exportFilename.Length > 0 && commandOptionCheck != "all" ? exportFilename : Path.Combine(exportFilePath, "ARKViewer_Export_Tribes.json");

                            //Id, Name, Players, Tames, Structures, Last Active
                            using (FileStream fs = File.Create(exportFilename))
                            {
                                using (StreamWriter sw = new StreamWriter(fs))
                                {
                                    using (JsonTextWriter jw = new JsonTextWriter(sw))
                                    {
                                        jw.WriteStartArray();

                                        foreach (var playerTribe in allTribes)
                                        {
                                            jw.WriteStartObject();

                                            jw.WritePropertyName("tribeid");
                                            jw.WriteValue(playerTribe.TribeId);

                                            jw.WritePropertyName("tribe");
                                            jw.WriteValue(playerTribe.TribeName);

                                            jw.WritePropertyName("players");
                                            jw.WriteValue(playerTribe.PlayerCount);

                                            jw.WritePropertyName("tames");
                                            jw.WriteValue(playerTribe.TameCount);

                                            jw.WritePropertyName("structures");
                                            jw.WriteValue(playerTribe.StructureCount);

                                            jw.WritePropertyName("active");
                                            jw.WriteValue(playerTribe.LastActive);


                                            jw.WriteEnd();
                                        }

                                        jw.WriteEndArray();
                                    }
                                }
                            }
                        }


                        if (commandOptionCheck == "all" || commandOptionCheck == "players")
                        {
                            //Players
                            exportFilename = exportFilename.Length > 0 && commandOptionCheck != "all" ? exportFilename : Path.Combine(exportFilePath, "ARKViewer_Export_Players.json");

                            //Id, Name, Tribe, Sex, Lvl, Lat, Lon, HP, Stam, Melee, Weight, Speed, Food, Water, Oxygen, Crafting, Fortitude, Steam, Last Online
                            using (FileStream fs = File.Create(exportFilename))
                            {
                                using (StreamWriter sw = new StreamWriter(fs))
                                {
                                    using (JsonTextWriter jw = new JsonTextWriter(sw))
                                    {
                                        jw.WriteStartArray();

                                        foreach (var player in gd.Players)
                                        {
                                            jw.WriteStartObject();

                                            jw.WritePropertyName("playerid");
                                            jw.WriteValue(player.Id);

                                            jw.WritePropertyName("steam");
                                            jw.WriteValue(player.Name);

                                            jw.WritePropertyName("name");
                                            jw.WriteValue(player.CharacterName);

                                            jw.WritePropertyName("tribeid");
                                            jw.WriteValue(player.TribeId);

                                            jw.WritePropertyName("tribe");
                                            if (player.Tribe != null && player.Tribe.Name != null)
                                            {
                                                jw.WriteValue(player.Tribe.Name);
                                            }
                                            else
                                            {
                                                jw.WriteValue("");
                                            }

                                            jw.WritePropertyName("sex");
                                            jw.WriteValue(player.Gender);

                                            jw.WritePropertyName("lvl");
                                            jw.WriteValue(player.CharacterLevel);

                                            jw.WritePropertyName("lat");
                                            if (player.Location != null)
                                            {
                                                jw.WriteValue(player.Location.Latitude);
                                            }
                                            else
                                            {
                                                jw.WriteValue(0);
                                            }

                                            jw.WritePropertyName("lon");
                                            if (player.Location != null)
                                            {
                                                jw.WriteValue(player.Location.Longitude);
                                            }
                                            else
                                            {
                                                jw.WriteValue(0);
                                            }


                                            //0=health
                                            //1=stamina
                                            //2=torpor
                                            //3=oxygen
                                            //4=food
                                            //5=water
                                            //6=temperature
                                            //7=weight
                                            //8=melee damage
                                            //9=movement speed
                                            //10=fortitude
                                            //11=crafting speed
                                            jw.WritePropertyName("hp");
                                            jw.WriteValue(player.Stats[0]);

                                            jw.WritePropertyName("stam");
                                            jw.WriteValue(player.Stats[1]);

                                            jw.WritePropertyName("melee");
                                            jw.WriteValue(player.Stats[8]);

                                            jw.WritePropertyName("weight");
                                            jw.WriteValue(player.Stats[7]);

                                            jw.WritePropertyName("speed");
                                            jw.WriteValue(player.Stats[9]);

                                            jw.WritePropertyName("food");
                                            jw.WriteValue(player.Stats[4]);

                                            jw.WritePropertyName("water");
                                            jw.WriteValue(player.Stats[5]);

                                            jw.WritePropertyName("oxy");
                                            jw.WriteValue(player.Stats[3]);

                                            jw.WritePropertyName("craft");
                                            jw.WriteValue(player.Stats[11]);

                                            jw.WritePropertyName("fort");
                                            jw.WriteValue(player.Stats[10]);

                                            jw.WritePropertyName("active");
                                            jw.WriteValue(player.LastActiveTime);

                                            jw.WritePropertyName("ccc");
                                            if (player.Location != null)
                                            {
                                                jw.WriteValue($"{player.Location.X} {player.Location.Y} {player.Location.Z}");
                                            }
                                            else
                                            {
                                                jw.WriteValue("");
                                            }


                                            jw.WriteEnd();
                                        }

                                        jw.WriteEndArray();
                                    }
                                }
                            }
                        }

                        //success
                        Environment.ExitCode = 0;
                    }
                    catch (Exception ex)
                    {
                        string traceLog     = ex.StackTrace;
                        string errorMessage = ex.Message;

                        try
                        {
                            StringBuilder errorData = new StringBuilder();

                            errorData.AppendLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            errorData.AppendLine($"Error: {errorMessage}");
                            errorData.AppendLine($"Trace: {traceLog}");
                            errorData.AppendLine("");
                            if (logWriter == null)
                            {
                                logWriter = new StreamWriter(logFilename);
                            }
                            logWriter.Write(errorData.ToString());
                        }
                        catch
                        {
                            //couldn't write to error.log
                        }

                        Console.Out.WriteLine($"Error : {ex.Message.ToString()}");

                        //error
                        Environment.ExitCode = -1;
                    }
                }
                else
                {
                    //no save file found or inaccessible
                    if (logWriter == null)
                    {
                        logWriter = new StreamWriter(logFilename);
                    }
                    logWriter.Write($"Unable to find or access save game file: {saveFilename}");
                    Environment.ExitCode = -2;
                }

                if (logWriter != null)
                {
                    logWriter.Close();
                    logWriter.Dispose();
                }

                Application.Exit();
            }
            else
            {
                //no command line options, run viewer


                Application.Run(new frmViewer());
            }
        }
        private static void Go(Engine engine)
        {
            var developerPerksDefinitionClass = engine.GetClass("WillowGame.DeveloperPerksDefinition");

            if (developerPerksDefinitionClass == null)
            {
                throw new InvalidOperationException();
            }

            dynamic developerPerks = engine.Objects.FirstOrDefault(o => o.IsA(developerPerksDefinitionClass) &&
                                                                   o.GetName().StartsWith("Default__") == false);

            if (developerPerks == null)
            {
                throw new InvalidOperationException();
            }

            using (var output = new StreamWriter("Developer Perks.json", false, Encoding.Unicode))
                using (var writer = new JsonTextWriter(output))
                {
                    writer.Indentation = 2;
                    writer.IndentChar  = ' ';
                    writer.Formatting  = Formatting.Indented;

                    writer.WriteStartObject();

                    writer.WritePropertyName("developers");
                    writer.WriteStartArray();
                    foreach (var developerInfo in developerPerks.DeveloperInfo)
                    {
                        writer.WriteStartObject();

                        writer.WritePropertyName("gamertag");
                        writer.WriteValue(developerInfo.Gamertag);

                        writer.WritePropertyName("unique_id");
                        writer.WriteValue(developerInfo.UniqueId);

                        writer.WritePropertyName("platform");
                        writer.WriteValue(((DeveloperPerksPlatforms)developerInfo.Platform).ToString());

                        if (developerInfo.UnlocksGamerpics != null &&
                            developerInfo.UnlocksGamerpics.Length > 0)
                        {
                            writer.WritePropertyName("unlock_gamerpics");
                            writer.WriteStartArray();
                            foreach (var b in developerInfo.UnlocksGamerpics)
                            {
                                writer.WriteValue((byte)b);
                            }
                            writer.WriteEnd();
                        }

                        writer.WritePropertyName("eligible_for_gearbox_customizations");
                        writer.WriteValue(developerInfo.bEligibleForGearboxCustomizations);

                        writer.WriteEndObject();
                    }
                    writer.WriteEndArray();

                    writer.WritePropertyName("perks");
                    writer.WriteStartArray();
                    foreach (var perkInfo in developerPerks.PerkInfo)
                    {
                        writer.WriteStartObject();

                        writer.WritePropertyName("button_chain");
                        writer.WriteStartArray();
                        foreach (var button in perkInfo.ButtonChain)
                        {
                            writer.WriteValue(button);
                        }
                        writer.WriteEndArray();

                        writer.WritePropertyName("command");
                        writer.WriteValue(perkInfo.Command);

                        writer.WritePropertyName("must_be_developer");
                        writer.WriteValue(perkInfo.bMustBeDeveloper);

                        writer.WriteEndObject();
                    }
                    writer.WriteEndArray();

                    writer.WritePropertyName("developer_customization_unlocks");
                    writer.WriteStartArray();
                    foreach (var developerCustomizationUnlock in developerPerks.DeveloperCustomizationUnlocks)
                    {
                        if (developerCustomizationUnlock != null)
                        {
                            writer.WriteValue(developerCustomizationUnlock.GetPath());
                        }
                    }
                    writer.WriteEndArray();

                    writer.WriteEndObject();
                    writer.Flush();
                }
        }
        // submit our data to the database, sinc to the watch and exit
        private void saveOnClick(object sender, EventArgs e)
        {
            // gather all data (excluding list data)
            string perscription = ((AutoCompleteTextView)FindViewById(Resource.Id.autoCompletePerscription)).Text;
            string startDate    = ((EditText)FindViewById(Resource.Id.perscriptionStartTime)).Text;
            string endDate      = ((EditText)FindViewById(Resource.Id.perscriptionEndTime)).Text;
            string dosage       = ((EditText)FindViewById(Resource.Id.txtDosage)).Text;
            string form         = (string)((Spinner)FindViewById(Resource.Id.formselect)).SelectedItem;
            string takewith     = (string)((Spinner)FindViewById(Resource.Id.instructionselect)).SelectedItem;
            string Interval     = (string)((Spinner)FindViewById(Resource.Id.intervalselect)).SelectedItem;

            // validate data (excluding list data) already validated
            Regex         r             = new Regex("^[0-9][0-9]/(0[0-9])|(1[0-2])/([0-2][0-9])|(3[0-1])");
            bool          error_occured = false;
            StringBuilder error         = new StringBuilder("Incorrect/missing inputs for ");

            if (!r.IsMatch(startDate))
            {
                error_occured = true;
                error.Append("Perscription start time");
            }
            if (endDate.Length > 0 && !r.IsMatch(endDate))
            {
                error_occured = true;
                error.Append("Perscription end time");
            }
            if (perscription.Length == 0)
            {
                error_occured = true;
                error.Append("Perscription ");
            }
            if (dosage.Length == 0 || decimal.Parse(dosage) == 0)
            {
                error_occured = true;
                error.Append("Dosage ");
            }
            if (intervalAdapter.Count == 0)
            {
                error_occured = true;
                error.Append("Intervals ");
            }

            if (error_occured)
            {
                Toast tost = Toast.MakeText(this, error.ToString(), ToastLength.Long);
                tost.Show();
                return;
            }

            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw)) {
                writer.Formatting = Formatting.Indented;

                writer.WriteStartObject();
                writer.WritePropertyName("user");
                writer.WriteValue("*****@*****.**");// temporary until google authentication complete
                writer.WritePropertyName("perscription");
                writer.WriteValue(perscription);
                writer.WritePropertyName("start_date");
                writer.WriteValue(startDate);
                writer.WritePropertyName("end_date");
                writer.WriteValue(endDate);
                writer.WritePropertyName("dosage");
                writer.WriteValue(dosage);
                writer.WritePropertyName("form");
                writer.WriteValue(form);
                writer.WritePropertyName("take_with");
                writer.WriteValue(takewith);
                writer.WritePropertyName("Interval");
                writer.WriteValue(Interval);
                writer.WritePropertyName("Intervals");
                writer.WriteStartArray();
                for (int x = 0; x < intervalAdapter.Count; x++)
                {
                    writer.WriteValue(intervalAdapter.GetItem(x));
                }
                writer.WriteEnd();
                writer.WriteEndObject();
            }

            // nowhere to send to yet
            //sendRequest(sb.ToString());

            // exit
            Intent i = new Intent();

            i.PutExtra("Perscription", sb.ToString());
            SetResult(Result.Ok, i);
            Finish();
        }