public static void SaveBuildingInventory(string reality, Player player) { if (string.IsNullOrWhiteSpace(reality) || player == null) { Debug.LogError("Reality is null or player is null! Both must not be null!"); return; } // Get all the items in the building inventory... var items = player.BuildingInventory.GetItems().ToArray(); if (items == null) { Debug.LogError("Inventory building items for player '" + player.Name + "' are null!"); return; } // Get path... string path = OutputUtils.RealitySaveDirectory + reality + OutputUtils.PlayerSaveDirectory + player.Name + OutputUtils.BuildingInventorySaveFile; // Save to file... OutputUtils.ObjectToFile(items, path); // Done! Debug.Log("Saved " + items.Length + " inventory building items to '" + path + "'"); }
protected void debugLoggerShowCallback(IWrite iWrite, string cmdName, object[] cmdArguments) { iWrite.WriteLine( OutputUtils.FormatField("Name", 10) + OutputUtils.FormatField("Triggered", 10) + OutputUtils.FormatField("Logged", 10) + OutputUtils.FormatField("Dropped", 10) + OutputUtils.FormatField("Log type", 10) + OutputUtils.FormatField("Latest", 24) + OutputUtils.FormatField("Oldest", 24) + OutputUtils.FormatField("Stamped", 10) ); iWrite.WriteLine("-----------------------------------------------------------------------------------------------------------------------"); bool isEmpty = true; foreach (ILogger logger in Resources.Loggers) { isEmpty = false; iWrite.WriteLine( OutputUtils.FormatField(logger.GetName(), 10) + OutputUtils.FormatField(logger.GetCountTrigger(), 10) + OutputUtils.FormatField(logger.GetCountLog(), 10) + OutputUtils.FormatField(logger.GetCountDropped(), 10) + OutputUtils.FormatField(logger.GetLogType().ToString(), 10) + OutputUtils.FormatField(logger.GetLatest().ToString(), 24) + OutputUtils.FormatField(logger.GetOldest().ToString(), 24) + OutputUtils.FormatField(logger.TimeStamped().ToString(), 10) ); } if (isEmpty) { iWrite.WriteLine("No loggers"); } }
protected void debugProducerShowCallback(IWrite iWrite, string cmdName, object[] cmdArguments) { System.Collections.ArrayList names; System.Collections.ArrayList values; int entry = 0; int columnSize = 12; bool isEmpty = true; iWrite.WriteLine(); foreach (IResourceProducer producer in Resources.Producers) { producer.GetEventCounters(out names, out values); isEmpty = false; if (entry == 0) { names.Insert(0, "Name"); CommandLineInterface.printTableHeader((JQuant.IWrite) this, names, columnSize); } values.Insert(0, OutputUtils.FormatField(producer.Name, columnSize)); CommandLineInterface.printValues((JQuant.IWrite) this, values, columnSize); entry++; } if (isEmpty) { iWrite.WriteLine("No producers"); } }
public static void SaveHolding(string reality, Player player) { if (string.IsNullOrEmpty(reality)) { Debug.LogError("Reality is null or em empty, cannot save held item."); return; } if (player == null) { Debug.LogError("Null player, cannot perform IO operation for held item."); return; } // Get file path. string path = OutputUtils.RealitySaveDirectory + reality + OutputUtils.HeldItemSaveFile; // Get the player holding monobehaviour. PlayerHolding holding = player.Holding; if (holding.Item == null) { OutputUtils.ObjectToFile(null, path); } else { ItemSaveData sd = holding.Item.GetSaveData(); OutputUtils.ObjectToFile(sd, path); } // Done! }
protected void debugPrintResourcesNameAndStats(IWrite iWrite, System.Collections.ArrayList list) { int entry = 0; int columnSize = 8; bool isEmpty = true; iWrite.WriteLine(); foreach (INamedResource resNamed in list) { isEmpty = false; IResourceStatistics resStat = (IResourceStatistics)resNamed; System.Collections.ArrayList names; System.Collections.ArrayList values; resStat.GetEventCounters(out names, out values); if (entry == 0) { names.Insert(0, "Name"); CommandLineInterface.printTableHeader(iWrite, names, columnSize); } values.Insert(0, OutputUtils.FormatField(resNamed.Name, columnSize)); CommandLineInterface.printValues(iWrite, values, columnSize); entry++; } if (isEmpty) { System.Console.WriteLine("Table is empty - no resources registered"); } }
public static void SaveKeyBindings() { string path = OutputUtils.InputSaveKeyBindings; Debug.Log("Saving key bindings to '" + path + "'..."); OutputUtils.ObjectToFile(keyBindings, path); // Will be auto }
protected void debugThreadShowCallback(IWrite iWrite, string cmdName, object[] cmdArguments) { iWrite.WriteLine(); iWrite.WriteLine( OutputUtils.FormatField("Name", 10) + OutputUtils.FormatField("State", 14) + OutputUtils.FormatField("Ticks", 10) ); iWrite.WriteLine("-------------------------------------------"); bool isEmpty = true; foreach (IThread iThread in Resources.Threads) { isEmpty = false; iWrite.WriteLine( OutputUtils.FormatField(iThread.Name, 10) + OutputUtils.FormatField(EnumUtils.GetDescription(iThread.GetState()), 14) + OutputUtils.FormatField(iThread.GetLongestJob(), 10) ); } if (isEmpty) { iWrite.WriteLine("No threads"); } int workerThreads; int completionPortThreads; System.Threading.ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); iWrite.WriteLine("workerThreads=" + workerThreads + ",completionPortThreads=" + completionPortThreads); }
public static void SavePlayerState(string reality, Player player) { if (string.IsNullOrEmpty(reality)) { Debug.LogError("Reality is null or em empty, cannot save player state."); return; } if (player == null) { Debug.LogError("Null player, cannot save player state."); return; } // Make path. string path = OutputUtils.RealitySaveDirectory + reality + OutputUtils.PlayerSaveDirectory + player.Name + OutputUtils.PlayerStateFile; Debug.Log("Saving state of player '" + player.Name + "' to '" + path + "'..."); // Make save data. PlayerSaveData sd = new PlayerSaveData(); sd.Set(player); // Save to file. OutputUtils.ObjectToFile(sd, path); }
protected static string OrderPair2String(MarketSimulation.OrderPair op, int columnSize) { string res = "" + op.price + ":" + op.size + " "; res = OutputUtils.FormatField(res, columnSize); return(res); }
/// <summary> /// Execute the method that save the output /// </summary> /// <param name="exception">set it true if you call this method on an unkown error</param> public static void Finish(Boolean exception) { //stop the stopwatch _globalTime.Stop(); //save all info that will be used by OutputUtils to write global info OutputUtils.Global.xmlNode = ConfigUtils.Global; OutputUtils.Global.endTime = DateTime.Now; OutputUtils.Global.duration = _globalTime.ElapsedMilliseconds; //close window(s) Thread.Sleep(2000); string windowToCloseRegEx = ConfigUtils.WindowTitleToClose; if (windowToCloseRegEx != "") { SystemUtils.User32.CloseWindow(windowToCloseRegEx); } Thread.Sleep(2000); if (_processToKillRegEx != "") { processesAfterAlexa = SystemUtils.ProcessUtils.GetUserProcessesByRegEx(userDomain, userName, _processToKillRegEx); foreach (UInt32 pidAfterAlexa in processesAfterAlexa) { bool pidFound = false; foreach (UInt32 pidBeforeAlexa in processesBeforeAlexa) { if (pidAfterAlexa == pidBeforeAlexa) { pidFound = true; } } if (pidFound == false) { SystemUtils.ProcessUtils.processesToKill.Add(pidAfterAlexa); } } //loop through all processes to kill foreach (UInt32 pidToKill in SystemUtils.ProcessUtils.processesToKill) { //kill the process SystemUtils.ProcessUtils.KillProcess(pidToKill); } } //save the output file and exit OutputUtils.Finish(exception); //if exit is true then exit with exitcode 3 //if (exit) Environment.Exit(3); }
protected void printIntStatistics(IWrite iWrite, IntStatistics statistics) { iWrite.WriteLine(OutputUtils.FormatField(statistics.Name, 8) + OutputUtils.FormatField(statistics.Mean, 8) + OutputUtils.FormatField(statistics.Full().ToString(), 8) + OutputUtils.FormatField(statistics.Size, 8) + OutputUtils.FormatField(statistics.Count, 8) ); }
public static void SaveWorldState(World world) { // Get world state object. WorldSaveState sd = new WorldSaveState(world); string path = OutputUtils.RealitySaveDirectory + world.RealityName + OutputUtils.WorldStateSaveFile; OutputUtils.ObjectToFile(sd, path); Debug.Log("Saved world state to '" + path + "'"); }
protected void printIntStatisticsHeader(IWrite iWrite) { iWrite.WriteLine(OutputUtils.FormatField("Name", 8) + OutputUtils.FormatField("Mean", 8) + OutputUtils.FormatField("Ready", 8) + OutputUtils.FormatField("Size", 8) + OutputUtils.FormatField("Count", 8) ); iWrite.WriteLine("----------------------------------------------------------------"); }
private void outputToolStripMenuItem_Click(object sender, EventArgs e) { FolderBrowserDialog fd = new FolderBrowserDialog(); if (fd.ShowDialog(this) == DialogResult.OK) { OutputUtils ou = new OutputUtils(); ou.Output(fd.SelectedPath); } }
protected void printIntMaxMin(IWrite iWrite, IntMaxMin maxMin) { iWrite.WriteLine(OutputUtils.FormatField(maxMin.Name, 8) + OutputUtils.FormatField(maxMin.Max, 8) + OutputUtils.FormatField(maxMin.Min, 8) + OutputUtils.FormatField(maxMin.Full().ToString(), 8) + OutputUtils.FormatField(maxMin.Size, 8) + OutputUtils.FormatField(maxMin.Count, 8) ); }
protected string debugJsonTest() { TestJsonElement[] els = new TestJsonElement[2]; els[0] = new TestJsonElement(1, 2); els[1] = new TestJsonElement(3, 4); string json = OutputUtils.GetJSON(els, "els"); return(json); }
protected void printIntMaxMinHeader(IWrite iWrite) { iWrite.WriteLine(OutputUtils.FormatField("Name", 8) + OutputUtils.FormatField("Max", 8) + OutputUtils.FormatField("Min", 8) + OutputUtils.FormatField("Ready", 8) + OutputUtils.FormatField("Size", 8) + OutputUtils.FormatField("Count", 8) ); iWrite.WriteLine("----------------------------------------------------------------"); }
public static void SaveLanguage(Language lang) { if (lang == null) { return; } if (!Application.isEditor) { return; } string path = GetLanguagePath(lang.Name); OutputUtils.ObjectToFile(lang, path); }
public static void SaveDefinition(LanguageDefinition def) { if (def == null) { return; } if (!Application.isEditor) { return; } string path = GetDefinitionPath(def.Name); OutputUtils.ObjectToFile(def, path); }
public static void printValues(IWrite iWrite, System.Collections.ArrayList values, int[] columns) { string outputS = ""; for (int i = 0; i < values.Count; i++) { string s = ""; int columnSize = columns[i]; // add blank up to columnSize s = OutputUtils.FormatField(values[i].ToString(), columnSize); outputS += s; } iWrite.WriteLine(outputS); }
public static void printTableHeader(IWrite iWrite, System.Collections.ArrayList names, int[] columns) { int line = 0; bool printed = true; int maxOutputSLength = 0; while (printed) { printed = false; string outputS = ""; for (int i = 0; i < names.Count; i++) { int columnSize = columns[i]; int charsInColumn = columnSize - 1; string s = ""; string name = names[i].ToString(); // get (columnSize-1) chars from the name[i] if (name.Length > line * charsInColumn) { int temp = System.Math.Min(name.Length - line * charsInColumn, charsInColumn); s = name.Substring(line * charsInColumn, temp); printed = true; } // add blank up to columnSize s = OutputUtils.FormatField(s, columnSize); outputS += s; } if (printed) { iWrite.WriteLine(outputS); if (maxOutputSLength < outputS.Length) { maxOutputSLength = outputS.Length; } } line++; } printSeparator(iWrite, maxOutputSLength); }
public static void SaveGear(string reality, Player player) { if (string.IsNullOrEmpty(reality)) { Debug.LogError("Reality is null or em empty, cannot save gear items."); return; } if (player == null) { Debug.LogError("Null player, cannot perform IO operation for gear items."); return; } // Get all the slots, and then get save data from each slot. List <GearSaveData> saveData = new List <GearSaveData>(); Debug.Log("Saving " + (player.GearMap.Count - 1) + " gear slots..."); foreach (var slotName in player.GearMap.Keys) { if (slotName == "Hands") { continue; } BodyGear bg = player.GearMap[slotName]; GearSaveData sd = bg.GetSaveData(); if (sd == null) { Debug.LogError("Gear slot '" + slotName + "' gave null save data!"); continue; } saveData.Add(sd); } // Make array. GearSaveData[] array = saveData.ToArray(); saveData.Clear(); // Get file path. string path = OutputUtils.RealitySaveDirectory + reality + OutputUtils.GearItemSaveFile; // Save to file. OutputUtils.ObjectToFile(array, path); }
public static void SaveFurniture(string reality, params Furniture[] f) { if (string.IsNullOrWhiteSpace(reality)) { Debug.LogError("Reality name is null or empty! Cannot save furniture!"); return; } // Get file path... string path = OutputUtils.RealitySaveDirectory + reality + OutputUtils.FurnitureSaveDirectory + OutputUtils.FurnitureSaveFile; // Make save datas... var saves = GetSaveData(f); // Save to file! OutputUtils.ObjectToFile(saves, path); Debug.Log(string.Format("Saved {0}/{1} placed furniture objects to '{2}'", saves.Length, f.Length, path)); }
public static void ItemsToFile(string reality, params Item[] items) { items = FilterItems(items); ItemSaveData[] saveData = new ItemSaveData[items.Length]; for (int i = 0; i < items.Length; i++) { items[i].RequestDataUpdate(); ItemSaveData sd = ItemToSaveData(items[i]); saveData[i] = sd; } string filePath = OutputUtils.RealitySaveDirectory + reality + OutputUtils.WorldItemSaveFile; Debug.Log("Saving " + items.Length + " items to '" + filePath + "'"); OutputUtils.ObjectToFile(saveData, filePath, new JsonSerializerSettings() { Formatting = Formatting.Indented, ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); }
// IO for inventory and player. // EVERYTHING must be called from the SERVER ONLY! public static void SaveInventory(string reality) { if (string.IsNullOrEmpty(reality)) { Debug.LogError("Reality is null or em empty, cannot save inventory items."); return; } // Make array of inventory item data. List <InventoryItemData> items = PlayerInventory.inv.Inventory.Contents; InventoryItemData[] array = items.ToArray(); items = null; // Get save file path. string path = OutputUtils.RealitySaveDirectory + reality + OutputUtils.InventoryItemSaveFile; Debug.Log("Saving " + array.Length + " inventory items to '" + path + "'"); // Save to file. OutputUtils.ObjectToFile(array, path); }
public HttpResponseMessage SendToUser() { /* * SqlConnection Conn = new SqlConnection(KeyWords.DBconnectionString); * await Conn.OpenAsync(); * SqlCommand Cmd = Conn.CreateCommand(); * Cmd.CommandText = this.query; * //Cmd.CommandTimeout = KeyWords.DatabaseSearchTimeout == null || KeyWords.DatabaseSearchTimeout == "" ? 600 : Int32.Parse(KeyWords.DatabaseSearchTimeout); * Cmd.CommandTimeout = Int32.Parse(KeyWords.DatabaseSearchTimeout); * //SqlDataReader reader = await Cmd.ExecuteReaderAsync(); * var Adapter = new SqlDataAdapter(Cmd); * Adapter.Fill(ResultsDataSet); * Conn.Close(); */ RunQuery(); //BinaryFormatter fmt = new BinaryFormatter(); Action <Stream, HttpContent, TransportContext> WriteToStream = null; BinaryFormatter fmt; // do not add the SQL query as a second table in vo services and csv/txt/fits formats. if (!format.Contains("csv") && !format.Contains("txt") && !format.Contains("text/plain") && !format.Contains("fits") && queryType != KeyWords.SDSSFields && queryType != KeyWords.ConeSearchQuery && queryType != KeyWords.SIAP) { AddQueryTable(ResultsDataSet);// this adds to "ResultsDataSet" a new Table that shows the sql command. } string FileType = ""; ExtraInfo.TryGetValue("FormatFromUser", out FileType); string SaveResult = ""; ExtraInfo.TryGetValue("SaveResult", out SaveResult); switch (format) { case "csv": case "txt": case "text/plain": ResultsDataSet.RemotingFormat = SerializationFormat.Xml; WriteToStream = (stream, foo, bar) => { OutputUtils.writeCSV(ResultsDataSet, stream); stream.Close(); }; response.Content = new PushStreamContent(WriteToStream, new MediaTypeHeaderValue((KeyWords.contentCSV))); if (FileType == "csv") { FileType = ".csv"; } else { FileType = ".txt"; } if (SaveResult == "true") { response.Content.Headers.Add("Content-Disposition", "attachment;filename=\"result" + FileType + "\""); } break; case "fits": case "application/fits": ResultsDataSet.RemotingFormat = SerializationFormat.Binary; WriteToStream = (stream, foo, bar) => { OutputUtils.WriteFits(ResultsDataSet, stream); stream.Close(); }; response.Content = new PushStreamContent(WriteToStream, new MediaTypeHeaderValue((KeyWords.contentFITS))); if (SaveResult == "true") { response.Content.Headers.Add("Content-Disposition", "attachment;filename=\"result.fits\""); } break; case "votable": case "application/x-votable+xml": ResultsDataSet.RemotingFormat = SerializationFormat.Xml; WriteToStream = (stream, foo, bar) => { OutputUtils.WriteVOTable(ResultsDataSet, stream); stream.Close(); }; response.Content = new PushStreamContent(WriteToStream, new MediaTypeHeaderValue((KeyWords.contentVOTable))); if (SaveResult == "true") { response.Content.Headers.Add("Content-Disposition", "attachment;filename=\"result.votable.xml\""); } break; case "xml": case "application/xml": ResultsDataSet.RemotingFormat = SerializationFormat.Xml; WriteToStream = (stream, foo, bar) => { OutputUtils.WriteXml(ResultsDataSet, stream); stream.Close(); }; response.Content = new PushStreamContent(WriteToStream, new MediaTypeHeaderValue((KeyWords.contentXML))); if (SaveResult == "true") { response.Content.Headers.Add("Content-Disposition", "attachment;filename=\"result.xml\""); } break; case "json": case "application/json": ResultsDataSet.RemotingFormat = SerializationFormat.Xml; WriteToStream = (stream, foo, bar) => { OutputUtils.WriteJson(ResultsDataSet, stream); stream.Close(); }; response.Content = new PushStreamContent(WriteToStream, new MediaTypeHeaderValue((KeyWords.contentJson))); if (SaveResult == "true") { response.Content.Headers.Add("Content-Disposition", "attachment;filename=\"result.json\""); } break; case "html": case "dataset": case "application/x-dataset": ProcessDataSet proc = new ProcessDataSet(query, format, TaskName, ExtraInfo, null, true, positionType, queryType, null, null); response.Content = proc.GetContent(ResultsDataSet); if (ExtraInfo.ContainsKey("FormatFromUser")) { if (ExtraInfo["FormatFromUser"] == "html") { response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); } } //ResultsDataSet.RemotingFormat = SerializationFormat.Binary; //fmt = new BinaryFormatter(); //WriteToStream = (stream, foo, bar) => { fmt.Serialize(stream, ResultsDataSet); stream.Close(); }; //response.Content = new PushStreamContent(WriteToStream, new MediaTypeHeaderValue(KeyWords.contentDataset)); break; default: ResultsDataSet.RemotingFormat = SerializationFormat.Binary; fmt = new BinaryFormatter(); WriteToStream = (stream, foo, bar) => { fmt.Serialize(stream, ResultsDataSet); stream.Close(); }; response.Content = new PushStreamContent(WriteToStream, new MediaTypeHeaderValue((KeyWords.contentDataset))); break; } //reader.Close(); //response.Content = new StringContent(ClientIP); logger.LogActivity(ActivityInfo, "SkyserverMessage"); return(response); }
public HttpResponseMessage SendToMyDB() { HttpResponseMessage respMessage = null; string ResponseResult = ""; string requestUri = ""; if (logger.IsValidUser) { string TableName = ExtraInfo["TableName"]; if (!string.IsNullOrEmpty(TableName)) { Regex rg = new Regex("[^a-zA-Z0-9]"); if (rg.IsMatch(TableName)) { throw (new Exception("String TableName may only contain letters or numbers.")); } /* * string ForbiddenChar = ",./-?\!"; * for (int i = 0; i < ForbiddenChar.Length;i++) * { * if (TableName.Contains(ForbiddenChar.Substring(i,1))) * throw (new Exception("TableName may not contain characters like " + ForbiddenChar )); * } */ requestUri = ConfigurationManager.AppSettings["CASJobsREST"] + "contexts/MyDB/tables/"; HttpClient client = new HttpClient(); client.Timeout = new TimeSpan(0, 0, 0, KeyWords.TimeoutCASJobs);// default is 100000ms client.BaseAddress = new Uri(requestUri); client.DefaultRequestHeaders.Add("X-Auth-Token", logger.Token); respMessage = client.GetAsync(requestUri).Result; ResponseResult = respMessage.Content.ReadAsStringAsync().Result; if (!respMessage.IsSuccessStatusCode) { if (ExtraInfo["DoReturnHtml"].ToLower() == "false") { CreateErrorResponseMessageJSON(ResponseResult); } else { CreateErrorResponseMessageHTML(ResponseResult); } logger.LogActivity(ActivityInfo, "SkyserverMessage"); return(response); } Dictionary <string, string> values; Newtonsoft.Json.Linq.JArray array = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(ResponseResult);//ResponseResult comes in json format for (int i = 0; i < array.Count; i++) { values = JsonConvert.DeserializeObject <Dictionary <string, string> >(array[i].ToString()); if (values["Name"] == TableName) { if (ExtraInfo["DoReturnHtml"].ToLower() == "false") { throw (new Exception("Table \"" + TableName + "\" already exists in MyDB. Try changing the table name or see it in MyDB")); } else { ProcessDataSet proc = new ProcessDataSet(query, format, TaskName, ExtraInfo, null, true, positionType, queryType, null, null); string queryResult1 = proc.getTableReSubmitHTMLresult(TableName, logger.Token); response.Content = new StringContent(queryResult1, tCode, KeyWords.contentHTML); response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); } return(response); } //throw (new Exception("Table \"" + TableName + "\" already exists in MyDB. Try changing the table name or <a target=INFO href=\"" + ConfigurationManager.AppSettings["CASJobs"] + "MyDB.aspx" + "\">LINK</a> ")); } } else// create a table name { //DateTime2 now = DateTime2.Now; TableName = "Table_" + DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"); } /* * if (!(ExtraInfo["EntryPoint"].ToLower().Contains("sqlsearch") || ExtraInfo["EntryPoint"].ToLower().Contains("crossid") || ExtraInfo["EntryPoint"].ToLower().Contains("proximity")))// sending query as a job * { * string queryResult = ""; * StringBuilder strbldr = new StringBuilder(); * StringWriter sw = new StringWriter(strbldr); * using (JsonWriter writer = new JsonTextWriter(sw)) * { * writer.WriteStartObject(); * writer.WritePropertyName("query"); * writer.WriteValue(ExtraInfo["QueryForUserDisplay"]); * writer.WritePropertyName("TaskName"); * writer.WriteValue("SkyserverWS.SendToMyDB"); * writer.WritePropertyName("CreateTable"); * writer.WriteValue("true"); * writer.WritePropertyName("TableName"); * writer.WriteValue(TableName); * } * * StringContent content = new StringContent(strbldr.ToString()); * content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); * content.Headers.Add("X-Auth-Token", logger.Token); * * //posting the request and getting the result back. * HttpClient client2 = new HttpClient(); * client2.Timeout = new TimeSpan(0, 0, 0, KeyWords.TimeoutCASJobs);// default is 100000ms * requestUri = ConfigurationManager.AppSettings["CASJobsREST"] + "contexts/" + KeyWords.DataRelease + "/jobs"; * client2.BaseAddress = new Uri(requestUri); * respMessage = client2.PutAsync(requestUri, content).Result; * string JobID = "UNKNOWN"; * if (respMessage.IsSuccessStatusCode) * { * JobID = respMessage.Content.ReadAsStringAsync().Result; * if (ExtraInfo["DoReturnHtml"].ToLower() == "false") * { * queryResult = "[{\"JobID\": \"" + JobID + "\", \"TableName\"= \"" + TableName + "\"}]"; * response.Content = new StringContent(queryResult, tCode, KeyWords.contentJson); * response.Content.Headers.ContentType = new MediaTypeHeaderValue(KeyWords.contentJson); * } * else * { * ProcessDataSet proc = new ProcessDataSet(query, format, TaskName, ExtraInfo, null, true, positionType, queryType, null, null); * queryResult = proc.getCasJobsSubmitHTMLresult(JobID, TableName, logger.Token); * response.Content = new StringContent(queryResult, tCode, KeyWords.contentHTML); * response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); * } * } * else * { * string ErrorMessage = respMessage.Content.ReadAsStringAsync().Result; * if (ExtraInfo["DoReturnHtml"].ToLower() == "false") * CreateErrorResponseMessageJSON(ErrorMessage); * else * CreateErrorResponseMessageHTML(ErrorMessage); * } * * logger.LogActivity(ActivityInfo, "SkyserverMessage"); * return response; * * } * else // sending query results as a csv * { * } */ //sending query result as a csv: string queryResult = ""; RunQuery(); Action <Stream, HttpContent, TransportContext> WriteToStream = null; DataSet ds = new DataSet(); ds.Tables.Add(ResultsDataSet.Tables[0].Copy()); WriteToStream = (stream, foo, bar) => { OutputUtils.writeCSV(ds, stream, false); stream.Close(); }; HttpContent content = new PushStreamContent(WriteToStream, new MediaTypeHeaderValue((KeyWords.contentCSV))); //content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); content.Headers.Add("X-Auth-Token", logger.Token); requestUri = ConfigurationManager.AppSettings["CASJobsREST"] + "contexts/MyDB/tables/" + TableName; HttpClient client2 = new HttpClient(); client2.Timeout = new TimeSpan(0, 0, 0, KeyWords.TimeoutCASJobs);// default is 100000ms client2.BaseAddress = new Uri(requestUri); respMessage = client2.PostAsync(requestUri, content).Result; if (respMessage.IsSuccessStatusCode) { if (ExtraInfo["DoReturnHtml"].ToLower() == "false") { queryResult = "[{\"IsSuccessStatusCode\": \"true\", \"TableName\"= \"" + TableName + "\"}]"; response.Content = new StringContent(queryResult, tCode, KeyWords.contentJson); response.Content.Headers.ContentType = new MediaTypeHeaderValue(KeyWords.contentJson); } else { ProcessDataSet proc = new ProcessDataSet(query, format, TaskName, ExtraInfo, null, true, positionType, queryType, null, null); queryResult = proc.getTableSubmitHTMLresult(TableName, logger.Token); response.Content = new StringContent(queryResult, tCode, KeyWords.contentHTML); response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); } } else { string ErrorMessage = respMessage.Content.ReadAsStringAsync().Result; if (ExtraInfo["DoReturnHtml"].ToLower() == "false") { CreateErrorResponseMessageJSON(ErrorMessage); } else { CreateErrorResponseMessageHTML(ErrorMessage); } } logger.LogActivity(ActivityInfo, "SkyserverMessage"); return(response); } else { throw (new UnauthorizedAccessException("You are not logged-in with SciServer. Please log-in and try again.")); } }
public void ProcessCommand(IWrite iWrite, string cmdName) { Command cmd; // store the current menu Menu currentMenuCopy = CurrentMenu; bool restoreCurrentMenu = false; if (cmdName.Equals("")) { return; } cmdName = OutputUtils.RemoveLeadingBlanks(cmdName); // is there a slash ? fectch the command before the slash // and execute the command after that remove the prefix from the string // CurrentMenu reference will be restored from copy in the end of the function int argIdx = cmdName.IndexOf(" "); // ignore slashes in the arguments if (argIdx < 0) { argIdx = cmdName.Length; // if there is no arguments look until end of line } int slashIdx = cmdName.IndexOf("/"); while ((slashIdx >= 0) && (slashIdx < argIdx)) { string subcommand = cmdName.Substring(0, slashIdx); ProcessCommand(iWrite, subcommand); cmdName = cmdName.Remove(0, slashIdx + 1); slashIdx = cmdName.IndexOf("/"); restoreCurrentMenu = true; } // may be exit or help commands - always look in the system menu bool found = SystemMenu.FindCommand(cmdName, out cmd); // not a system command try current menu then if (!found) { found = CurrentMenu.FindCommand(cmdName, out cmd); } if (found && cmd.IsCommand()) { // temporary no parsing for the arguments cmd.Handler(iWrite, cmdName, SplitCommand(cmdName)); } else if (found && !cmd.IsCommand()) { CurrentMenu = (Menu)cmd; PrintCommands(iWrite); } else { iWrite.WriteLine("Unknown command " + cmdName); } if (restoreCurrentMenu) { CurrentMenu = currentMenuCopy; } }