static Boolean TestKnownEnc(Aes aes, Byte[] Key, Byte[] IV, Byte[] Plain, Byte[] Cipher) { Byte[] CipherCalculated; Console.WriteLine("Encrypting the following bytes:"); PrintByteArray(Plain); Console.WriteLine("With the following Key:"); PrintByteArray(Key); Console.WriteLine("and IV:"); PrintByteArray(IV); Console.WriteLine("Expecting this ciphertext:"); PrintByteArray(Cipher); ICryptoTransform sse = aes.CreateEncryptor(Key, IV); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write); cs.Write(Plain,0,Plain.Length); cs.FlushFinalBlock(); CipherCalculated = ms.ToArray(); cs.Close(); Console.WriteLine("Computed this cyphertext:"); PrintByteArray(CipherCalculated); if (!Compare(Cipher, CipherCalculated)) { Console.WriteLine("ERROR: result is different from the expected"); return false; } Console.WriteLine("OK"); return true; }
//you need to provide the correct select statement for whatever doc you are trying to recieve public void DownloadFile(string selectStatement) { byte[] fileData; string connection = ConfigurationManager.ConnectionStrings["testDB"].ConnectionString; SqlConnection conn = new SqlConnection(connection); SqlCommand cmd = new SqlCommand(selectStatement, conn); conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { fileData = (byte[])dr[0]; using ( MemoryStream stream = new MemoryStream(fileData)) { HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=weserveuFile.pdf"); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.BinaryWrite(stream.ToArray()); HttpContext.Current.Response.End(); } } dr.Close(); conn.Close(); }
// gets the image's sizes private void GetWidthHeight(string filename, out string width, out string height) { width = ""; height = ""; System.Drawing.Image objImage; MemoryStream objStream; FileStream binStream = File.OpenRead(filename); byte[] buf = new byte[binStream.Length]; System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback); binStream.Read(buf, 0, (int)binStream.Length); binStream.Close(); objStream = new MemoryStream(buf); objStream.Position = 0; try { objImage = System.Drawing.Image.FromStream(objStream); width = objImage.Width.ToString(); height = objImage.Height.ToString(); objImage.Dispose(); } catch { } objStream.Close(); }
public static void Main() { byte[] bytes; var values = new long[] { 0, 1, 0xFFFF, 0xFF00FF00FF00L, 12345678901234L, -0xFFFF, -0xFF00FF00FF00L }; long length; using (var ms = new MemoryStream()) using (var bw = new BinaryWriter(ms)) { foreach (var value in values) { bw.Write(value); Console.WriteLine(value); } bw.Flush(); length = ms.Position; bytes = ms.GetBuffer(); } Util.PrintByteArray(bytes, (int)length); using (var ms = new MemoryStream(bytes, false)) using (var br = new BinaryReader(ms)) { for (int i = 0; i < values.Length; i++) { var value = br.ReadInt64(); Console.WriteLine(value); } } }
public void OnMsgConstellationLevelup(MemoryStream stream) { MS2C_ConstellationLevelup mS2C_ConstellationLevelup = Serializer.NonGeneric.Deserialize(typeof(MS2C_ConstellationLevelup), stream) as MS2C_ConstellationLevelup; if (mS2C_ConstellationLevelup.Result != 0) { GameUIManager.mInstance.ShowMessageTip("PlayerR", mS2C_ConstellationLevelup.Result); return; } this.mconLv = Globals.Instance.Player.Data.ConstellationLevel; GameUIManager.mInstance.ShowFadeBG(5900, 3000); this.mGUIXingZuoPage.mUIXingZuoItem.mWaitTimeToHide = 1.1f; this.mGUIXingZuoPage.mUIXingZuoItem.RefreshShowIcon(); this.mGUIRightInfo.Refresh(this.mconLv); this.mGUIXingZuoPage.mUIXingZuoItem.RefreshEffect(); base.StartCoroutine(this.WaitShowAttribute()); if (Globals.Instance.Player.ItemSystem.GetItemCount(GameConst.GetInt32(103)) >= GUIRightInfo.GetCost()) { base.StartCoroutine(this.EffectSound()); } int constellationLevel = Globals.Instance.Player.Data.ConstellationLevel; if (constellationLevel == 10 || constellationLevel == 30) { GameUIManager.mInstance.ShowPetQualityUp(constellationLevel); } if (constellationLevel > 0 && constellationLevel % 5 == 0 && (constellationLevel != 10 & constellationLevel != 30)) { base.StartCoroutine(this.WaitShowBaoXiang()); } Globals.Instance.TutorialMgr.InitializationCompleted(this, null); }
public override void LoadTable(string _path) { if ((null != AssetbundleManager.Instance && true == AssetbundleManager.Instance.useAssetbundle) || true == AsTableManager.Instance.useReadBinary) { // Ready Binary TextAsset textAsset = ResourceLoad.LoadTextAsset (_path); MemoryStream stream = new MemoryStream (textAsset.bytes); BinaryReader br = new BinaryReader (stream); int nCount = br.ReadInt32 (); for (int i = 0; i < nCount; i++) { Tbl_SynDisassemble_Record record = new Tbl_SynDisassemble_Record (br); m_recordList.Add (record); } br.Close (); stream.Close (); } else { XmlElement root = GetXmlRootElement(_path); XmlNodeList nodes = root.ChildNodes; foreach(XmlNode node in nodes) { Tbl_SynDisassemble_Record record = new Tbl_SynDisassemble_Record((XmlElement)node); m_recordList.Add( record ); } } }
public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Verify InvalidOperationException is thrown when set ReadTimeOut property..."); try { Stream s = new MemoryStream(); for (int i = 0; i < 100; i++) s.WriteByte((byte)i); s.Position = 0; s.ReadTimeout = 10; TestLibrary.TestFramework.LogError("001", "No exception occurs!"); retVal = false; } catch (InvalidOperationException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception occurs: " + e); retVal = false; } return retVal; }
// Creates a memory stream with the first 4K bytes of the record. private void CreateMemoryStream() { byte[] pData; int cbData = INITIAL_READ; int totalSize; log.ReadRecordPrefix(this.recordSequenceNumber, out pData, ref cbData, out totalSize, out this.prevSeqNum, out this.nextSeqNum); if (cbData < FileLogRecordHeader.Size) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.LogCorrupt()); this.header = new FileLogRecordHeader(pData); this.recordSize = totalSize - FileLogRecordHeader.Size; int streamSize = Math.Min(this.recordSize, INITIAL_READ - FileLogRecordHeader.Size); this.stream = new MemoryStream( pData, FileLogRecordHeader.Size, streamSize, false); if (totalSize <= INITIAL_READ) { // Record is smaller than 4K. We have read the entire record. this.entireRecordRead = true; } }
static void Main (string [] args) { int i = 0; while (args [i].StartsWith ("-")){ if (args [i] == "-debug") debug = true; if (args [i] == "-headers") headers = true; if (args [i] == "-header") header = args [++i]; i++; } c = new TcpClient (args [i], Int32.Parse (args [i+1])); c.ReceiveTimeout = 1000; ns = c.GetStream (); sw = new StreamWriter (ns); sr = new StreamReader (ns); string host = args [i]; if (args [i+1] != "80") host += ":" + args [i+1]; send (String.Format ("GET {0} HTTP/1.1\r\nHost: {1}\r\n\r\n", args [i+2], host)); MemoryStream ms = new MemoryStream (); try { byte [] buf = new byte [1024]; int n; while ((n = ns.Read (buf, 0, 1024)) != 0){ ms.Write (buf, 0, n); } } catch {} ms.Position = 0; sr = new StreamReader (ms); string s; while ((s = sr.ReadLine ()) != null){ if (s == ""){ if (headers) return; string x = sr.ReadToEnd (); Console.Write (x); break; } else { if (debug || headers) Console.WriteLine (s); if (header != null && s.StartsWith (header)){ Console.WriteLine (s); return; } } } }
public void LoadFromFile() { TextAsset textAsset = Res.Load("Attribute/AchievementInfo") as TextAsset; if (textAsset == null) { global::Debug.LogError(new object[] { "Res.Load error, Name = AchievementInfo" }); return; } try { this.infos.Clear(); MemoryStream source = new MemoryStream(textAsset.bytes, 0, textAsset.bytes.Length); AchievementInfoDict achievementInfoDict = Serializer.NonGeneric.Deserialize(typeof(AchievementInfoDict), source) as AchievementInfoDict; for (int i = 0; i < achievementInfoDict.Data.Count; i++) { this.infos.Add(achievementInfoDict.Data[i].ID, achievementInfoDict.Data[i]); } } catch (Exception ex) { global::Debug.LogError(new object[] { "Load AchievementInfo.bytes Error, Exception = " + ex.Message }); } }
public static string Serialize(object obj) { MemoryStream memoryStream = new MemoryStream (); binaryFormatter.Serialize (memoryStream, obj); string serialized = System.Convert.ToBase64String (memoryStream.ToArray ()); return serialized; }
private void Start() { string imgFile = folderName + FileUpload1.FileName; Stream inputStream = new MemoryStream(); System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath(imgFile)); img.Save(inputStream, System.Drawing.Imaging.ImageFormat.Jpeg); Stream outputStream; int diameter; if (int.TryParse(tbDiameter.Text.Trim(), out diameter)) { outputStream = CircleImageCreater.CreateCircleImageStream(inputStream, diameter); } else { outputStream = CircleImageCreater.CreateCircleImageStream(inputStream); } saveImage(outputStream, FileUpload1.FileName + ".png"); oldImage.ImageUrl = imgFile; newImage.ImageUrl = folderName + FileUpload1.FileName + ".png"; //dispose inputStream.Dispose(); outputStream.Dispose(); }
public override void Serialize(MemoryStream stream) { header.Serialize(stream); System.Byte[] height_bytes = BitConverter.GetBytes(height); stream.Write(height_bytes, 0, height_bytes.Length); System.Byte[] width_bytes = BitConverter.GetBytes(width); stream.Write(width_bytes, 0, width_bytes.Length); System.Byte[] fields_len_bytes = BitConverter.GetBytes((System.UInt32)fields.Count); stream.Write(fields_len_bytes, 0, fields_len_bytes.Length); foreach(sensor_msgs.PointField element in fields) { element.Serialize(stream); } System.Byte[] is_bigendian_bytes = BitConverter.GetBytes(is_bigendian); stream.Write(is_bigendian_bytes, 0, is_bigendian_bytes.Length); System.Byte[] point_step_bytes = BitConverter.GetBytes(point_step); stream.Write(point_step_bytes, 0, point_step_bytes.Length); System.Byte[] row_step_bytes = BitConverter.GetBytes(row_step); stream.Write(row_step_bytes, 0, row_step_bytes.Length); System.Byte[] compression_type_bytes = new System.Byte[] {compression_type}; stream.Write(compression_type_bytes, 0, compression_type_bytes.Length); System.Byte[] compressed_data_bytes = compressed_data.ToArray(); System.Byte[] compressed_data_len_bytes = BitConverter.GetBytes((System.UInt32)compressed_data_bytes.Length); stream.Write(compressed_data_len_bytes, 0, compressed_data_len_bytes.Length); stream.Write(compressed_data_bytes, 0, compressed_data_bytes.Length); System.Byte[] is_dense_bytes = BitConverter.GetBytes(is_dense); stream.Write(is_dense_bytes, 0, is_dense_bytes.Length); }
public static void Main() { string PlainText = "Titan"; byte[] PlainBytes = new byte[5]; PlainBytes = Encoding.ASCII.GetBytes(PlainText.ToCharArray()); PrintByteArray(PlainBytes); byte[] CipherBytes = new byte[8]; PasswordDeriveBytes pdb = new PasswordDeriveBytes("Titan", null); byte[] IV = new byte[8]; byte[] Key = pdb.CryptDeriveKey("RC2", "SHA1", 40, IV); PrintByteArray(Key); PrintByteArray(IV); // Now use the data to encrypt something RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); Console.WriteLine(rc2.Padding); Console.WriteLine(rc2.Mode); ICryptoTransform sse = rc2.CreateEncryptor(Key, IV); MemoryStream ms = new MemoryStream(); CryptoStream cs1 = new CryptoStream(ms, sse, CryptoStreamMode.Write); cs1.Write(PlainBytes, 0, PlainBytes.Length); cs1.FlushFinalBlock(); CipherBytes = ms.ToArray(); cs1.Close(); Console.WriteLine(Encoding.ASCII.GetString(CipherBytes)); PrintByteArray(CipherBytes); ICryptoTransform ssd = rc2.CreateDecryptor(Key, IV); CryptoStream cs2 = new CryptoStream(new MemoryStream(CipherBytes), ssd, CryptoStreamMode.Read); byte[] InitialText = new byte[5]; cs2.Read(InitialText, 0, 5); Console.WriteLine(Encoding.ASCII.GetString(InitialText)); PrintByteArray(InitialText); }
public static byte[] GetBytes(Level data) { IFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, data); return stream.ToArray(); }
public override void Serialize(MemoryStream stream) { header.Serialize(stream); System.Byte[] angle_min_bytes = BitConverter.GetBytes(angle_min); stream.Write(angle_min_bytes, 0, angle_min_bytes.Length); System.Byte[] angle_max_bytes = BitConverter.GetBytes(angle_max); stream.Write(angle_max_bytes, 0, angle_max_bytes.Length); System.Byte[] angle_increment_bytes = BitConverter.GetBytes(angle_increment); stream.Write(angle_increment_bytes, 0, angle_increment_bytes.Length); System.Byte[] time_increment_bytes = BitConverter.GetBytes(time_increment); stream.Write(time_increment_bytes, 0, time_increment_bytes.Length); System.Byte[] scan_time_bytes = BitConverter.GetBytes(scan_time); stream.Write(scan_time_bytes, 0, scan_time_bytes.Length); System.Byte[] range_min_bytes = BitConverter.GetBytes(range_min); stream.Write(range_min_bytes, 0, range_min_bytes.Length); System.Byte[] range_max_bytes = BitConverter.GetBytes(range_max); stream.Write(range_max_bytes, 0, range_max_bytes.Length); System.Byte[] ranges_len_bytes = BitConverter.GetBytes((System.UInt32)ranges.Count); stream.Write(ranges_len_bytes, 0, ranges_len_bytes.Length); foreach(sensor_msgs.LaserEcho element in ranges) { element.Serialize(stream); } System.Byte[] intensities_len_bytes = BitConverter.GetBytes((System.UInt32)intensities.Count); stream.Write(intensities_len_bytes, 0, intensities_len_bytes.Length); foreach(sensor_msgs.LaserEcho element in intensities) { element.Serialize(stream); } }
public static NetworkResponse Parse(MemoryStream dataStream) { ResponseNoWaitForGame response = new ResponseNoWaitForGame(); response.status = DataReader.ReadInt(dataStream); return response; }
Messages Deserialize(byte[] bytes) { MemoryStream stream = new MemoryStream(bytes); BinaryFormatter b = new BinaryFormatter(); return (Messages)b.Deserialize(stream); }
public static void saveFunction(string saveTag, object obj) { MemoryStream memoryStream = new MemoryStream (); binaryFormatter.Serialize (memoryStream, obj); string temp = System.Convert.ToBase64String (memoryStream.ToArray ()); PlayerPrefs.SetString (saveTag, temp); }
protected void Page_Load(object sender, EventArgs e) { string mode = Request["mode"]; int node = 0; int.TryParse(Request["nid"], out node); Super2d3dGraph oGraph = null; if (mode == "links") { if (WAFContext.Session.ContentExists(node)) { NewsletterDelivery delivery = WAFContext.Session.GetContent<NewsletterDelivery>(node,WAFContext.Session.LCID); oGraph = NewsletterCharts.GetDeliveryLinksBarChart(delivery); } } else if (mode == "clicksvssent") { if (WAFContext.Session.ContentExists(node)) { NewsletterDelivery delivery = WAFContext.Session.GetContent<NewsletterDelivery>(node,WAFContext.Session.LCID); oGraph = NewsletterCharts.GetDeliveryReadsVsClicksBarChart(delivery); } } if (oGraph != null) { oGraph.RefreshChart(); // Save image in a temporary buffer (PNG format for best quality) MemoryStream io = new MemoryStream(); oGraph.Image.Save(io, ImageFormat.Png); // Output the content of the buffer to the browser Response.Clear(); Response.ContentType = "image/png"; Response.BinaryWrite(io.GetBuffer()); } }
/// <summary> /// Builds and in memory stream containing the binary data in a multi-part MIME that is ready for upload /// </summary> /// <returns></returns> public override byte [] GenerateMimeEncodedChunk() { var inMemoryStream = new MemoryStream(); using (inMemoryStream) { WriteBoundaryLine(inMemoryStream); // WriteAsciiLine(inMemoryStream, "Content-Disposition: name=\"request_payload\""); WriteAsciiLine(inMemoryStream, "Content-Disposition: form-data; name=\"request_payload\""); //Server v9.2 is stricter about request syntax WriteAsciiLine(inMemoryStream, "Content-Type: text/xml"); WriteAsciiLine(inMemoryStream); WriteAsciiLine(inMemoryStream); //[2015-10-17] Extra line to meet expectations for 2 empty lines after content WriteBoundaryLine(inMemoryStream); // WriteAsciiLine(inMemoryStream, "Content-Disposition: name=\"tableau_file\"; filename=\"FILE-NAME\""); WriteAsciiLine(inMemoryStream, "Content-Disposition: form-data; name=\"tableau_file\"; filename=\"FILE-NAME\""); //Server v9.2 is stricter about request syntax WriteAsciiLine(inMemoryStream, "Content-Type: application/octet-stream"); WriteAsciiLine(inMemoryStream); //Write the raw binary data inMemoryStream.Write(_uploadData, 0, _numberBytes); WriteAsciiLine(inMemoryStream); WriteBoundaryLine(inMemoryStream, true); //Go to the beginning inMemoryStream.Seek(0, SeekOrigin.Begin); return inMemoryStream.ToArray(); } }
public MemoryStream GET_PRESTATIONS_GROUPE(MemoryStream xml) { Dictionary<object, Object> param = null; MemoryStream mresult = null; bool demo = false; List<PRESTATIONS_GROUPE> result = null; OperationContext.Current.OperationCompleted += new EventHandler(delegate(object sender, EventArgs args) { if (mresult != null) mresult.Dispose(); }); try { param = Serializer.READC<Dictionary<object, object>>(xml); demo = ((param.Keys.Any(x => x.Equals("DEMO"))) && (param["DEMO"] != null)) ? Convert.ToBoolean(param["DEMO"]) : false; using (var CONTEXT = new dbAbisEntities((!demo) ? CS : CS_DEMO)) { result = CONTEXT.EXECUTE_ENTITY_STORED_PROCEDURE<PRESTATIONS_GROUPE>("PRESTATIONS_GROUPEget", param, new List<string> { "DEMO" }); } mresult = Serializer.WRITEC<List<PRESTATIONS_GROUPE>>(result); return mresult; } catch (Exception ex) { throw new ApplicationException(String.Empty, ex); } }
//public static string Unscramble(string text ) { // byte[] clear = Encoding.UTF8.GetBytes (text); // return Encoding.UTF8.GetString( Xor( clear) ); //} public static byte[] Xor(byte[] clearTextBytes ) { byte[] key = GenKey (clearTextBytes.Length); //Debug.Log ("KEY : " + Encoding.Unicode.GetString (key)); MemoryStream ms = new MemoryStream(); for (int i = 0; i < clearTextBytes.Length; i++) { byte b = (byte)( (clearTextBytes [i] ^ key [i]) ); //if (b == 0 ) { // b = key [i]; //Debug.Log ("GOt NULL BYTE FROM KEY: " + key [i] + ", BYTE: " + clearTextBytes [i]); //} ms.WriteByte ( b ); } byte[] output = ms.ToArray(); //Debug.Log ("SCRAM OUT: " + output.Length); return output; }
public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) { byte[] encryptedBytes = null; // Set your salt here, change it to meet your flavor: // The salt bytes must be at least 8 bytes. byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; using (MemoryStream ms = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { AES.KeySize = 256; AES.BlockSize = 128; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Mode = CipherMode.CBC; using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length); cs.Close(); } encryptedBytes = ms.ToArray(); } } return encryptedBytes; //end public byte[] AES_Encrypt }
public static ActionPayload Decode(byte[] payload) { MemoryStream stream = new MemoryStream(payload); BinaryReader reader = new BinaryReader(stream); byte op = reader.ReadByte (); ActionPayload action = new ActionPayload(); switch (op) { case ActionPayload.OP_MOVEMENT: action.op = op; action.time = reader.ReadSingle (); action.position = new Vector3(); action.position.x = reader.ReadSingle (); action.position.y = reader.ReadSingle (); action.position.z = reader.ReadSingle (); action.rot = reader.ReadSingle (); action.state = (int)reader.ReadSingle (); break; } return action; }
public static object Load(string saveTag) { string temp = PlayerPrefs.GetString (saveTag); if (temp == string.Empty) {return null;} MemoryStream memoryStream = new MemoryStream (System.Convert.FromBase64String (temp)); return binaryFormatter.Deserialize(memoryStream); }
public WrappedMemoryStream(bool canRead, bool canWrite, bool canSeek, byte[] data) { wrapped = data != null ? new MemoryStream(data) : new MemoryStream(); _canWrite = canWrite; _canRead = canRead; _canSeek = canSeek; }
// Decrypt a byte array into a byte array using a key and an IV public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV) { // Create a MemoryStream that is going to accept the decrypted bytes MemoryStream ms = new MemoryStream(); // Create a symmetric algorithm. // We are going to use Rijndael because it is strong and available on all platforms. // You can use other algorithms, to do so substitute the next line with something like // TripleDES alg = TripleDES.Create(); Rijndael alg = Rijndael.Create(); // Now set the key and the IV. // We need the IV (Initialization Vector) because the algorithm is operating in its default // mode called CBC (Cipher Block Chaining). The IV is XORed with the first block (8 byte) // of the data after it is decrypted, and then each decrypted block is XORed with the previous // cipher block. This is done to make encryption more secure. // There is also a mode called ECB which does not need an IV, but it is much less secure. alg.Key = Key; alg.IV = IV; // Create a CryptoStream through which we are going to be pumping our data. // CryptoStreamMode.Write means that we are going to be writing data to the stream // and the output will be written in the MemoryStream we have provided. CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write); // Write the data and make it do the decryption cs.Write(cipherData, 0, cipherData.Length); // Close the crypto stream (or do FlushFinalBlock). // This will tell it that we have done our decryption and there is no more data coming in, // and it is now a good time to remove the padding and finalize the decryption process. cs.Close(); // Now get the decrypted data from the MemoryStream. // Some people make a mistake of using GetBuffer() here, which is not the right way. byte[] decryptedData = ms.ToArray(); return decryptedData; }
public static int Main(string [] args) { if (args.Length < 2) return Usage (); Dictionary<string,object> targs = new Dictionary<string,object> (); Assembly asm = Assembly.LoadFrom (args [0]); Type template_type = asm.GetType (args [1]); for (int i = 2; i + 1 < args.Length; i += 2) { targs.Add (args [i], args [i + 1]); } targs ["test_enumerable"] = new List<string> () { "one", "two", "three", "four" }; Console.WriteLine ("TEMPLATE TYPE: {0}", template_type); MethodInfo meth = template_type.GetMethod ("RenderToStream"); object template = Activator.CreateInstance (template_type); MemoryStream stream = new MemoryStream (); StreamWriter writer = new StreamWriter (stream); meth.Invoke (template, new object [] { Console.Out, targs }); return 0; }
public object DeserializeObject(string pXmlizedString , System.Type ty) { XmlSerializer xs = new XmlSerializer(ty); MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString)); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); return xs.Deserialize(memoryStream); }
static void Main(string[] args) { var data = new DataTable(); using (var csvReader = new CsvReader(new StreamReader(System.IO.File.OpenRead(@"data.csv")), false, ',')) { data.Load(csvReader); } object[] headers = (object[])data.Rows[0].ItemArray.Clone(); //foreach(var item in headers.ItemArray) Write(item + " "); WriteLine(); data.Rows[0].Delete(); data.AcceptChanges(); bool runprog = true; var drillaggregates = new List <int>(); headermenu(headers); Console.Write("Enter initial aggregate column # (must be numeric values only): "); var initagg = Convert.ToInt32(Console.ReadLine()); drillaggregates.Add(initagg); var filters = new List <int>(); var filterdata = new List <object>(); do { try { WriteLine("Menu options:\n\t0. Display Fact Table\n\t1. Display Aggregated Table\n\t2. Reinitialize Aggregate\n\t3. Drill-down\n\t4. Filter\n\t5. View\n\t6. Quit\n\t7. Reset Drill Aggregates\n\t8. Reset Filters\n\t9. Remove Drill Aggregate\n\t10.Remove Filter"); // also remove aggregate on website Write("Enter menu choice #: "); int menuoption = Convert.ToInt32(Console.ReadLine()); if (menuoption == 0) // Display Fact Table { var watch = Stopwatch.StartNew(); WriteLine(string.Join(",", headers)); for (int i = 0; i < data.Rows.Count; i++) { WriteLine(string.Join(", ", data.Rows[i].ItemArray)); } watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 1) // Display Aggregated Table { var watch = Stopwatch.StartNew(); displayaggregatetable(data, headers, drillaggregates.ToArray(), filters.ToArray(), filterdata.ToArray()); watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 2) // Reinitialize Aggregate { var watch = Stopwatch.StartNew(); headermenu(headers); Write("Enter initial aggregate column # (must be numeric values only): "); initagg = Convert.ToInt32(Console.ReadLine()); if (drillaggregates.Count == 0) { drillaggregates.Add(initagg); } else { drillaggregates[0] = initagg; } watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 3) // Drill-down { var watch = Stopwatch.StartNew(); headermenu(headers); Write("Enter drill-down aggregate choice #: "); int drillagg = Convert.ToInt32(Console.ReadLine()); if (!drillaggregates.Contains(drillagg)) { drillaggregates.Add(drillagg); } displayaggregatetable(data, headers, drillaggregates.ToArray(), filters.ToArray(), filterdata.ToArray()); watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 4) // Filter { var watch = Stopwatch.StartNew(); headermenu(headers); Write("Enter filter header choice #: "); int filterheader = Convert.ToInt32(Console.ReadLine()); var filteroptions = new List <object>(); for (int i = 0; i < data.Rows.Count; i++) { filteroptions.Add(data.Rows[i][filterheader]); } filteroptions = filteroptions.Distinct().ToList(); WriteLine("Filter options: "); for (int i = 0; i < filteroptions.Count; i++) { WriteLine("\t{0}. {1}", i, filteroptions[i]); } Write("Enter filter option choice #: "); int filterby = Convert.ToInt32(Console.ReadLine()); var filter = filteroptions[filterby]; if (!filters.Contains(filterheader)) { filters.Add(filterheader); filterdata.Add(filter); } if (drillaggregates.Count > 1 || filters.Count > 0) { displayaggregatetable(data, headers, drillaggregates.ToArray(), filters.ToArray(), filterdata.ToArray()); } else { if (filters.Count == 0 && drillaggregates.Count == 1) { var filtertable = data.Clone(); for (int i = 0; i < filtertable.Rows.Count; i++) { if (filtertable.Rows[i][filterheader] != filter) { filtertable.Rows[i].Delete(); } } filtertable.AcceptChanges(); WriteLine(string.Join(",", headers)); for (int i = 0; i < filtertable.Rows.Count; i++) { WriteLine(string.Join(", ", filtertable.Rows[i].ItemArray)); } } } watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 5) // View { var watch = Stopwatch.StartNew(); DataTable x, y; int xhead, yhead; if (filters.Count == 0 && drillaggregates.Count == 1) { headermenu(headers); Write("Enter x header column #: "); xhead = Convert.ToInt32(Console.ReadLine()); Write("Enter y header column #: "); yhead = Convert.ToInt32(Console.ReadLine()); x = data.Copy(); y = data.Copy(); for (int i = data.Columns.Count; i-- > 0;) { if (i != xhead) { x.Columns.RemoveAt(i); } if (i != yhead) { y.Columns.RemoveAt(i); } } } else { WriteLine("Header options (remove drill aggregates to display more options):"); for (int i = 0; i < drillaggregates.Count; i++) { WriteLine("{0}. {1}", drillaggregates[i], headers[drillaggregates[i]]); } Write("Enter x header column #: "); xhead = Convert.ToInt32(Console.ReadLine()); Write("Enter y header column #: "); yhead = Convert.ToInt32(Console.ReadLine()); var sorteddrillagg = drillaggregates.ToArray(); Array.Sort(sorteddrillagg); int xheadind = Array.IndexOf(sorteddrillagg, xhead); int yheadind = Array.IndexOf(sorteddrillagg, yhead); x = getaggregatetable(data, drillaggregates.ToArray(), filters.ToArray(), filterdata.ToArray()); for (int i = x.Columns.Count; i-- > 0;) { if (i != xheadind) { x.Columns.RemoveAt(i); } } y = getaggregatetable(data, drillaggregates.ToArray(), filters.ToArray(), filterdata.ToArray()); for (int i = y.Columns.Count; i-- > 0;) { if (i != yheadind) { y.Columns.RemoveAt(i); } } } WriteLine("Graph options:\n\t1. Bar\n\t2. Line\n\t3. Line with Marker\n\t4. Scatter\n\t5. Pie"); Write("Enter graph choice #: "); int graphtype = Convert.ToInt32(Console.ReadLine()); var xlist = new List <object>(); var ylist = new List <object>(); for (int i = 0; i < x.Rows.Count; i++) { xlist.Add(x.Rows[i][0]); ylist.Add(y.Rows[i][0]); } var myModel = new PlotModel { Title = $"Data from the CSV File: {headers[xhead]} and {headers[yhead]}", Background = OxyColors.White }; var linearAxis1 = new LinearAxis(); linearAxis1.Position = AxisPosition.Bottom; var linearAxis2 = new LinearAxis(); linearAxis2.Position = AxisPosition.Left; if (graphtype != 5 || graphtype != 1) { linearAxis1.Title = headers[xhead].ToString(); linearAxis2.Title = headers[yhead].ToString(); } // else { linearAxis1.Title = headers[xhead].ToString(); } if (graphtype != 1) { myModel.Axes.Add(linearAxis1); } if (graphtype != 1) { myModel.Axes.Add(linearAxis2); } if (graphtype == 1) // Bar { var barSource = new List <BarItem>(); for (int i = 0; i < xlist.Count; i++) { barSource.Add(new BarItem { Value = Convert.ToDouble(ylist[i]) }); } var barSeries = new BarSeries { ItemsSource = barSource, LabelPlacement = LabelPlacement.Inside, }; var catSource = new List <string>(); for (int i = 0; i < xlist.Count; i++) { catSource.Add(xlist[i].ToString()); } linearAxis1.Title = headers[yhead].ToString(); myModel.Series.Add(barSeries); myModel.Axes.Add(new CategoryAxis { Position = AxisPosition.Left, Key = "X_Axis", Title = headers[xhead].ToString(), ItemsSource = catSource.ToArray() }); myModel.Axes.Add(linearAxis1); } else if (graphtype == 2) // Line { var lineSeries = new LineSeries(); for (int i = 0; i < xlist.Count; i++) { lineSeries.Points.Add(new DataPoint(Convert.ToDouble(xlist[i]), Convert.ToDouble(ylist[i]))); } myModel.Series.Add(lineSeries); } else if (graphtype == 3) // Line with Marker { var lineSeries = new LineSeries(); lineSeries.MarkerType = MarkerType.Circle; lineSeries.MarkerSize = 5; lineSeries.MarkerStroke = OxyColors.Black; lineSeries.MarkerFill = OxyColors.SkyBlue; lineSeries.MarkerStrokeThickness = 1.5; for (int i = 0; i < xlist.Count; i++) { lineSeries.Points.Add(new DataPoint(Convert.ToDouble(xlist[i]), Convert.ToDouble(ylist[i]))); } myModel.Series.Add(lineSeries); } else if (graphtype == 4) // Scatter { var scatterSeries = new ScatterSeries(); for (int i = 0; i < xlist.Count; i++) { scatterSeries.Points.Add(new ScatterPoint(Convert.ToDouble(xlist[i]), Convert.ToDouble(ylist[i]))); } myModel.Series.Add(scatterSeries); } else if (graphtype == 5) // Pie { var aggr_x = xlist.Distinct().ToList(); //plt.pie(aggr_x, labels=aggr_x) var pieSeries = new PieSeries { StrokeThickness = 2.0, InsideLabelPosition = 0.8, AngleSpan = 360, StartAngle = 0 }; for (int i = 0; i < xlist.Count; i++) { pieSeries.Slices.Add(new PieSlice(xlist[i].ToString(), Convert.ToDouble(ylist[i])) { IsExploded = false }); } myModel.Series.Add(pieSeries); //https://oxyplot.readthedocs.io/en/latest/models/series/PieSeries.html } var form = new Form1(myModel); Application.EnableVisualStyles(); Application.Run(form); var stream = new MemoryStream(); var pngExporter = new PngExporter { Width = 600, Height = 400 }; //, Background = OxyColors.White }; pngExporter.Export(myModel, stream); var bytes = new Byte[(int)stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(bytes, 0, (int)stream.Length); string b64 = Convert.ToBase64String(bytes); string uri = "data:image/png;base64," + b64; string html = $"<img src = \"{uri}\"/>"; watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 6) // Quit { runprog = false; return; } else if (menuoption == 7) // Reset Drill Aggregates { var watch = Stopwatch.StartNew(); drillaggregates.Clear(); watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 8) // Reset Filters { var watch = Stopwatch.StartNew(); filters.Clear(); filterdata.Clear(); watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 9) // Remove Drill Aggregate { var watch = Stopwatch.StartNew(); WriteLine("Current drill aggregates:"); for (int i = 0; i < drillaggregates.Count; i++) { WriteLine("{0}. {1}", i, headers[drillaggregates[i]]); } Write("Enter choice # to remove: "); int removechoice = Convert.ToInt32(Console.ReadLine()); drillaggregates.RemoveAt(removechoice); watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 10) // Remove Filter { var watch = Stopwatch.StartNew(); WriteLine("Current filters:"); for (int i = 0; i < filters.Count; i++) { WriteLine("{0}. {1}", i, headers[filters[i]]); } Write("Enter choice # to remove: "); int removechoice = Convert.ToInt32(Console.ReadLine()); filters.RemoveAt(removechoice); filterdata.RemoveAt(removechoice); watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } } catch (Exception ex) { WriteLine(ex.StackTrace); } } while (runprog); }
/// <summary> /// Saves the local Avatar /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void UploadUpdate_Click([NotNull] object sender, [NotNull] EventArgs e) { if (this.File.PostedFile == null || this.File.PostedFile.FileName.Trim().Length <= 0 || this.File.PostedFile.ContentLength <= 0) { return; } long x = this.Get <YafBoardSettings>().AvatarWidth; long y = this.Get <YafBoardSettings>().AvatarHeight; var avatarSize = this.Get <YafBoardSettings>().AvatarSize; Stream resized = null; try { using (var img = Image.FromStream(this.File.PostedFile.InputStream)) { if (img.Width > x || img.Height > y) { this.PageContext.AddLoadMessage( $"{this.GetTextFormatted("WARN_TOOBIG", x, y)} {this.GetTextFormatted("WARN_SIZE", img.Width, img.Height)} {this.GetText("CP_EDITAVATAR", "WARN_RESIZED")}"); resized = ImageHelper.GetResizedImageStreamFromImage(img, x, y); } } // Delete old first... this.GetRepository <User>().DeleteAvatar(this.currentUserId); if (this.Get <YafBoardSettings>().UseFileTable) { var image = Image.FromStream(resized ?? this.File.PostedFile.InputStream); var memoryStream = new MemoryStream(); image.Save(memoryStream, image.RawFormat); memoryStream.Position = 0; this.GetRepository <User>().SaveAvatar( this.currentUserId, null, memoryStream, this.File.PostedFile.ContentType); } else { var uploadFolderPath = this.Get <HttpRequestBase>().MapPath( string.Concat(BaseUrlBuilder.ServerFileRoot, YafBoardFolders.Current.Uploads)); // check if Uploads folder exists if (!Directory.Exists(uploadFolderPath)) { Directory.CreateDirectory(uploadFolderPath); } var fileName = this.File.PostedFile.FileName; var pos = fileName.LastIndexOfAny(new[] { '/', '\\' }); if (pos >= 0) { fileName = fileName.Substring(pos + 1); } // filename can be only 255 characters long (due to table column) if (fileName.Length > 255) { fileName = fileName.Substring(fileName.Length - 255); } var newFileName = $"{this.currentUserId}{Path.GetExtension(fileName)}"; var filePath = Path.Combine(uploadFolderPath, newFileName); // Delete old avatar if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } var avatarImage = Image.FromStream(resized ?? this.File.PostedFile.InputStream); using (var memory = new MemoryStream()) { using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite)) { avatarImage.Save(memory, avatarImage.RawFormat); var bytes = memory.ToArray(); fs.Write(bytes, 0, bytes.Length); } } this.GetRepository <User>().SaveAvatar( this.currentUserId, $"{YafForumInfo.ForumBaseUrl}{YafBoardFolders.Current.Uploads}/{newFileName}", null, null); } // clear the cache for this user... this.Get <IRaiseEvent>().Raise(new UpdateUserEvent(this.currentUserId)); if (avatarSize > 0 && this.File.PostedFile.ContentLength >= avatarSize && resized == null) { this.PageContext.AddLoadMessage( $"{this.GetTextFormatted("WARN_BIGFILE", avatarSize)} {this.GetTextFormatted("WARN_FILESIZE", this.File.PostedFile.ContentLength)}", MessageTypes.warning); } this.BindData(); } catch (Exception exception) { this.Logger.Log( exception.Message, EventLogTypes.Error, this.PageContext.CurrentUserData.UserName, string.Empty, exception); // image is probably invalid... this.PageContext.AddLoadMessage(this.GetText("CP_EDITAVATAR", "INVALID_FILE"), MessageTypes.danger); } }
public void Process(Map map, MapInfo info) { Grid <byte> heightMap = new Grid <byte>(map.HeightMap.MapWidth, map.HeightMap.MapHeight); if (AddObjects) { foreach (var o in map.Objects) { if (!o.IsWaypoint && o.RoadOptions == RoadOptions.None) { var coordinates = map.PositionToCoordinates(o.GetPosition()); if (info.Tiles[coordinates.X, coordinates.Y].HasFlag(TileInfo.Structure)) { heightMap[coordinates.X - map.HeightMap.Border, coordinates.Y - map.HeightMap.Border] = 255; } } } } using (MemoryStream tga = new MemoryStream()) { BinaryWriter writer = new BinaryWriter(tga); writer.Write((byte)0); // Id Length writer.Write((byte)0); // Cmap Type writer.Write((byte)10); // Image Type (TGA_RLERGB 10) writer.Write((UInt16)0); // Cmap Index writer.Write((UInt16)0); // Cmap Length writer.Write((byte)0); // Cmap Entry Size writer.Write((UInt16)0); // X Origin writer.Write((UInt16)0); // Y Origin writer.Write(Convert.ToUInt16(map.HeightMap.MapWidth)); // Image Width writer.Write(Convert.ToUInt16(map.HeightMap.MapHeight)); // Image Height writer.Write((byte)32); // Pixel Depth writer.Write((byte)0); // Imag Desc List <System.Drawing.Color> tgaPacket = new List <System.Drawing.Color>(); for (int j = 0; j < heightMap.Height; j++) { for (int i = 0; i < heightMap.Width; i++) { byte height = map.HeightMap[i + map.HeightMap.Border, j + map.HeightMap.Border]; if (height > heightMap[i, j]) { heightMap[i, j] = height; } Color pixel = Color.FromArgb(height, height, height); tgaPacket.Add(pixel); if (tgaPacket.Count == 128) { WriteTgaPacket(writer, tgaPacket); } } } WriteTgaPacket(writer, tgaPacket); lock (Lock) { BmpPreview = heightMap.ToArray(); TgaPreview = tga.ToArray(); } } }
public IProjectItemModel CreateProjectItem(string path, byte[] content, bool overwrite) { var contentStream = new MemoryStream(content); return CreateProjectItem(path, contentStream, overwrite); }
internal WebHeaderCollection WriteHeadersTo(MemoryStream destination) { var headers = new WebHeaderCollection(HttpHeaderType.Response, true); if (_headers != null) { headers.Add(_headers); } if (_contentType != null) { var type = _contentType.IndexOf("charset=", StringComparison.Ordinal) == -1 && _contentEncoding != null ? String.Format("{0}; charset={1}", _contentType, _contentEncoding.WebName) : _contentType; headers.InternalSet("Content-Type", type, true); } if (headers.GetOne("Server") == null) { headers.InternalSet("Server", "websocket-sharp/1.0", true); } var prov = CultureInfo.InvariantCulture; if (headers.GetOne("Date") == null) { headers.InternalSet("Date", DateTime.UtcNow.ToString("r", prov), true); } if (!_sendChunked) { headers.InternalSet("Content-Length", _contentLength.ToString(prov), true); } else { headers.InternalSet("Transfer-Encoding", "chunked", true); } /* * Apache forces closing the connection for these status codes: * - 400 Bad Request * - 408 Request Timeout * - 411 Length Required * - 413 Request Entity Too Large * - 414 Request-Uri Too Long * - 500 Internal Server Error * - 503 Service Unavailable */ var closeConn = !_context.Request.KeepAlive || !_keepAlive || _statusCode == 400 || _statusCode == 408 || _statusCode == 411 || _statusCode == 413 || _statusCode == 414 || _statusCode == 500 || _statusCode == 503; var reuses = _context.Connection.Reuses; if (closeConn || reuses >= 100) { headers.InternalSet("Connection", "close", true); } else { headers.InternalSet( "Keep-Alive", String.Format("timeout=15,max={0}", 100 - reuses), true); if (_context.Request.ProtocolVersion < HttpVersion.Version11) { headers.InternalSet("Connection", "keep-alive", true); } } if (_location != null) { headers.InternalSet("Location", _location, true); } if (_cookies != null) { foreach (Cookie cookie in _cookies) { headers.InternalSet("Set-Cookie", cookie.ToResponseString(), true); } } var enc = _contentEncoding ?? Encoding.Default; var writer = new StreamWriter(destination, enc, 256); writer.Write("HTTP/{0} {1} {2}\r\n", _version, _statusCode, _statusDescription); writer.Write(headers.ToStringMultiValue(true)); writer.Flush(); // Assumes that the destination was at position 0. destination.Position = enc.GetPreamble().Length; return(headers); }
public ActionResult LogoFoto(int ContratanteId, HttpPostedFileBase file) { ViewBag.ContratanteID = ContratanteId; int grupoId = (int)Geral.PegaAuthTicket("Grupo"); int usuarioId = (int)Geral.PegaAuthTicket("UsuarioId"); if (file == null) { ModelState.AddModelError("", "Escolha uma Imagem!"); } else { MemoryStream target = new MemoryStream(); file.InputStream.CopyTo(target); Bitmap imagem1 = (Bitmap)Image.FromStream(target); Bitmap imagemRedimensionada = ScaleImage(imagem1, 220, 130); MemoryStream novaImagem = new MemoryStream(); imagemRedimensionada.Save(novaImagem, System.Drawing.Imaging.ImageFormat.Png); Contratante contratante = Db.Contratante.FirstOrDefault(c => c.WFD_GRUPO.Any(g => g.ID == grupoId)); if (contratante != null) { contratante.LOGO_FOTO = novaImagem.ToArray(); //string extensao = (file.FileName.IndexOf(".") >= 0) ? file.FileName.Substring(file.FileName.IndexOf(".")) : ""; contratante.EXTENSAO_IMAGEM = ".png"; Db.Entry(contratante).State = EntityState.Modified; } Db.SaveChanges(); string caminhoFisico = Server.MapPath("/ImagensUsuarios"); string arquivo = "ImagemContratante" + contratante.ID + ".png"; string caminhoCompleto = caminhoFisico + "\\" + arquivo; System.IO.File.WriteAllBytes(caminhoCompleto, novaImagem.ToArray()); string dados = User.Identity.Name; dados = dados.Replace("semfoto.png", arquivo).Replace("semlogo.png", arquivo); var usuario = Db.WFD_USUARIO .Include("WAC_PERFIL.WAC_FUNCAO") .FirstOrDefault(u => u.ID == usuarioId); string roles = string.Empty; foreach (var perfil in usuario.WAC_PERFIL) { foreach (var funcao in perfil.WAC_FUNCAO) { if (!roles.Contains(funcao.CODIGO)) { roles += funcao.CODIGO + ","; } } } _metodosGerais.CriarAuthTicket(dados, roles); _metodosGerais.AuthenticateRequest(); ViewBag.MensagemSucesso = "Imagem Salva com sucesso!"; } return(View()); }
public void OnSaveDialog(Notification notification) { KeyValuePair <string, string> results = (KeyValuePair <string, string>)notification.data; String bot_transcript = results.Value; String user_transcript = results.Key; DateTime today = System.DateTime.Now; string key = today.ToString("yyyy-MM-dd") + "/" + PlayerPrefs.GetString("guid") + ".txt"; string dialogue = "{\"actor\": \"human\", \"msg\": \"" + user_transcript + "\", \"timestamp\": \"" + today.ToString() + "\"}\n" + "{\"actor\": \"bot\", \"msg\": \"" + bot_transcript + "\", \"timestamp\": \"" + today.ToString() + "\"}\n"; byte[] dialogueData = System.Text.Encoding.UTF8.GetBytes(dialogue); Stream stream = new MemoryStream(); int position = 0; try { s3Client.GetObjectAsync("unitychat", key, (responseObj) => { if (responseObj.Response != null) { var response = responseObj.Response; if (response.ResponseStream != null) { Stream inputStream = response.ResponseStream; byte[] buffer = new byte[16 * 1024]; int read; while ((read = inputStream.Read(buffer, 0, buffer.Length)) > 0) { stream.Write(buffer, 0, read); } position = (int)inputStream.Length; } } TextWriter writer = new StreamWriter(stream); writer.Write(dialogue); writer.Flush(); stream.Position = 0L; var request = new PostObjectRequest() { Region = RegionEndpoint.USEast1, Bucket = "unitychat", Key = key, InputStream = stream, CannedACL = S3CannedACL.PublicReadWrite }; try { s3Client.PostObjectAsync(request, (postResponseObj) => { if (postResponseObj.Exception == null) { Debug.Log(string.Format("object {0} posted to bucket", postResponseObj.Request.Key)); } else { Debug.Log(string.Format("receieved error {0}", postResponseObj.Exception.StackTrace)); } }); } catch (Exception e) { Debug.Log("exception: " + e.ToString()); } }); } catch (Exception ex) { Debug.Log("Amazon died trying to run:" + ex.Message); } }
public void InitBuffers() { _stream = new MemoryStream(); _writer = new EndianBinaryWriter(EndianBitConverter.Little, _stream); }
public BinaryWriter CreateStaticDictionaryCache() { staticDictionaryStream = new MemoryStream(); var writer = new BinaryWriter(staticDictionaryStream); return writer; }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; Hashtable hsh1; String strValue; Thread[] workers; ThreadStart ts1; Int32 iNumberOfWorkers = 15; Boolean fLoopExit; DictionaryEntry[] strValueArr; String[] strKeyArr; Hashtable hsh3; Hashtable hsh4; IDictionaryEnumerator idic; MemoryStream ms1; Boolean fPass; Object oValue; try { do { hsh1 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { hsh1.Add("Key_" + i, "Value_" + i); } hsh2 = Hashtable.Synchronized(hsh1); fPass = true; iCountTestcases++; if(hsh2.Count != hsh1.Count) { iCountErrors++; Console.WriteLine("Err_742dsf! Expected value not returned, " + hsh2.Count); } for(int i=0; i<iNumberOfElements; i++) { if(!((String)hsh2["Key_" + i]).Equals("Value_" + i)) { Console.WriteLine(hsh2["Key_" + i]); fPass = false; } } try { oValue = hsh2[null]; fPass = false; } catch(ArgumentNullException) { } catch(Exception) { fPass = false; } hsh2.Clear(); for(int i=0; i<iNumberOfElements; i++) { hsh2["Key_" + i] = "Value_" + i; } if(!fPass) { iCountErrors++; Console.WriteLine("Err_752dsgf! Oh man! This is busted!!!!"); } strValueArr = new DictionaryEntry[hsh2.Count]; hsh2.CopyTo(strValueArr, 0); hsh3 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { if(!hsh2.Contains("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742ds8f! Expected value not returned, " + hsh2.Contains("Key_" + i)); } if(!hsh2.ContainsKey("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hsh2.ContainsKey("Key_" + i)); } if(!hsh2.ContainsValue("Value_" + i)) { iCountErrors++; Console.WriteLine("Err_563fgd! Expected value not returned, " + hsh2.ContainsValue("Value_" + i)); } if(!hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)) { iCountErrors++; Console.WriteLine("Err_87429dsfd! Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value); } try { hsh3.Add(strValueArr[i], null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_74298dsd! Exception thrown for " + strValueArr[i]); } } hsh4 = (Hashtable)hsh2.Clone(); if(hsh4.Count != hsh1.Count) { iCountErrors++; Console.WriteLine("Err_342342! Expected value not returned, " + hsh4.Count); } strValueArr = new DictionaryEntry[hsh4.Count]; hsh4.CopyTo(strValueArr, 0); hsh3 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { if(!hsh4.Contains("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742ds8f! Expected value not returned, " + hsh4.Contains("Key_" + i)); } if(!hsh4.ContainsKey("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hsh4.ContainsKey("Key_" + i)); } if(!hsh4.ContainsValue("Value_" + i)) { iCountErrors++; Console.WriteLine("Err_6-4142dsf! Expected value not returned, " + hsh4.ContainsValue("Value_" + i)); } if(!hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)) { iCountErrors++; Console.WriteLine("Err_87429dsfd! Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value); } try { hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_74298dsd! Exception thrown for " + ((DictionaryEntry)strValueArr[i]).Value); } } if(hsh4.IsReadOnly) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsReadOnly); } if(!hsh4.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsSynchronized); } idic = hsh2.GetEnumerator(); hsh3 = new Hashtable(); hsh4 = new Hashtable(); while(idic.MoveNext()) { if(!hsh2.ContainsKey(idic.Key)) { iCountErrors++; Console.WriteLine("Err_4532sfds! Expected value not returned"); } if(!hsh2.ContainsValue(idic.Value)) { iCountErrors++; Console.WriteLine("Err_682wm! Expected value not returned"); } try { hsh3.Add(idic.Key, null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_5243sfd! Exception thrown for " + idic.Key); } try { hsh4.Add(idic.Value, null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_25sfs! Exception thrown for " + idic.Value); } } BinaryFormatter formatter = new BinaryFormatter(); ms1 = new MemoryStream(); formatter.Serialize(ms1, hsh2); ms1.Position = 0; hsh4 = (Hashtable)formatter.Deserialize(ms1); if(hsh4.Count != hsh1.Count) { iCountErrors++; Console.WriteLine("Err_072xsf! Expected value not returned, " + hsh4.Count); } strValueArr = new DictionaryEntry[hsh4.Count]; hsh4.CopyTo(strValueArr, 0); hsh3 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { if(!hsh4.Contains("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742ds8f! Expected value not returned, " + hsh4.Contains("Key_" + i)); } if(!hsh4.ContainsKey("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hsh4.ContainsKey("Key_" + i)); } if(!hsh4.ContainsValue("Value_" + i)) { iCountErrors++; Console.WriteLine("Err_0672esfs! Expected value not returned, " + hsh4.ContainsValue("Value_" + i)); } if(!hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)) { iCountErrors++; Console.WriteLine("Err_87429dsfd! Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value); } try { hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_74298dsd! Exception thrown for " + strValueArr[i]); } } if(hsh4.IsReadOnly) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsReadOnly); } if(!hsh4.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsSynchronized); } if(hsh2.IsReadOnly) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh2.IsReadOnly); } if(!hsh2.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh2.IsSynchronized); } if(hsh2.SyncRoot != hsh1) { iCountErrors++; Console.WriteLine("Err_7428dsafd! Expected value not returned, "); } String[] strValueArr11 = new String[hsh1.Count]; strKeyArr = new String[hsh1.Count]; hsh2.Keys.CopyTo(strKeyArr, 0); hsh2.Values.CopyTo(strValueArr11, 0); hsh3 = new Hashtable(); hsh4 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { if(!hsh2.ContainsKey(strKeyArr[i])) { iCountErrors++; Console.WriteLine("Err_4532sfds! Expected value not returned"); } if(!hsh2.ContainsValue(strValueArr11[i])) { iCountErrors++; Console.WriteLine("Err_074dsd! Expected value not returned, " + strValueArr11[i]); } try { hsh3.Add(strKeyArr[i], null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_5243sfd! Exception thrown for " + idic.Key); } try { hsh4.Add(strValueArr11[i], null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_25sfs! Exception thrown for " + idic.Value); } } hsh2.Remove("Key_1"); if(hsh2.ContainsKey("Key_1")) { iCountErrors++; Console.WriteLine("Err_423ewd! Expected value not returned, "); } if(hsh2.ContainsValue("Value_1")) { iCountErrors++; Console.WriteLine("Err_64q213d! Expected value not returned, "); } hsh2.Add("Key_1", "Value_1"); if(!hsh2.ContainsKey("Key_1")) { iCountErrors++; Console.WriteLine("Err_423ewd! Expected value not returned, "); } if(!hsh2.ContainsValue("Value_1")) { iCountErrors++; Console.WriteLine("Err_74523esf! Expected value not returned, "); } hsh2["Key_1"] = "Value_Modified_1"; if(!hsh2.ContainsKey("Key_1")) { iCountErrors++; Console.WriteLine("Err_423ewd! Expected value not returned, "); } if(hsh2.ContainsValue("Value_1")) { iCountErrors++; Console.WriteLine("Err_74523esf! Expected value not returned, "); } if(!hsh2.ContainsValue("Value_Modified_1")) { iCountErrors++; Console.WriteLine("Err_342fs! Expected value not returned, "); } hsh3 = Hashtable.Synchronized(hsh2); if(hsh3.Count != hsh1.Count) { iCountErrors++; Console.WriteLine("Err_742dsf! Expected value not returned, " + hsh3.Count); } if(!hsh3.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh3.IsSynchronized); } hsh2.Clear(); if(hsh2.Count != 0) { iCountErrors++; Console.WriteLine("Err_742dsf! Expected value not returned, " + hsh2.Count); } strLoc = "Loc_8345vdfv"; hsh1 = new Hashtable(); hsh2 = Hashtable.Synchronized(hsh1); workers = new Thread[iNumberOfWorkers]; ts1 = new ThreadStart(AddElements); for(int i=0; i<workers.Length; i++) { workers[i] = new Thread(ts1); workers[i].Name = "Thread worker " + i; workers[i].Start(); } while(true) { fLoopExit=false; for(int i=0; i<iNumberOfWorkers;i++) { if(workers[i].IsAlive) fLoopExit=true; } if(!fLoopExit) break; } iCountTestcases++; if(hsh2.Count != iNumberOfElements*iNumberOfWorkers) { iCountErrors++; Console.WriteLine("Err_75630fvbdf! Expected value not returned, " + hsh2.Count); } iCountTestcases++; for(int i=0; i<iNumberOfWorkers; i++) { for(int j=0; j<iNumberOfElements; j++) { strValue = "Thread worker " + i + "_" + j; if(!hsh2.Contains(strValue)) { iCountErrors++; Console.WriteLine("Err_452dvdf_" + i + "_" + j + "! Expected value not returned, " + strValue); } } } workers = new Thread[iNumberOfWorkers]; ts1 = new ThreadStart(RemoveElements); for(int i=0; i<workers.Length; i++) { workers[i] = new Thread(ts1); workers[i].Name = "Thread worker " + i; workers[i].Start(); } while(true) { fLoopExit=false; for(int i=0; i<iNumberOfWorkers;i++) { if(workers[i].IsAlive) fLoopExit=true; } if(!fLoopExit) break; } iCountTestcases++; if(hsh2.Count != 0) { iCountErrors++; Console.WriteLine("Err_6720fvdg! Expected value not returned, " + hsh2.Count); } iCountTestcases++; if(hsh1.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_4820fdf! Expected value not returned, " + hsh1.IsSynchronized); } iCountTestcases++; if(!hsh2.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_4820fdf! Expected value not returned, " + hsh2.IsSynchronized); } } while (false); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
/// <summary> /// Reads the specified content. /// </summary> /// <param name="content">The content.</param> static public CSequence ReadContent(MemoryStream content) { CParser parser = new CParser(content); CSequence sequence = parser.ReadContent(); return sequence; }
public BinaryWriter CreateDynamicDictionaryCache() { dynamicDictionaryStream = new MemoryStream(); var writer = new BinaryWriter(dynamicDictionaryStream); return writer; }
public static object DeSerialize(byte[] bytes, SerializedType type) { switch (type) { case SerializedType.String: return(Encoding.UTF8.GetString(bytes)); case SerializedType.Datetime: return(new DateTime(BitConverter.ToInt64(bytes, 0))); case SerializedType.Bool: return(bytes[0] == 1); case SerializedType.Byte: return(bytes[0]); case SerializedType.Short: return(BitConverter.ToInt16(bytes, 0)); case SerializedType.UShort: return(BitConverter.ToUInt16(bytes, 0)); case SerializedType.Int: return(BitConverter.ToInt32(bytes, 0)); case SerializedType.UInt: return(BitConverter.ToUInt32(bytes, 0)); case SerializedType.Long: return(BitConverter.ToInt64(bytes, 0)); case SerializedType.ULong: return(BitConverter.ToUInt64(bytes, 0)); case SerializedType.Float: return(BitConverter.ToSingle(bytes, 0)); case SerializedType.Double: return(BitConverter.ToDouble(bytes, 0)); case SerializedType.Object: using (MemoryStream ms = new MemoryStream(bytes)) { return(new BinaryFormatter().Deserialize(ms)); } case SerializedType.ObjectJson: return(Encoding.UTF8.GetString(bytes)); case SerializedType.CompressedByteArray: return(DeSerialize(decompress(bytes), SerializedType.ByteArray)); case SerializedType.CompressedString: return(DeSerialize(decompress(bytes), SerializedType.String)); case SerializedType.CompressedObject: return(DeSerialize(decompress(bytes), SerializedType.Object)); case SerializedType.CompressedObjectJson: return(DeSerialize(decompress(bytes), SerializedType.ObjectJson)); case SerializedType.ByteArray: default: return(bytes); } }
/// <summary> /// 序列化 /// </summary> /// <param name="value">值</param> /// <param name="type">返回序列化类型</param> /// <param name="compressionThreshold">指定超过长度时启用压缩功能</param> /// <returns></returns> public static byte[] Serialize(object value, out SerializedType type, uint compressionThreshold) { byte[] bytes; if (value is byte[]) { bytes = (byte[])value; type = SerializedType.ByteArray; if (bytes.Length > compressionThreshold) { bytes = compress(bytes); type = SerializedType.CompressedByteArray; } } else if (value is string) { bytes = Encoding.UTF8.GetBytes((string)value); type = SerializedType.String; if (bytes.Length > compressionThreshold) { bytes = compress(bytes); type = SerializedType.CompressedString; } } else if (value is DateTime) { bytes = BitConverter.GetBytes(((DateTime)value).Ticks); type = SerializedType.Datetime; } else if (value is bool) { bytes = new byte[] { (byte)((bool)value ? 1 : 0) }; type = SerializedType.Bool; } else if (value is byte) { bytes = new byte[] { (byte)value }; type = SerializedType.Byte; } else if (value is short) { bytes = BitConverter.GetBytes((short)value); type = SerializedType.Short; } else if (value is ushort) { bytes = BitConverter.GetBytes((ushort)value); type = SerializedType.UShort; } else if (value is int) { bytes = BitConverter.GetBytes((int)value); type = SerializedType.Int; } else if (value is uint) { bytes = BitConverter.GetBytes((uint)value); type = SerializedType.UInt; } else if (value is long) { bytes = BitConverter.GetBytes((long)value); type = SerializedType.Long; } else if (value is ulong) { bytes = BitConverter.GetBytes((ulong)value); type = SerializedType.ULong; } else if (value is float) { bytes = BitConverter.GetBytes((float)value); type = SerializedType.Float; } else if (value is double) { bytes = BitConverter.GetBytes((double)value); type = SerializedType.Double; } else { type = SerializedType.ObjectJson; Type t = value.GetType(); switch (StaticTool.GetSystemType(ref t)) { case SysType.Base: case SysType.Enum: case SysType.Custom: if (t.GetCustomAttributes(typeof(SerializableAttribute), false).Length > 0) { type = SerializedType.Object; } break; } if (type == SerializedType.Object) { //可序列化 List<object> 如果 object 不支持序列化,会挂。 using (MemoryStream ms = new MemoryStream()) { new BinaryFormatter().Serialize(ms, value); bytes = ms.ToArray(); if (bytes.Length > compressionThreshold) { bytes = compress(bytes); type = SerializedType.CompressedObject; } } } else { string json = JsonHelper.ToJson(value); bytes = Encoding.UTF8.GetBytes(json); if (bytes.Length > compressionThreshold) { bytes = compress(bytes); type = SerializedType.CompressedObjectJson; } } } return(bytes); }
public void Send(MemoryStream stream) { channel.Send(stream); }
/// <inheritdoc /> public virtual IDictionary<string, object> LoadTempData(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } // Accessing Session property will throw if the session middleware is not enabled. var session = context.Session; var tempDataDictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); byte[] value; if (session.TryGetValue(TempDataSessionStateKey, out value)) { using (var memoryStream = new MemoryStream(value)) using (var writer = new BsonReader(memoryStream)) { tempDataDictionary = _jsonSerializer.Deserialize<Dictionary<string, object>>(writer); } var convertedDictionary = new Dictionary<string, object>( tempDataDictionary, StringComparer.OrdinalIgnoreCase); foreach (var item in tempDataDictionary) { var jArrayValue = item.Value as JArray; var jObjectValue = item.Value as JObject; if (jArrayValue != null && jArrayValue.Count > 0) { var arrayType = jArrayValue[0].Type; Type returnType; if (_tokenTypeLookup.TryGetValue(arrayType, out returnType)) { var arrayConverter = _arrayConverters.GetOrAdd(returnType, type => { return (Func<JArray, object>)_convertArrayMethodInfo .MakeGenericMethod(type) .CreateDelegate(typeof(Func<JArray, object>)); }); var result = arrayConverter(jArrayValue); convertedDictionary[item.Key] = result; } else { var message = Resources.FormatTempData_CannotDeserializeToken(nameof(JToken), arrayType); throw new InvalidOperationException(message); } } else if (jObjectValue != null) { if (!jObjectValue.HasValues) { convertedDictionary[item.Key] = null; continue; } var jTokenType = jObjectValue.Properties().First().Value.Type; Type valueType; if (_tokenTypeLookup.TryGetValue(jTokenType, out valueType)) { var dictionaryConverter = _dictionaryConverters.GetOrAdd(valueType, type => { return (Func<JObject, object>)_convertDictMethodInfo .MakeGenericMethod(type) .CreateDelegate(typeof(Func<JObject, object>)); }); var result = dictionaryConverter(jObjectValue); convertedDictionary[item.Key] = result; } else { var message = Resources.FormatTempData_CannotDeserializeToken(nameof(JToken), jTokenType); throw new InvalidOperationException(message); } } else if (item.Value is long) { var longValue = (long)item.Value; if (longValue < int.MaxValue) { // BsonReader casts all ints to longs. We'll attempt to work around this by force converting // longs to ints when there's no loss of precision. convertedDictionary[item.Key] = (int)longValue; } } } tempDataDictionary = convertedDictionary; // If we got it from Session, remove it so that no other request gets it session.Remove(TempDataSessionStateKey); } else { // Since we call Save() after the response has been sent, we need to initialize an empty session // so that it is established before the headers are sent. session.Set(TempDataSessionStateKey, new byte[] { }); } return tempDataDictionary; }
static void Initialise() { LocalEvents = new SceneTriggerSet(); Checkpoint = new MemoryStream(); GlobalEvents = new HashSet<int>(); }
//public CompositeType GetDataUsingDataContract(CompositeType composite) //{ // if (composite == null) // { // throw new ArgumentNullException("composite"); // } // if (composite.BoolValue) // { // composite.StringValue += "Suffix"; // } // return composite; //} public int CreateSession(int serviceCategoryID, Guid userID, byte[] parameters, Decimal PeasCount, Decimal PeasValue) { //Where Magic happens Utils.Helper_Trace("MANAGER SERVICE", "Entering CreateSession()"); Utils.Helper_Trace("MANAGER SERVICE", string.Format("ServiceCategoryID = {0}", serviceCategoryID)); Utils.Helper_Trace("MANAGER SERVICE", string.Format("UserID = {0}", userID.ToString())); Dictionary<string, object> dicoParameters; try { MemoryStream ms; ms = new MemoryStream(parameters); BinaryFormatter bf; bf = new BinaryFormatter(); dicoParameters = (Dictionary<string, object>)bf.Deserialize(ms); } catch (Exception e) { Utils.Helper_Trace("MANAGER SERVICE", string.Format("Exception while deserializing parameters : {0}", e.Message)); return -1; } Utils.Helper_Trace("MANAGER SERVICE", string.Format("Size of parameters = {0} bytes", parameters.Length)); int[] tabAssetID = null; int MaxPages; string FileName = string.Empty; string nmapAddress = string.Empty; string cronExpression = string.Empty; string sip = string.Empty; string extrange = string.Empty; string policy = string.Empty; string strategie = string.Empty; switch (serviceCategoryID) //TODO Hardcoded { case 1: // Vulnerability Assessment tabAssetID = (int[])dicoParameters["ASSETS"]; cronExpression = (string)dicoParameters["CRONEXPRESSION"]; policy = (string)dicoParameters["POLICY"]; strategie = (string)dicoParameters["STRATEGY"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets = {0}", tabAssetID.Length)); Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression = {0}", cronExpression)); break; case 2: //WAS (Web Application Scanning) tabAssetID = (int[])dicoParameters["ASSETS"]; cronExpression = (string)dicoParameters["CRONEXPRESSION"]; policy = (string)dicoParameters["POLICY"]; strategie = (string)dicoParameters["STRATEGY"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets = {0}", tabAssetID.Length)); Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression = {0}", cronExpression)); break; case 3: Utils.Helper_Trace("MANAGER SERVICE", "NO parameters defined in XManagerService Service1.cs for service category 3"); break; case 4: //PCI DSS tabAssetID = (int[])dicoParameters["ASSETS"]; cronExpression = (string)dicoParameters["CRONEXPRESSION"]; policy = "PCI DSS"; strategie = "Compliance PCI DSS"; //(string)dicoParameters["STRATEGY"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets = {0}", tabAssetID.Length)); Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression = {0}", cronExpression)); break; case 5: Utils.Helper_Trace("MANAGER SERVICE", "NO parameters defined in XManagerService Service1.cs for service category 5"); break; case 6: // VOIP Scanner tabAssetID = (int[])dicoParameters["ASSETS"]; sip = (string)dicoParameters["SIP"]; extrange = (string)dicoParameters["EXTRANGE"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets = {0}", tabAssetID.Length)); break; case 7: // Web Anti-malware Monitoring tabAssetID = (int[])dicoParameters["ASSETS"]; cronExpression = (string)dicoParameters["CRONEXPRESSION"]; MaxPages = (int)dicoParameters["MaxPages"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Service Malware Monitoring:Number of assets = {0}", tabAssetID.Length)); Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression = {0}", cronExpression)); Utils.Helper_Trace("MANAGER SERVICE", string.Format("Service Malware Monitoring:MaxPages = {0}", MaxPages)); break; case 8: // Web Site Monitoring tabAssetID = (int[])dicoParameters["ASSETS"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets = {0}", tabAssetID.Length)); break; case 9: Utils.Helper_Trace("MANAGER SERVICE", "NO parameters defined in XManagerService Service1.cs for service category 9"); break; case 10: // Discovery nmapAddress = (string)dicoParameters["TARGET"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Target = {0}", nmapAddress)); break; case 11: case 12: case 13: // Import case 14: case 15: FileName = (string)dicoParameters["FILENAME"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Import File : Filename = {0}", FileName)); break; case 16: //Information Gathering (OSINT) tabAssetID = (int[])dicoParameters["ASSETS"]; cronExpression = (string)dicoParameters["CRONEXPRESSION"]; policy = (string)dicoParameters["POLICY"]; strategie = (string)dicoParameters["STRATEGY"]; Utils.Helper_Trace("MANAGER SERVICE", string.Format("Number of assets = {0}", tabAssetID.Length)); Utils.Helper_Trace("MANAGER SERVICE", string.Format("Cron Expression = {0}", cronExpression)); break; } XORCISMEntities context = new XORCISMEntities(); // =============================================== // Add a new entry in table SESSION or SESSIONCRON // =============================================== int id; if (cronExpression == "") { // ================================ // Add a new entry in table SESSION // ================================ Utils.Helper_Trace("MANAGER SERVICE", string.Format("Adding an entry in table SESSION")); SESSION tmpSession = new SESSION(); //Price try { tmpSession.UserID = userID; tmpSession.Status = XCommon.STATUS.IDLE.ToString(); tmpSession.ServiceCategoryID = serviceCategoryID; tmpSession.DateEnd = null; tmpSession.DateStart = DateTimeOffset.Now; tmpSession.Parameters = parameters; //Price context.SESSION.Add(tmpSession); context.SaveChanges(); //Price } catch (Exception ex) { /* USER user; user = context.USERS.SingleOrDefault(u => u.UserId == userID); ACCOUNT userAccount; userAccount = context.USERACCOUNT.SingleOrDefault(o => o.UserID == user.UserId).ACCOUNT; //Price */ Utils.Helper_Trace("MANAGER SERVICE", string.Format("Error adding entry in table SESSION : Exception = {0} - {1}", ex.Message, ex.InnerException.Message)); throw ex; } Utils.Helper_Trace("MANAGER SERVICE", string.Format("SessionID = {0}", tmpSession.SessionID)); //Random random = new Random(); try { // tmpSession.SessionID = tmpSession.SessionID + random.Next(20, 200); // context.SaveChanges(); } catch (Exception ex) { Utils.Helper_Trace("MANAGER SERVICE", string.Format("Error random SESSION : Exception = {0} - {1}", ex.Message, ex.InnerException.Message)); } Utils.Helper_Trace("MANAGER SERVICE", string.Format("NewRandomSessionID = {0}", tmpSession.SessionID)); id = tmpSession.SessionID; // ============================================ // Add several entries in table ASSETSESSION // ============================================ if (tabAssetID != null) { Utils.Helper_Trace("MANAGER SERVICE", string.Format("Adding {0} entries in table ASSETSESSION", tabAssetID.Count())); try { foreach (int assetID in tabAssetID) { ASSETSESSION tmpAinS = new ASSETSESSION(); tmpAinS.SESSION = tmpSession; tmpAinS.AssetID = assetID; context.ASSETSESSION.Add(tmpAinS); } context.SaveChanges(); } catch (Exception ex) { Utils.Helper_Trace("MANAGER SERVICE", string.Format("Error adding entries in table ASSETSESSION : Exception = {0}", ex.Message)); throw ex; } } } else { Utils.Helper_Trace("MANAGER SERVICE", string.Format("Adding an entry in table SESSIONCRON")); SESSIONCRON tmpSessionCron = new SESSIONCRON(); //Price try { tmpSessionCron.UserID = userID; tmpSessionCron.CronExpression = cronExpression; tmpSessionCron.Parameters = parameters; tmpSessionCron.Status = XCommon.STATUS.IDLE.ToString(); tmpSessionCron.ServiceCategoryID = serviceCategoryID; tmpSessionCron.DateStart = DateTimeOffset.Now; //TODO Non il faut que ce soit les dates de start/end du cron A VOIR TODO tmpSessionCron.DateEnd = null; //Price context.SESSIONCRON.Add(tmpSessionCron); context.SaveChanges(); } catch (Exception ex) { Utils.Helper_Trace("MANAGER SERVICE", string.Format("Error adding entry in table SESSIONCRON : Exception = {0} - {1}", ex.Message, ex.InnerException.Message)); throw ex; } Utils.Helper_Trace("MANAGER SERVICE", string.Format("SessionCronID = {0}", tmpSessionCron.SessionCronID)); id = tmpSessionCron.SessionCronID; } Utils.Helper_Trace("MANAGER SERVICE", "Leaving CreateSession()"); // Finished return id; }
public bool Open(IFilter imageFilter) { Stream stream = imageFilter.GetDataForkStream(); stream.Seek(0, SeekOrigin.Begin); if(stream.Length < 512) return false; byte[] vhdxIdB = new byte[Marshal.SizeOf(vhdxId)]; stream.Read(vhdxIdB, 0, Marshal.SizeOf(vhdxId)); vhdxId = new VhdxIdentifier(); IntPtr idPtr = Marshal.AllocHGlobal(Marshal.SizeOf(vhdxId)); Marshal.Copy(vhdxIdB, 0, idPtr, Marshal.SizeOf(vhdxId)); vhdxId = (VhdxIdentifier)Marshal.PtrToStructure(idPtr, typeof(VhdxIdentifier)); Marshal.FreeHGlobal(idPtr); if(vhdxId.signature != VHDX_SIGNATURE) return false; imageInfo.Application = Encoding.Unicode.GetString(vhdxId.creator); stream.Seek(64 * 1024, SeekOrigin.Begin); byte[] vHdrB = new byte[Marshal.SizeOf(vHdr)]; stream.Read(vHdrB, 0, Marshal.SizeOf(vHdr)); vHdr = new VhdxHeader(); IntPtr headerPtr = Marshal.AllocHGlobal(Marshal.SizeOf(vHdr)); Marshal.Copy(vHdrB, 0, headerPtr, Marshal.SizeOf(vHdr)); vHdr = (VhdxHeader)Marshal.PtrToStructure(headerPtr, typeof(VhdxHeader)); Marshal.FreeHGlobal(headerPtr); if(vHdr.Signature != VHDX_HEADER_SIG) { stream.Seek(128 * 1024, SeekOrigin.Begin); vHdrB = new byte[Marshal.SizeOf(vHdr)]; stream.Read(vHdrB, 0, Marshal.SizeOf(vHdr)); vHdr = new VhdxHeader(); headerPtr = Marshal.AllocHGlobal(Marshal.SizeOf(vHdr)); Marshal.Copy(vHdrB, 0, headerPtr, Marshal.SizeOf(vHdr)); vHdr = (VhdxHeader)Marshal.PtrToStructure(headerPtr, typeof(VhdxHeader)); Marshal.FreeHGlobal(headerPtr); if(vHdr.Signature != VHDX_HEADER_SIG) throw new ImageNotSupportedException("VHDX header not found"); } stream.Seek(192 * 1024, SeekOrigin.Begin); byte[] vRegTableB = new byte[Marshal.SizeOf(vRegHdr)]; stream.Read(vRegTableB, 0, Marshal.SizeOf(vRegHdr)); vRegHdr = new VhdxRegionTableHeader(); IntPtr vRegTabPtr = Marshal.AllocHGlobal(Marshal.SizeOf(vRegHdr)); Marshal.Copy(vRegTableB, 0, vRegTabPtr, Marshal.SizeOf(vRegHdr)); vRegHdr = (VhdxRegionTableHeader)Marshal.PtrToStructure(vRegTabPtr, typeof(VhdxRegionTableHeader)); Marshal.FreeHGlobal(vRegTabPtr); if(vRegHdr.signature != VHDX_REGION_SIG) { stream.Seek(256 * 1024, SeekOrigin.Begin); vRegTableB = new byte[Marshal.SizeOf(vRegHdr)]; stream.Read(vRegTableB, 0, Marshal.SizeOf(vRegHdr)); vRegHdr = new VhdxRegionTableHeader(); vRegTabPtr = Marshal.AllocHGlobal(Marshal.SizeOf(vRegHdr)); Marshal.Copy(vRegTableB, 0, vRegTabPtr, Marshal.SizeOf(vRegHdr)); vRegHdr = (VhdxRegionTableHeader)Marshal.PtrToStructure(vRegTabPtr, typeof(VhdxRegionTableHeader)); Marshal.FreeHGlobal(vRegTabPtr); if(vRegHdr.signature != VHDX_REGION_SIG) throw new ImageNotSupportedException("VHDX region table not found"); } vRegs = new VhdxRegionTableEntry[vRegHdr.entries]; for(int i = 0; i < vRegs.Length; i++) { byte[] vRegB = new byte[Marshal.SizeOf(vRegs[i])]; stream.Read(vRegB, 0, Marshal.SizeOf(vRegs[i])); vRegs[i] = new VhdxRegionTableEntry(); IntPtr vRegPtr = Marshal.AllocHGlobal(Marshal.SizeOf(vRegs[i])); Marshal.Copy(vRegB, 0, vRegPtr, Marshal.SizeOf(vRegs[i])); vRegs[i] = (VhdxRegionTableEntry)Marshal.PtrToStructure(vRegPtr, typeof(VhdxRegionTableEntry)); Marshal.FreeHGlobal(vRegPtr); if(vRegs[i].guid == batGuid) batOffset = (long)vRegs[i].offset; else if(vRegs[i].guid == metadataGuid) metadataOffset = (long)vRegs[i].offset; else if((vRegs[i].flags & REGION_FLAGS_REQUIRED) == REGION_FLAGS_REQUIRED) throw new ImageNotSupportedException($"Found unsupported and required region Guid {vRegs[i].guid}, not proceeding with image."); } if(batOffset == 0) throw new Exception("BAT not found, cannot continue."); if(metadataOffset == 0) throw new Exception("Metadata not found, cannot continue."); uint fileParamsOff = 0, vdSizeOff = 0, p83Off = 0, logOff = 0, physOff = 0, parentOff = 0; stream.Seek(metadataOffset, SeekOrigin.Begin); byte[] metTableB = new byte[Marshal.SizeOf(vMetHdr)]; stream.Read(metTableB, 0, Marshal.SizeOf(vMetHdr)); vMetHdr = new VhdxMetadataTableHeader(); IntPtr metTablePtr = Marshal.AllocHGlobal(Marshal.SizeOf(vMetHdr)); Marshal.Copy(metTableB, 0, metTablePtr, Marshal.SizeOf(vMetHdr)); vMetHdr = (VhdxMetadataTableHeader)Marshal.PtrToStructure(metTablePtr, typeof(VhdxMetadataTableHeader)); Marshal.FreeHGlobal(metTablePtr); vMets = new VhdxMetadataTableEntry[vMetHdr.entries]; for(int i = 0; i < vMets.Length; i++) { byte[] vMetB = new byte[Marshal.SizeOf(vMets[i])]; stream.Read(vMetB, 0, Marshal.SizeOf(vMets[i])); vMets[i] = new VhdxMetadataTableEntry(); IntPtr vMetPtr = Marshal.AllocHGlobal(Marshal.SizeOf(vMets[i])); Marshal.Copy(vMetB, 0, vMetPtr, Marshal.SizeOf(vMets[i])); vMets[i] = (VhdxMetadataTableEntry)Marshal.PtrToStructure(vMetPtr, typeof(VhdxMetadataTableEntry)); Marshal.FreeHGlobal(vMetPtr); if(vMets[i].itemId == fileParametersGuid) fileParamsOff = vMets[i].offset; else if(vMets[i].itemId == virtualDiskSizeGuid) vdSizeOff = vMets[i].offset; else if(vMets[i].itemId == page83DataGuid) p83Off = vMets[i].offset; else if(vMets[i].itemId == logicalSectorSizeGuid) logOff = vMets[i].offset; else if(vMets[i].itemId == physicalSectorSizeGuid) physOff = vMets[i].offset; else if(vMets[i].itemId == parentLocatorGuid) parentOff = vMets[i].offset; else if((vMets[i].flags & METADATA_FLAGS_REQUIRED) == METADATA_FLAGS_REQUIRED) throw new ImageNotSupportedException($"Found unsupported and required metadata Guid {vMets[i].itemId}, not proceeding with image."); } byte[] tmp; if(fileParamsOff != 0) { stream.Seek(fileParamsOff + metadataOffset, SeekOrigin.Begin); tmp = new byte[8]; stream.Read(tmp, 0, 8); vFileParms = new VhdxFileParameters { blockSize = BitConverter.ToUInt32(tmp, 0), flags = BitConverter.ToUInt32(tmp, 4) }; } else throw new Exception("File parameters not found."); if(vdSizeOff != 0) { stream.Seek(vdSizeOff + metadataOffset, SeekOrigin.Begin); tmp = new byte[8]; stream.Read(tmp, 0, 8); virtualDiskSize = BitConverter.ToUInt64(tmp, 0); } else throw new Exception("Virtual disk size not found."); if(p83Off != 0) { stream.Seek(p83Off + metadataOffset, SeekOrigin.Begin); tmp = new byte[16]; stream.Read(tmp, 0, 16); page83Data = new Guid(tmp); } if(logOff != 0) { stream.Seek(logOff + metadataOffset, SeekOrigin.Begin); tmp = new byte[4]; stream.Read(tmp, 0, 4); logicalSectorSize = BitConverter.ToUInt32(tmp, 0); } else throw new Exception("Logical sector size not found."); if(physOff != 0) { stream.Seek(physOff + metadataOffset, SeekOrigin.Begin); tmp = new byte[4]; stream.Read(tmp, 0, 4); physicalSectorSize = BitConverter.ToUInt32(tmp, 0); } else throw new Exception("Physical sector size not found."); if(parentOff != 0 && (vFileParms.flags & FILE_FLAGS_HAS_PARENT) == FILE_FLAGS_HAS_PARENT) { stream.Seek(parentOff + metadataOffset, SeekOrigin.Begin); byte[] vParHdrB = new byte[Marshal.SizeOf(vMetHdr)]; stream.Read(vParHdrB, 0, Marshal.SizeOf(vMetHdr)); vParHdr = new VhdxParentLocatorHeader(); IntPtr vParHdrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(vMetHdr)); Marshal.Copy(vParHdrB, 0, vParHdrPtr, Marshal.SizeOf(vMetHdr)); vParHdr = (VhdxParentLocatorHeader)Marshal.PtrToStructure(vParHdrPtr, typeof(VhdxParentLocatorHeader)); Marshal.FreeHGlobal(vParHdrPtr); if(vParHdr.locatorType != parentTypeVhdxGuid) throw new ImageNotSupportedException($"Found unsupported and required parent locator type {vParHdr.locatorType}, not proceeding with image."); vPars = new VhdxParentLocatorEntry[vParHdr.keyValueCount]; for(int i = 0; i < vPars.Length; i++) { byte[] vParB = new byte[Marshal.SizeOf(vPars[i])]; stream.Read(vParB, 0, Marshal.SizeOf(vPars[i])); vPars[i] = new VhdxParentLocatorEntry(); IntPtr vParPtr = Marshal.AllocHGlobal(Marshal.SizeOf(vPars[i])); Marshal.Copy(vParB, 0, vParPtr, Marshal.SizeOf(vPars[i])); vPars[i] = (VhdxParentLocatorEntry)Marshal.PtrToStructure(vParPtr, typeof(VhdxParentLocatorEntry)); Marshal.FreeHGlobal(vParPtr); } } else if((vFileParms.flags & FILE_FLAGS_HAS_PARENT) == FILE_FLAGS_HAS_PARENT) throw new Exception("Parent locator not found."); if((vFileParms.flags & FILE_FLAGS_HAS_PARENT) == FILE_FLAGS_HAS_PARENT && vParHdr.locatorType == parentTypeVhdxGuid) { parentImage = new Vhdx(); bool parentWorks = false; foreach(VhdxParentLocatorEntry parentEntry in vPars) { stream.Seek(parentEntry.keyOffset + metadataOffset, SeekOrigin.Begin); byte[] tmpKey = new byte[parentEntry.keyLength]; stream.Read(tmpKey, 0, tmpKey.Length); string entryType = Encoding.Unicode.GetString(tmpKey); IFilter parentFilter; if(string.Compare(entryType, RELATIVE_PATH_KEY, StringComparison.OrdinalIgnoreCase) == 0) { stream.Seek(parentEntry.valueOffset + metadataOffset, SeekOrigin.Begin); byte[] tmpVal = new byte[parentEntry.valueLength]; stream.Read(tmpVal, 0, tmpVal.Length); string entryValue = Encoding.Unicode.GetString(tmpVal); try { parentFilter = new FiltersList().GetFilter(Path.Combine(imageFilter.GetParentFolder(), entryValue)); if(parentFilter != null && parentImage.Open(parentFilter)) { parentWorks = true; break; } } catch { parentWorks = false; } string relEntry = Path.Combine(Path.GetDirectoryName(imageFilter.GetPath()), entryValue); try { parentFilter = new FiltersList().GetFilter(Path.Combine(imageFilter.GetParentFolder(), relEntry)); if(parentFilter == null || !parentImage.Open(parentFilter)) continue; parentWorks = true; break; } catch { // ignored } } else if(string.Compare(entryType, VOLUME_PATH_KEY, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(entryType, ABSOLUTE_WIN32_PATH_KEY, StringComparison.OrdinalIgnoreCase) == 0) { stream.Seek(parentEntry.valueOffset + metadataOffset, SeekOrigin.Begin); byte[] tmpVal = new byte[parentEntry.valueLength]; stream.Read(tmpVal, 0, tmpVal.Length); string entryValue = Encoding.Unicode.GetString(tmpVal); try { parentFilter = new FiltersList().GetFilter(Path.Combine(imageFilter.GetParentFolder(), entryValue)); if(parentFilter == null || !parentImage.Open(parentFilter)) continue; parentWorks = true; break; } catch { // ignored } } } if(!parentWorks) throw new Exception("Image is differential but parent cannot be opened."); hasParent = true; } chunkRatio = (long)(Math.Pow(2, 23) * logicalSectorSize / vFileParms.blockSize); dataBlocks = virtualDiskSize / vFileParms.blockSize; if(virtualDiskSize % vFileParms.blockSize > 0) dataBlocks++; long batEntries; if(hasParent) { long sectorBitmapBlocks = (long)dataBlocks / chunkRatio; if(dataBlocks % (ulong)chunkRatio > 0) sectorBitmapBlocks++; sectorBitmapPointers = new ulong[sectorBitmapBlocks]; batEntries = sectorBitmapBlocks * (chunkRatio - 1); } else batEntries = (long)(dataBlocks + (dataBlocks - 1) / (ulong)chunkRatio); DicConsole.DebugWriteLine("VHDX plugin", "Reading BAT"); long readChunks = 0; blockAllocationTable = new ulong[dataBlocks]; byte[] batB = new byte[batEntries * 8]; stream.Seek(batOffset, SeekOrigin.Begin); stream.Read(batB, 0, batB.Length); ulong skipSize = 0; for(ulong i = 0; i < dataBlocks; i++) if(readChunks == chunkRatio) { if(hasParent) sectorBitmapPointers[skipSize / 8] = BitConverter.ToUInt64(batB, (int)(i * 8 + skipSize)); readChunks = 0; skipSize += 8; } else { blockAllocationTable[i] = BitConverter.ToUInt64(batB, (int)(i * 8 + skipSize)); readChunks++; } if(hasParent) { DicConsole.DebugWriteLine("VHDX plugin", "Reading Sector Bitmap"); MemoryStream sectorBmpMs = new MemoryStream(); foreach(ulong pt in sectorBitmapPointers) switch(pt & BAT_FLAGS_MASK) { case SECTOR_BITMAP_NOT_PRESENT: sectorBmpMs.Write(new byte[1048576], 0, 1048576); break; case SECTOR_BITMAP_PRESENT: stream.Seek((long)((pt & BAT_FILE_OFFSET_MASK) * 1048576), SeekOrigin.Begin); byte[] bmp = new byte[1048576]; stream.Read(bmp, 0, bmp.Length); sectorBmpMs.Write(bmp, 0, bmp.Length); break; default: if((pt & BAT_FLAGS_MASK) != 0) throw new ImageNotSupportedException($"Unsupported sector bitmap block flags (0x{pt & BAT_FLAGS_MASK:X16}) found, not proceeding."); break; } sectorBitmap = sectorBmpMs.ToArray(); sectorBmpMs.Close(); } maxBlockCache = (int)(MAX_CACHE_SIZE / vFileParms.blockSize); maxSectorCache = (int)(MAX_CACHE_SIZE / logicalSectorSize); imageStream = stream; sectorCache = new Dictionary<ulong, byte[]>(); blockCache = new Dictionary<ulong, byte[]>(); imageInfo.CreationTime = imageFilter.GetCreationTime(); imageInfo.LastModificationTime = imageFilter.GetLastWriteTime(); imageInfo.MediaTitle = Path.GetFileNameWithoutExtension(imageFilter.GetFilename()); imageInfo.SectorSize = logicalSectorSize; imageInfo.XmlMediaType = XmlMediaType.BlockMedia; imageInfo.MediaType = MediaType.GENERIC_HDD; imageInfo.ImageSize = virtualDiskSize; imageInfo.Sectors = imageInfo.ImageSize / imageInfo.SectorSize; imageInfo.DriveSerialNumber = page83Data.ToString(); // TODO: Separate image application from version, need several samples. imageInfo.Cylinders = (uint)(imageInfo.Sectors / 16 / 63); imageInfo.Heads = 16; imageInfo.SectorsPerTrack = 63; return true; }
public static Image bytes2Image(byte[] bytes) { MemoryStream ms = new MemoryStream(bytes); return Image.FromStream(ms); }
public void WriteThrowsForNullData() { using var stream = new MemoryStream(); var cfgWriter = new XmlConfigurationWriter(); cfgWriter.Write(stream, null); } /* End of Function - WriteThrowsForNullData */
public void TestUncompressThisRow() { var data = new byte[] { 0x09, 0x00, 0x2e, 0x07, 0x00, 0xad, 0x03, 0x00, 0x2e, 0x03, 0x10, 0xaf, 0xf5, 0x2f, 0xaf, 0xf5, 0x03, 0x0c, 0xf5, 0xaf, 0x5f, 0x5f, 0x0b, }; var data2 = new byte[] { 0x09, 0x00, 0x2e, 0x07, 0x00, 0xad, 0x03, 0x00, 0x2e, 0x03, 0x10, 0xaf, 0xf5, 0x2f, 0xaf, 0xf5, 0x03, 0x04, 0xf5, 0xaf, 0x06, 0x5f, 0x0b, }; var s = new MemoryStream(); CompressedFrameReader.DecompressRow(data, s, 27, 9); var ss = s.ToArray(); var s2 = new MemoryStream(); CompressedFrameReader.DecompressRow(data2, s2, 27, 9); var ss2 = s.ToArray(); CollectionAssert.AreEqual(ss, ss2); }
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return(sample); }
public async Task <IActionResult> FilePreview(IFormFileCollection files) //System.Web HttpPostedFileBase file) { var resImport = new ResultCrmDb(); if ((Request.Form?.Files?.Count ?? 0) != 1) { resImport.AddError(Constant.ErrCodeImport, "Файла для импорта не передан!"); return(Tools.CreateResult(true, "Файла не передан!", resImport)); } var formfile = Request.Form.Files[0]; if (formfile.Length > 500000) { resImport.AddError(Constant.ErrCodeImport, "Размер файла превышает 500кБ !"); return(Tools.CreateResult(false, "Файл слшком длинный !", resImport)); } var filename = formfile.FileName; var fileextension = Path.GetExtension(filename).ToUpper(); if (fileextension.Length < 4 || !allowedExtensions.Split(',').Any(x => fileextension.StartsWith(x.Trim()))) { resImport.AddError(Constant.ErrCodeImport, "Файл с таким расширением не импортируется !"); return(Tools.CreateResult(true, "Файла не передан!", resImport)); } using (var memoryStream = new MemoryStream()) { byte[] bytesUtf = null; await formfile.CopyToAsync(memoryStream); if (fileextension == ".XLSX") { // Уже Utf bytesUtf = memoryStream.ToArray(); } else { var enc = CodePagesEncodingProvider.Instance.GetEncoding(1251); var bytes1251 = memoryStream.ToArray(); //var txt1251 = enc.GetString(bytes1251, 0, bytes1251.Length); bytesUtf = Encoding.Convert(enc, Encoding.UTF8, bytes1251); } //string txtUtf = Encoding.UTF8.GetString(bytesUtf); ImportParam importParam = new ImportParam() { FileName = filename, FormatGroup = fileextension == ".XLSX" ? "MFXL" : "FKTX", Format = fileextension == ".XLSX" ? "VP" : fileextension.Substring(1, 2), TypeImp = ImportType.Preview, CodeAte = "004", // ГО Волоколамский CodePos = "00", DaysToSkip = 1 }; resImport = await _importAdapter.PreviewFile(bytesUtf, importParam); return(Tools.CreateResult(true, "", resImport)); } }
/// <summary> /// Executes command buffers until we hit the next resultset /// </summary> /// <returns>CommandResult containing the next resultset when hit /// or null if no more resultsets were found</returns> internal CommandResult GetNextResultSet(MySqlDataReader reader) { // if we are supposed to return only a single resultset and our reader // is calling us back again, then return null if (reader != null && (reader.Behavior & CommandBehavior.SingleResult) != 0 && lastResult != null) { return(null); } // if the last result we returned has more results if (lastResult != null && lastResult.ReadNextResult(false)) { return(lastResult); } lastResult = null; CommandResult result = null; // if we haven't prepared a statement and don't have any sql buffers // to execute, we are done if (preparedStatement == null) { if (sqlBuffers == null || sqlBuffers.Count == 0) { return(null); } } else if (preparedStatement.ExecutionCount > 0) { return(null); } // if we have a prepared statement, we execute it instead if (preparedStatement != null) { result = preparedStatement.Execute(parameters); if (!result.IsResultSet) { if (updateCount == -1) { updateCount = 0; } updateCount += (long)result.AffectedRows; } } else { while (sqlBuffers.Count > 0) { MemoryStream sqlStream = (MemoryStream)sqlBuffers[0]; using (sqlStream) { result = connection.driver.SendQuery(sqlStream.GetBuffer(), (int)sqlStream.Length, false); sqlBuffers.RemoveAt(0); } if (result.AffectedRows != -1) { if (updateCount == -1) { updateCount = 0; } updateCount += (long)result.AffectedRows; } // if this is a resultset, then we break out of our execution loop if (result.IsResultSet) { break; } } } if (result.IsResultSet) { lastResult = result; return(result); } return(null); }
private static byte[] rsaEncrypt(byte[] buffer /*, string key*/) { RSAParameters rsaParameters; if (_cachedPublicKey is null) { _cachedPublicKey = ParsePublicKey(publicKey); } rsaParameters = _cachedPublicKey.Value; return(BigInteger.ModPow(GetBigIntegerBigEndian(buffer), GetBigIntegerBigEndian(rsaParameters.Exponent), GetBigIntegerBigEndian(rsaParameters.Modulus)).ToByteArray(true, true)); RSAParameters ParsePublicKey(string _publicKey) { _publicKey = _publicKey.Replace("\n", string.Empty); _publicKey = _publicKey.Substring(26, _publicKey.Length - 50); using (MemoryStream _stream = new MemoryStream(Convert.FromBase64String(_publicKey))) { using (BinaryReader _reader = new BinaryReader(_stream)) { ushort _i16; byte[] _oid; byte _i8; byte _low; byte _high; int _modulusLength; byte[] _modulus; int _exponentLength; byte[] _exponent; _i16 = _reader.ReadUInt16(); if (_i16 == 0x8130) { _reader.ReadByte(); } else if (_i16 == 0x8230) { _reader.ReadInt16(); } else { throw new ArgumentException(nameof(_publicKey)); } _oid = _reader.ReadBytes(15); if (!_oid.SequenceEqual(new byte[] { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 })) { throw new ArgumentException(nameof(_publicKey)); } _i16 = _reader.ReadUInt16(); if (_i16 == 0x8103) { _reader.ReadByte(); } else if (_i16 == 0x8203) { _reader.ReadInt16(); } else { throw new ArgumentException(nameof(_publicKey)); } _i8 = _reader.ReadByte(); if (_i8 != 0x00) { throw new ArgumentException(nameof(_publicKey)); } _i16 = _reader.ReadUInt16(); if (_i16 == 0x8130) { _reader.ReadByte(); } else if (_i16 == 0x8230) { _reader.ReadInt16(); } else { throw new ArgumentException(nameof(_publicKey)); } _i16 = _reader.ReadUInt16(); if (_i16 == 0x8102) { _high = 0; _low = _reader.ReadByte(); } else if (_i16 == 0x8202) { _high = _reader.ReadByte(); _low = _reader.ReadByte(); } else { throw new ArgumentException(nameof(_publicKey)); } _modulusLength = BitConverter.ToInt32(new byte[] { _low, _high, 0x00, 0x00 }, 0); if (_reader.PeekChar() == 0x00) { _reader.ReadByte(); _modulusLength -= 1; } _modulus = _reader.ReadBytes(_modulusLength); if (_reader.ReadByte() != 0x02) { throw new ArgumentException(nameof(_publicKey)); } _exponentLength = _reader.ReadByte(); _exponent = _reader.ReadBytes(_exponentLength); return(new RSAParameters { Modulus = _modulus, Exponent = _exponent }); } } } BigInteger GetBigIntegerBigEndian(byte[] _value) { return(new BigInteger(new ReadOnlySpan <byte>(_value), true, true)); } }
/// <summary> /// Update the navigation property singleValueExtendedProperties in users /// </summary> public Command BuildPatchCommand() { var command = new Command("patch"); command.Description = "Update the navigation property singleValueExtendedProperties in users"; // Create options for all the parameters var userIdOption = new Option <string>("--user-id", description: "key: id of user") { }; userIdOption.IsRequired = true; command.AddOption(userIdOption); var mailFolderIdOption = new Option <string>("--mail-folder-id", description: "key: id of mailFolder") { }; mailFolderIdOption.IsRequired = true; command.AddOption(mailFolderIdOption); var messageIdOption = new Option <string>("--message-id", description: "key: id of message") { }; messageIdOption.IsRequired = true; command.AddOption(messageIdOption); var singleValueLegacyExtendedPropertyIdOption = new Option <string>("--single-value-legacy-extended-property-id", description: "key: id of singleValueLegacyExtendedProperty") { }; singleValueLegacyExtendedPropertyIdOption.IsRequired = true; command.AddOption(singleValueLegacyExtendedPropertyIdOption); var bodyOption = new Option <string>("--body") { }; bodyOption.IsRequired = true; command.AddOption(bodyOption); command.SetHandler(async(object[] parameters) => { var userId = (string)parameters[0]; var mailFolderId = (string)parameters[1]; var messageId = (string)parameters[2]; var singleValueLegacyExtendedPropertyId = (string)parameters[3]; var body = (string)parameters[4]; var cancellationToken = (CancellationToken)parameters[5]; using var stream = new MemoryStream(Encoding.UTF8.GetBytes(body)); var parseNode = ParseNodeFactoryRegistry.DefaultInstance.GetRootParseNode("application/json", stream); var model = parseNode.GetObjectValue <SingleValueLegacyExtendedProperty>(SingleValueLegacyExtendedProperty.CreateFromDiscriminatorValue); var requestInfo = CreatePatchRequestInformation(model, q => { }); requestInfo.PathParameters.Add("user%2Did", userId); requestInfo.PathParameters.Add("mailFolder%2Did", mailFolderId); requestInfo.PathParameters.Add("message%2Did", messageId); requestInfo.PathParameters.Add("singleValueLegacyExtendedProperty%2Did", singleValueLegacyExtendedPropertyId); var errorMapping = new Dictionary <string, ParsableFactory <IParsable> > { { "4XX", ODataError.CreateFromDiscriminatorValue }, { "5XX", ODataError.CreateFromDiscriminatorValue }, }; await RequestAdapter.SendNoContentAsync(requestInfo, errorMapping: errorMapping, cancellationToken: cancellationToken); Console.WriteLine("Success"); }, new CollectionBinding(userIdOption, mailFolderIdOption, messageIdOption, singleValueLegacyExtendedPropertyIdOption, bodyOption, new TypeBinding(typeof(CancellationToken)))); return(command); }
public MemoryStream RenderToBitmapStream(IViewport viewport, IEnumerable<ILayer> layers, Color background = null) { MemoryStream bitmapStream = null; RunMethodOnStaThread(() => bitmapStream = RenderToBitmapStreamStatic(viewport, layers, _symbolCache)); return bitmapStream; }
public IEnumerator readAMFList(MemoryStream memoryStream, IConfigVODB configVodb) { AMFReader reader = new AMFReader(memoryStream); byte typeCode = reader.ReadByte(); //DebugX.Log("typeCode:"+typeCode); if (typeCode != 9) { yield break; } Type type = configVodb.dbInstanceType; int handle = reader.ReadAMF3IntegerData(); bool inline = ((handle & 1) != 0); handle = handle >> 1; if (inline) { hashtable = null; string key = reader.ReadAMF3String(); object value; while (key != null && key != string.Empty) { if (hashtable == null) { hashtable = new Dictionary <string, object>(); reader.AddAMF3ObjectReference(hashtable); } value = reader.ReadAMF3Data(); hashtable.Add(key, value); key = reader.ReadAMF3String(); } //Not an associative array if (hashtable == null) { object[] array = new object[handle]; reader.AddAMF3ObjectReference(array); //long startParserTime = DateTime.Now.Ticks; FieldInfo[] fieldInfos = type.GetFields(); fieldInfosDic.Clear(); string fieldName; for (int i = 0, len = fieldInfos.Length; i < len; i++) { fieldName = fieldInfos[i].Name; if (fieldInfosDic.ContainsKey(fieldName) == false) { fieldInfosDic.Add(fieldName, fieldInfos[i]); } } for (int i = 0; i < handle; i++) { typeCode = reader.ReadByte(); if (typeCode == 10) { array[i] = ReadAMF3Object(reader, configVodb); } else { array[i] = reader.ReadAMF3Data(typeCode); } if (i % 1000 == 0) { yield return(null); } } //DebugX.Log("tt:" + (DateTime.Now.Ticks - startParserTime) / 10000); result = array; } else { for (int i = 0; i < handle; i++) { value = reader.ReadAMF3Data(); hashtable.Add(i.ToString(), value); } result = (IList)hashtable; } } else { result = (IList)reader.ReadAMF3ObjectReference(handle); } }
/// <summary> /// Prepares the necessary byte buffers from the given CommandText /// </summary> /// <returns>Array of byte buffers, one for each SQL command</returns> /// <remarks> /// Converts the CommandText into an array of tokens /// using TokenizeSql and then into one or more byte buffers that can be /// sent to the server. If the server supports batching (and we have enabled it), /// then all commands result in a single byte array, otherwise a single buffer /// is created for each SQL command (as separated by ';'). /// The SQL text is converted to bytes using the active encoding for the server. /// </remarks> private ArrayList PrepareSqlBuffers(string sql) { ArrayList buffers = new ArrayList(); PacketWriter writer = new PacketWriter(); writer.Encoding = connection.Encoding; writer.Version = connection.driver.Version; // if we are executing as a stored procedure, then we need to add the call // keyword. if (CommandType == CommandType.StoredProcedure) { if (storedProcedure == null) { storedProcedure = new StoredProcedure(connection); } sql = storedProcedure.Prepare(this); } // tokenize the SQL sql = sql.TrimStart(';').TrimEnd(';'); ArrayList tokens = TokenizeSql(sql); foreach (string token in tokens) { if (token.Trim().Length == 0) { continue; } if (token == ";" && !connection.driver.SupportsBatch) { MemoryStream ms = (MemoryStream)writer.Stream; if (ms.Length > 0) { buffers.Add(ms); } writer = new PacketWriter(); writer.Encoding = connection.Encoding; writer.Version = connection.driver.Version; continue; } else if (token[0] == parameters.ParameterMarker) { if (SerializeParameter(writer, token)) { continue; } } // our fall through case is to write the token to the byte stream writer.WriteStringNoNull(token); } // capture any buffer that is left over MemoryStream mStream = (MemoryStream)writer.Stream; if (mStream.Length > 0) { buffers.Add(mStream); } return(buffers); }