public virtual void Post(string url, Dictionary<string, string> data, System.Action<HttpResult> onResult) {
	
		this.MakeRequest(url, HttpMethods.POST, onResult, (r) => {

			JSONObject js = new JSONObject(data);
			var requestPayload = js.ToString();

			UTF8Encoding encoding = new UTF8Encoding();
			r.ContentLength = encoding.GetByteCount(requestPayload);
			r.Credentials = CredentialCache.DefaultCredentials;
			r.Accept = "application/json";
			r.ContentType = "application/json";
			
			//Write the payload to the request body.
			using ( Stream requestStream = r.GetRequestStream())
			{
				requestStream.Write(encoding.GetBytes(requestPayload), 0,
				                    encoding.GetByteCount(requestPayload));
			}

			return false;

		});

	}
 public void PosTest2()
 {
     Char[] chars = new Char[] { };
     UTF8Encoding utf8 = new UTF8Encoding();
     int byteCount = utf8.GetByteCount(chars, 0, 0);
     Assert.Equal(0, byteCount);
 }
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method GetByteCount(Char[],Int32,Int32) with non-null char[]");

        try
        {
            Char[] chars = new Char[] {
                            '\u0023', 
                            '\u0025', 
                            '\u03a0', 
                            '\u03a3'  };

            UTF8Encoding utf8 = new UTF8Encoding();
            int byteCount = utf8.GetByteCount(chars, 1, 2);

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method GetByteCount(string) with non-null string");

        try
        {
            String chars = "UTF8 Encoding Example";

            UTF8Encoding utf8 = new UTF8Encoding();
            int byteCount = utf8.GetByteCount(chars);

            if (byteCount != chars.Length)
            {
                TestLibrary.TestFramework.LogError("001.1", "Method GetByteCount Err.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
 public void PosTest2()
 {
     String chars = "";
     UTF8Encoding utf8 = new UTF8Encoding();
     int byteCount = utf8.GetByteCount(chars);
     Assert.Equal(0, byteCount);
 }
 public void PosTest1()
 {
     String chars = "UTF8 Encoding Example";
     UTF8Encoding utf8 = new UTF8Encoding();
     int byteCount = utf8.GetByteCount(chars);
     Assert.Equal(chars.Length, byteCount);
 }
    public bool PosTest2()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method GetByteCount(Char[],Int32,Int32) with null char[]");

        try
        {
            Char[] chars = new Char[] { };

            UTF8Encoding utf8 = new UTF8Encoding();
            int byteCount = utf8.GetByteCount(chars, 0, 0);

            if (byteCount != 0)
            {
                TestLibrary.TestFramework.LogError("001.1", "Method GetByteCount Err.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
 public void NegTest1()
 {
     Char[] chars = null;
     UTF8Encoding utf8 = new UTF8Encoding();
     Assert.Throws<ArgumentNullException>(() =>
     {
         int byteCount = utf8.GetByteCount(chars, 0, 0);
     });
 }
 public void PosTest1()
 {
     Char[] chars = new Char[] {
                     '\u0023',
                     '\u0025',
                     '\u03a0',
                     '\u03a3'  };
     UTF8Encoding utf8 = new UTF8Encoding();
     int byteCount = utf8.GetByteCount(chars, 1, 2);
 }
Esempio n. 10
0
    public bool EnsureThreadCreated(string title, string message, string thread_identifier)
    {
        try
        {
            string forum_api_key = ConfigurationManager.ConnectionStrings["DisqusForumAPI"].ConnectionString;
            string post_data = "forum_api_key=" + HttpUtility.UrlEncode(forum_api_key) +
                "&title=" + HttpUtility.UrlEncode(title) +
                "&identifier=" + HttpUtility.UrlEncode(thread_identifier);
            UTF8Encoding enc = new UTF8Encoding();

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://disqus.com/api/thread_by_identifier/");
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = enc.GetByteCount(post_data);

            using (Stream req_stream = req.GetRequestStream())
            {
                req_stream.Write(enc.GetBytes(post_data), 0, enc.GetByteCount(post_data));
            }

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            string resp_str = "";

            // We don't really care what the response is, apart from success/fail
            // And no need to parse the JSON response, so long as it says '"succeeded": true' somewhere

            using (Stream resp_stream = resp.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(resp_stream))
                {
                    resp_str = reader.ReadToEnd();
                }
            }

            return resp_str.Contains("\"succeeded\": true");
        }
        catch
        {
            return false;
        }
    }
Esempio n. 11
0
        public void PosTest2()
        {
            Byte[] bytes;
            Char[] chars = new Char[] { };

            UTF8Encoding utf8 = new UTF8Encoding();

            int byteCount = utf8.GetByteCount(chars, 0, 0);
            bytes = new Byte[byteCount];
            int charsEncodedCount = utf8.GetChars(bytes, 0, 0, chars, 0);
            Assert.Equal(0, charsEncodedCount);
        }
 public void NegTest3()
 {
     Char[] chars = new Char[] {
                     '\u0023',
                     '\u0025',
                     '\u03a0',
                     '\u03a3'  };
     UTF8Encoding utf8 = new UTF8Encoding();
     Assert.Throws<ArgumentOutOfRangeException>(() =>
     {
         int byteCount = utf8.GetByteCount(chars, 1, -2);
     });
 }
Esempio n. 13
0
        public void PosTest1()
        {
            Byte[] bytes;
            Char[] chars = new Char[] {
                            '\u0023',
                            '\u0025',
                            '\u03a0',
                            '\u03a3'  };

            UTF8Encoding utf8 = new UTF8Encoding();
            int byteCount = utf8.GetByteCount(chars, 1, 2);
            bytes = new Byte[byteCount];
            int charsEncodedCount = utf8.GetChars(bytes, 1, 2, chars, 0);
        }
Esempio n. 14
0
        public void NegTest2()
        {
            Byte[] bytes;
            Char[] chars = new Char[] {
                            '\u0023',
                            '\u0025',
                            '\u03a0',
                            '\u03a3'  };
            UTF8Encoding utf8 = new UTF8Encoding();

            int byteCount = utf8.GetByteCount(chars, 1, 2);
            bytes = null;
            Assert.Throws<ArgumentNullException>(() =>
            {
                int bytesEncodedCount = utf8.GetBytes(chars, 1, 2, bytes, 0);
            });
        }
Esempio n. 15
0
        /// <summary>
        /// Writes a string to the stream; supported wire-types: String
        /// </summary>
        public static void WriteString(string value, ProtoWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }
            if (writer.wireType != WireType.String)
            {
                throw CreateException(writer);
            }
            if (value == null)
            {
                throw new ArgumentNullException("value");                // written header; now what?
            }
            int len = value.Length;

            if (len == 0)
            {
                WriteUInt32Variant(0, writer);
                writer.wireType = WireType.None;
                return; // just a header
            }
#if MF
            byte[] bytes  = encoding.GetBytes(value);
            int    actual = bytes.Length;
            writer.WriteUInt32Variant((uint)actual);
            writer.Ensure(actual);
            Helpers.BlockCopy(bytes, 0, writer.ioBuffer, writer.ioIndex, actual);
#else
            int predicted = encoding.GetByteCount(value);
            WriteUInt32Variant((uint)predicted, writer);
            DemandSpace(predicted, writer);
            int actual = encoding.GetBytes(value, 0, value.Length, writer.ioBuffer, writer.ioIndex);
            Helpers.DebugAssert(predicted == actual);
#endif
            IncrementedAndReset(actual, writer);
        }
Esempio n. 16
0
        public void WriteAMF3XmlDocument(XmlDocument value)
        {
            this.WriteByte(11);
            string s = string.Empty;

            if ((value.DocumentElement != null) && (value.DocumentElement.OuterXml != null))
            {
                s = value.DocumentElement.OuterXml;
            }
            if (s == string.Empty)
            {
                this.WriteAMF3IntegerData(1);
            }
            else
            {
                int num2;
                if (!this._objectReferences.ContainsKey(value))
                {
                    this._objectReferences.Add(value, this._objectReferences.Count);
                    UTF8Encoding encoding = new UTF8Encoding();
                    num2  = encoding.GetByteCount(s) << 1;
                    num2 |= 1;
                    this.WriteAMF3IntegerData(num2);
                    byte[] bytes = encoding.GetBytes(s);
                    if (bytes.Length > 0)
                    {
                        this.Write(bytes);
                    }
                }
                else
                {
                    num2 = this._objectReferences[value];
                    num2 = num2 << 1;
                    this.WriteAMF3IntegerData(num2);
                }
            }
        }
Esempio n. 17
0
        public void WriteAMF3XElement(XElement xElement)
        {
            this.WriteByte(11);
            string key = string.Empty;

            if (xElement != null)
            {
                key = xElement.ToString();
            }
            if (key == string.Empty)
            {
                this.WriteAMF3IntegerData(1);
            }
            else
            {
                int num2;
                if (!this._objectReferences.ContainsKey(key))
                {
                    this._objectReferences.Add(key, this._objectReferences.Count);
                    UTF8Encoding encoding = new UTF8Encoding();
                    num2  = encoding.GetByteCount(key) << 1;
                    num2 |= 1;
                    this.WriteAMF3IntegerData(num2);
                    byte[] bytes = encoding.GetBytes(key);
                    if (bytes.Length > 0)
                    {
                        this.Write(bytes);
                    }
                }
                else
                {
                    num2 = this._objectReferences[key];
                    num2 = num2 << 1;
                    this.WriteAMF3IntegerData(num2);
                }
            }
        }
Esempio n. 18
0
        public static void ConvertTableToInsertSatements(DataTable dt, FileStream fs)
        {
            List <string>   insert       = new List <string>();
            UTF8Encoding    utf8Encoding = new UTF8Encoding();
            UnicodeEncoding uniEncoding  = new  UnicodeEncoding();

            fs.Seek(0, SeekOrigin.End);
            foreach (DataRow r in dt.Rows)
            {
                string newinsert = "(";
                var    length    = r.ItemArray.Length;
                for (int i = 0; i < length; i++)
                {
                    newinsert += $"'{r.ItemArray[i].ToString()}'";
                    if (i < length - 1)
                    {
                        newinsert += ",";
                    }
                }
                newinsert += ")\r\n";
                fs.Write(utf8Encoding.GetBytes(newinsert), 0, utf8Encoding.GetByteCount(newinsert));
            }
            fs.Flush();
        }
Esempio n. 19
0
        private HttpWebRequest ManufactureRequest(ApiRequest apiRequest)
        {
            string value = "";

            if (apiRequest.Args != null && apiRequest.Args.Count > 0)
            {
                apiRequest.Args.ForEach(e => value += e.Key + "=" + System.Uri.EscapeDataString(e.Value) + "&");
                value = value.Trim('&');
            }

            if (apiRequest.Method == "GET" && !string.IsNullOrEmpty(value))
            {
                apiRequest.Url += "?" + value;
            }

            var authRequest = (HttpWebRequest)HttpWebRequest.Create(apiRequest.Url);

            authRequest.Method      = apiRequest.Method;
            authRequest.ContentType = apiRequest.ContentType;
            authRequest.Credentials = CredentialCache.DefaultNetworkCredentials;

            authRequest.Headers.Add(GetAuthHeader());

            if (apiRequest.Method == "POST" || apiRequest.Method == "PUT")
            {
                var utd8WithoutBom = new UTF8Encoding(false);

                value += apiRequest.Data;
                authRequest.ContentLength = utd8WithoutBom.GetByteCount(value);
                using (var writer = new StreamWriter(authRequest.GetRequestStream(), utd8WithoutBom))
                {
                    writer.Write(value);
                }
            }
            return(authRequest);
        }
Esempio n. 20
0
        internal static unsafe byte[] GetBytes(string str, SerializerSession session, out int byteCount)
        {
            //if first byte is 0 = null
            //if first byte is 254 or less, then length is value - 1
            //if first byte is 255 then the next 4 bytes are an int32 for length
            if (str == null)
            {
                byteCount = 1;
                return(new[] { (byte)0 });
            }
            byteCount = Utf8.GetByteCount(str);
            if (byteCount < 254) //short string
            {
                var bytes = session.GetBuffer(byteCount + 1);
                Utf8.GetBytes(str, 0, str.Length, bytes, 1);
                bytes[0]   = (byte)(byteCount + 1);
                byteCount += 1;
                return(bytes);
            }
            else //long string
            {
                var bytes = session.GetBuffer(byteCount + 1 + 4);
                Utf8.GetBytes(str, 0, str.Length, bytes, 1 + 4);
                bytes[0] = 255;


                fixed(byte *b = bytes)
                {
                    *(int *)(b + 1) = byteCount;
                }

                byteCount += 1 + 4;

                return(bytes);
            }
        }
Esempio n. 21
0
    public bool NegTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentNullException is not thrown when chars is a null reference  ");

        try
        {
            Byte[] bytes;
            Char[] chars = new Char[] {
                '\u0023',
                '\u0025',
                '\u03a0',
                '\u03a3'
            };

            UTF8Encoding utf8 = new UTF8Encoding();

            int byteCount = utf8.GetByteCount(chars, 1, 2);
            bytes = new Byte[byteCount];
            chars = null;
            int charsEncodedCount = utf8.GetChars(bytes, 1, 2, chars, 0);

            TestLibrary.TestFramework.LogError("102.1", "ArgumentNullException is not thrown when chars is a null reference  ");
            retVal = false;
        }
        catch (ArgumentNullException) { }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return(retVal);
    }
Esempio n. 22
0
        /* Comments regarding AddHeader
         *
         * This way of adding the total point count in first line
         * is a bit dodgy. The reason is we write a line with many spaces
         * and after writing all the points go back and the replace
         * some of the spaces with numbers. This means
         * that the header will always have some spaces trailing the count number.
         * Fortunately most pts readers don't mind these extra spaces
         * and this method is magnitudes faster than the alternative.
         * The alternative would be to loop all point twice:
         * either rewrite all points to disk in a new file or
         * loop all count points first
         * and then write points to disk in a second loop.
         */
        private static void AddHeader(string FullPath, string HeaderText)
        {
            FileStream   fStream = null;
            UTF8Encoding utf8    = new UTF8Encoding();

            try
            {
                fStream          = File.Open(FullPath, FileMode.Open, FileAccess.ReadWrite);
                fStream.Position = 0;
                fStream.Write(utf8.GetBytes(HeaderText), 0, utf8.GetByteCount(HeaderText));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error while writing header");
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (fStream != null)
                {
                    fStream.Close();
                }
            }
        }
Esempio n. 23
0
        public static bool TruncateUTF8(ref string value, int limit)
        {
            if (string.IsNullOrEmpty(value) || Encoding.GetByteCount(value) <= limit)
            {
                return(false);
            }

            var charArray = new char[1];
            var length    = 0;

            for (var i = 0; i < value.Length - 1; i++)
            {
                charArray[0] = value[i];
                length      += Encoding.GetByteCount(charArray, 0, 1);
                if (length > limit)
                {
                    value = value.Substring(0, i);
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 24
0
        /*************************************************************************
         * Output
         *
         * output the log message to the log file
         *
         * **********************************************************************/

        private void Output(string msg)
        {
            /* Check whether some LogCtl somewhere is needing to rename the file
             * ----------------------------------------------------------------- */

            if (m_RenameEvent != null)
            {
                try
                {
                    while (!m_RenameEvent.WaitOne(0, true))
                    {
                        if (m_fs != null)
                        {
                            m_fs.Flush();
                            m_fs.Close();
                            m_fs.Dispose();
                            m_fs = null;
                        }

                        /* Some other logctl instance has reset the RenameEvent event
                         * ----------------------------------------------------------
                         * so wait up to 30 seconds for it to be reset */

                        if (!m_RenameEvent.WaitOne(30 * 1000, true))
                        {
                            /* Can't wait any longer
                             * --------------------- */

                            EmergencyMessage(EventLogEntryType.Warning, "The RenameEvent has been set for more than 30 seconds.");
                        }
                    }
                }
                catch (AbandonedMutexException e)
                {
                    EmergencyMessage(EventLogEntryType.Error, string.Format("The Global Rename Event has been abandoned. {0}", e.Message));
                }
            }

            if (m_fs == null)
            {
                Trace("Filestream closed. Opening a new one");
                try
                {
                    m_fs = new FileStream(m_Filename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
                }
                catch (Exception e)
                {
                    throw new Exception(string.Format("Failed to open {0}. {1}", m_Filename, e.Message));
                }
            }
            if (!TryLock())
            {
                EmergencyMessage(EventLogEntryType.Error, string.Format("Lock failed. msg={0}", msg));
            }
            UTF8Encoding ue = new UTF8Encoding();

            try
            {
                m_fs.Write(ue.GetBytes(msg), 0, ue.GetByteCount(msg));
                m_fs.Flush();
            }
            catch (Exception e)
            {
                EmergencyMessage(EventLogEntryType.Error, string.Format("Write failure to log file {0}. {1}", m_Filename, e.Message));
            }

            if (!TryUnlock())
            {
                EmergencyMessage(EventLogEntryType.Error, "Failed to unlock file.");
            }
        }
Esempio n. 25
0
        static void Main(string[] args)
        {
            // --- Various conversions between strings and arrays of char or byte. ---

            // Converting a string to an array of chars.
            Console.WriteLine("Convert a string to an array of chars.");
            string custName = "Pam III Sphar";

            char[] custNameChars = custName.ToCharArray();
            foreach (char c in custNameChars)
            {
                Console.Write(c);
            }
            Console.WriteLine();

            // Converting an array of chars to a string.
            Console.WriteLine("\nConvert an array of chars to a string.");
            char[] chars         = { 'a', 'b', 'c', 'd' };
            string charsAsString = new String(chars);

            Console.WriteLine("Chars a - d as a string: {0}", charsAsString);

            // Converting an array of bytes to a string.
            Console.WriteLine("\nUse an 'encoding' to convert an array "
                              + "of bytes to a string.");
            byte[]       bytes = { 80,  97, 109, 32, 73, 73, 73, 32,
                                   83,       112, 104, 97, 114 };
            UTF8Encoding encoding = new UTF8Encoding();
            string       name     = encoding.GetString(bytes, 0, bytes.Length);

            Console.WriteLine(name);

            // Converting a string to a byte array.
            Console.WriteLine("\nConvert a string to a byte array.");
            int numBytesInString = encoding.GetByteCount(custName); // 13.

            // Note: WriteLine() lets you specify 'placeholders,' {0}, {1},
            // and so on. It fills the placehoders with the variables or values
            // listed after the quoted string containing the placeholders.
            // See the Tip in the section "Formatting Your Strings Precisely"
            // in Chapter 6.
            Console.WriteLine("custName 'Pam III Sphar' has {0} chars.",
                              numBytesInString);
            byte[] theBytes = encoding.GetBytes(custName);
            Console.WriteLine("Retrieved {0} bytes from custName 'Pam III Sphar'.",
                              theBytes.Length);
            // List the bytes in a row.
            foreach (byte b in theBytes)
            {
                Console.Write(b + " ");
            }
            Console.WriteLine();

            // --- Using "cultures" ---

            // Using a 'culture' to make string comparison more accurate.
            Console.WriteLine("\nSpecifying a \"culture\" in string comparison.");
            // A culture tells the Compare() method how to understand strings from
            // a particular culture, such as 'en-US' (American), 'en-GB' (British),
            // 'fr-FR' (French in France), etc. Such strings may use various
            // diacritical marks such as umlauts, cedillas, and 'enyas'. Cultures
            // also govern currency, number, and date formatting. Using cultures
            // helps you write versions of your software suitable for use in various
            // countries and language communities, a process called "localizing" your code.
            // This is the briefest and barest introduction to cultures. See Help.
            Console.WriteLine("Is the string 'SOME STUFF' already uppercase?");
            string line = "SOME STUFF";

            // "InvariantCulture" means a culture specific to English (wthout reference to
            // any regional variants) and is used is the general default culture in many
            // cases. Look up "CultureInfo class" in the Help index for more information.)
            if (string.Compare(line.ToUpper(CultureInfo.InvariantCulture), line, false) == 0)
            {
                Console.WriteLine("yes 1");
            }
            if (string.Compare(line, "line", StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                Console.WriteLine("yes 2");
            }

            // --- Techniques for uppercasing the first char of a string ---

            // Uppercasing the first char in a string without StringBuilder.
            Console.WriteLine("\nUppercase the first char of a string in various ways:");
            // Use a combination of char and string methods.
            name = "chuck";
            string properName = char.ToUpper(name[0]).ToString() +
                                name.Substring(1, name.Length - 1);

            Console.WriteLine("{0} becomes {1}", name, properName);

            // Uppercasing the first char with a StringBuilder.
            Console.WriteLine("\nUse a StringBuilder to solve the problem of uppercasing "
                              + "just the first char of a string.");
            StringBuilder sb = new StringBuilder("jones");

            sb[0] = char.ToUpper(sb[0]);
            string fixedString = sb.ToString();

            Console.WriteLine("{0} becomes {1}", "jones", fixedString);

            Console.WriteLine("\nPress Enter to terminate...");
            Console.Read();
        }
Esempio n. 26
0
 public void WriteString(string value)
 {
     UTF8Encoding utf8Encoding = new UTF8Encoding();
     int byteCount = utf8Encoding.GetByteCount(value);
     byte[] buffer = utf8Encoding.GetBytes(value);
     this.WriteShort(byteCount);
     if (buffer.Length > 0)
         Write(buffer);
 }
Esempio n. 27
0
 public void NegTest6()
 {
     Byte[] bytes;
     Char[] chars = new Char[] {
                     '\u0023',
                     '\u0025',
                     '\u03a0',
                     '\u03a3'  };
     UTF8Encoding utf8 = new UTF8Encoding();
     int byteCount = utf8.GetByteCount(chars, 1, 2);
     bytes = new Byte[byteCount];
     Assert.Throws<ArgumentOutOfRangeException>(() =>
     {
         int bytesEncodedCount = utf8.GetBytes(chars, 1, chars.Length, bytes, 1);
     });
 }
Esempio n. 28
0
 public static int GetByteCount(ReadOnlySpan <char> val) => val.IsEmpty ? 0 : UTF8.GetByteCount(val);
Esempio n. 29
0
        public XmlDocument MakeAPICall(string requestBody, string callname, string error)
        {
            XmlDocument xmlDoc = new XmlDocument();

            //string APISandBoxServerURL = ConfigurationManager.AppSettings["APISandboxServerURL"];

            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(APISandBoxServerURL);

            string APIServerURL = ConfigurationManager.AppSettings["APIServerURL"];

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(APIServerURL);

            //Add the request headers
            //-------------------------------------------------------------------------
            //Add the keys


            request.Headers.Add("X-EBAY-API-DEV-NAME", ConfigurationManager.AppSettings["EbaydevId"]);
            request.Headers.Add("X-EBAY-API-APP-NAME", ConfigurationManager.AppSettings["EbayappId"]);
            request.Headers.Add("X-EBAY-API-CERT-NAME", ConfigurationManager.AppSettings["EbaycertId"]);

            //Add the version
            request.Headers.Add("X-EBAY-API-COMPATIBILITY-LEVEL", ConfigurationManager.AppSettings["Version"]);

            //Add the SiteID
            request.Headers.Add("X-EBAY-API-SITEID", ConfigurationManager.AppSettings["SiteID"]);

            //Add the call name
            request.Headers.Add("X-EBAY-API-CALL-NAME", callname);

            //Set the request properties
            request.Method      = "POST";
            request.ContentType = "text/xml";
            //-------------------------------------------------------------------------

            //Put the data into a UTF8 encoded  byte array
            UTF8Encoding encoding = new UTF8Encoding();
            int          dataLen  = encoding.GetByteCount(requestBody);

            byte[] utf8Bytes = new byte[dataLen];
            Encoding.UTF8.GetBytes(requestBody, 0, requestBody.Length, utf8Bytes, 0);

            Stream str = null;

            try
            {
                //Set the request Stream
                str = request.GetRequestStream();
                //Write the request to the Request Steam
                str.Write(utf8Bytes, 0, utf8Bytes.Length);
                str.Close();
                //Get response into stream
                WebResponse response = request.GetResponse();
                str = response.GetResponseStream();

                // Get Response into String
                StreamReader sr = new StreamReader(str);
                xmlDoc.LoadXml(sr.ReadToEnd());
                sr.Close();
                str.Close();
            }
            catch (Exception Ex)
            {
                error = Ex.Message;
                System.Web.HttpContext.Current.Response.Write("error=" + error);
            }
            return(xmlDoc);
        }
Esempio n. 30
0
        internal static int GetTextStringEncodedSize(string value)
        {
            int strEncodedLength = s_utf8EncodingStrict.GetByteCount(value);

            return(GetIntegerEncodedSize(strEncodedLength) + strEncodedLength);
        }
Esempio n. 31
0
        public override void WriteToStream(Stream outputStream)
        {
            Int32 messageLength = 4 + UTF8Encoding.GetByteCount(_portalName) + 1 +
                                  UTF8Encoding.GetByteCount(_preparedStatementName) + 1 + 2 + (_parameterFormatCodes.Length * 2) +
                                  2;


            // Get size of parameter values.
            Int32 i;

            if (_parameterValues != null)
            {
                for (i = 0; i < _parameterValues.Length; i++)
                {
                    messageLength += 4;
                    if (_parameterValues[i] != null)
                    {
                        if (((_parameterFormatCodes.Length == 1) && (_parameterFormatCodes[0] == (Int16)FormatCode.Binary)) ||
                            ((_parameterFormatCodes.Length != 1) && (_parameterFormatCodes[i] == (Int16)FormatCode.Binary)))
                        {
                            messageLength += ((Byte[])_parameterValues[i]).Length;
                        }
                        else
                        {
                            messageLength += UTF8Encoding.GetByteCount((String)_parameterValues[i]);
                        }
                    }
                }
            }

            messageLength += 2 + (_resultFormatCodes.Length * 2);


            outputStream.WriteByte((byte)FrontEndMessageCode.Bind);

            PGUtil.WriteInt32(outputStream, messageLength);
            PGUtil.WriteString(_portalName, outputStream);
            PGUtil.WriteString(_preparedStatementName, outputStream);

            PGUtil.WriteInt16(outputStream, (Int16)_parameterFormatCodes.Length);

            for (i = 0; i < _parameterFormatCodes.Length; i++)
            {
                PGUtil.WriteInt16(outputStream, _parameterFormatCodes[i]);
            }

            if (_parameterValues != null)
            {
                PGUtil.WriteInt16(outputStream, (Int16)_parameterValues.Length);

                for (i = 0; i < _parameterValues.Length; i++)
                {
                    if (((_parameterFormatCodes.Length == 1) && (_parameterFormatCodes[0] == (Int16)FormatCode.Binary)) ||
                        ((_parameterFormatCodes.Length != 1) && (_parameterFormatCodes[i] == (Int16)FormatCode.Binary)))
                    {
                        Byte[] parameterValue = (Byte[])_parameterValues[i];
                        if (parameterValue == null)
                        {
                            PGUtil.WriteInt32(outputStream, -1);
                        }
                        else
                        {
                            PGUtil.WriteInt32(outputStream, parameterValue.Length);
                            outputStream.Write(parameterValue, 0, parameterValue.Length);
                        }
                    }
                    else
                    {
                        if ((_parameterValues[i] == null))
                        {
                            PGUtil.WriteInt32(outputStream, -1);
                        }
                        else
                        {
                            Byte[] parameterValueBytes = UTF8Encoding.GetBytes((String)_parameterValues[i]);
                            PGUtil.WriteInt32(outputStream, parameterValueBytes.Length);
                            outputStream.Write(parameterValueBytes, 0, parameterValueBytes.Length);
                        }
                    }
                }
            }
            else
            {
                PGUtil.WriteInt16(outputStream, 0);
            }

            PGUtil.WriteInt16(outputStream, (Int16)_resultFormatCodes.Length);
            for (i = 0; i < _resultFormatCodes.Length; i++)
            {
                PGUtil.WriteInt16(outputStream, _resultFormatCodes[i]);
            }
        }
Esempio n. 32
0
        protected static int GetUTF8StringLength(string s)
        {
            UTF8Encoding enc = new UTF8Encoding();

            return(enc.GetByteCount(s));
        }
    public bool NegTest4()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentOutOfRangeException is not thrown when index and count do not denote a valid range in chars.");

        try
        {
            Char[] chars = new Char[] {
                            '\u0023', 
                            '\u0025', 
                            '\u03a0', 
                            '\u03a3'  };

            UTF8Encoding utf8 = new UTF8Encoding();
            int byteCount = utf8.GetByteCount(chars, 1, chars.Length);

            TestLibrary.TestFramework.LogError("104.1", "ArgumentOutOfRangeException is not thrown when index and count do not denote a valid range in chars.");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException) { }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("104.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Esempio n. 34
0
        private ApiResponse Get(ApiRequest apiRequest)
        {
            string value = "";

            if (apiRequest.Args != null && apiRequest.Args.Count > 0)
            {
                apiRequest.Args.ForEach(e => value += e.Key + "=" + System.Uri.EscapeDataString(e.Value) + "&");
                value = value.Trim('&');
            }

            if (apiRequest.Method == "GET" && !string.IsNullOrEmpty(value))
            {
                apiRequest.Url += "?" + value;
            }

            var authRequest = (HttpWebRequest)HttpWebRequest.Create(apiRequest.Url);

            authRequest.Method      = apiRequest.Method;
            authRequest.ContentType = apiRequest.ContentType;
            authRequest.Credentials = CredentialCache.DefaultNetworkCredentials;

            authRequest.Headers.Add(GetAuthHeader());

            if (apiRequest.Method == "POST" || apiRequest.Method == "PUT")
            {
                var utd8WithoutBom = new UTF8Encoding(false);

                value += apiRequest.Data;
                authRequest.ContentLength = utd8WithoutBom.GetByteCount(value);
                using (var writer = new StreamWriter(authRequest.GetRequestStream(), utd8WithoutBom))
                {
                    writer.Write(value);
                }
            }

            var    authResponse = (HttpWebResponse)authRequest.GetResponse();
            string content      = "";

            using (var reader = new StreamReader(authResponse.GetResponseStream(), Encoding.UTF8))
            {
                content = reader.ReadToEnd();
            }

            if ((string.IsNullOrEmpty(content) ||
                 content.ToLower() == "null") &&
                authResponse.StatusCode == HttpStatusCode.OK &&
                authResponse.Method == "DELETE")
            {
                var rsp = new ApiResponse();
                rsp.Data = new JObject();
                rsp.related_data_updated_at = DateTime.Now;
                rsp.StatusCode = authResponse.StatusCode;
                rsp.Method     = authResponse.Method;

                return(rsp);
            }

            try
            {
                ApiResponse rsp = content.ToLower() == "null"
                                        ? new ApiResponse {
                    Data = null
                }
                                        : JsonConvert.DeserializeObject <ApiResponse>(content);

                rsp.StatusCode = authResponse.StatusCode;
                rsp.Method     = authResponse.Method;
                return(rsp);
            }
            catch (Exception)
            {
                var token = JToken.Parse(content);
                var rsp   = new ApiResponse()
                {
                    Data = token,
                    related_data_updated_at = DateTime.Now,
                    StatusCode = authResponse.StatusCode,
                    Method     = authResponse.Method
                };
                return(rsp);
            }
        }
Esempio n. 35
0
        public void Execute()
        {
            HttpWebRequest request;

            #region UTF8Encode
            //Get XML into a string for use in encoding
            xmlText = RequestXml.InnerXml;



            //Put the data into a UTF8 encoded  byte array
            UTF8Encoding encoding  = new UTF8Encoding();
            int          dataLen   = encoding.GetByteCount(xmlText);
            byte[]       utf8Bytes = new byte[dataLen];
            Encoding.UTF8.GetBytes(xmlText, 0, xmlText.Length, utf8Bytes, 0);
            #endregion


            #region Setup The Request (inc. HTTP Headers
            //Create a new HttpWebRequest object for the ServerUrl
            request = (HttpWebRequest)WebRequest.Create(serverUrl);

            //Set Request Method (POST) and Content Type (text/xml)
            request.Method                 = "POST";
            request.ContentType            = "text/xml";
            request.ContentLength          = utf8Bytes.Length;
            request.AutomaticDecompression = DecompressionMethods.GZip;

            if (fakeTurboLister)
            {
                foreach (String header in CSharp.cc.Xml.XPath.SelectSingleNodes(@"
                    <requestheaders>
                        <header>X-EBAY-API-COMPATIBILITY-LEVEL: 601</header>
                        <header>X-EBAY-API-DEV-NAME: pebayktwo</header>
                        <header>X-EBAY-API-APP-NAME: deucedev</header>
                        <header>X-EBAY-API-CERT-NAME: pebayktwo9812p</header>
<!-- 
                        <header>X-EBAY-API-CALL-NAME: GetItems</header>
                        <header>X-EBAY-API-SITEID: 0</header>
-->
                        <header>X-EBAY-API-DETAIL-LEVEL: ReturnAll</header>
                        <header>X-EBAY-API-FLAGS: 711023.7.3512</header>
                      </requestheaders>", "//header"))
                {
                    request.Headers.Add(header);
                }

                request.UserAgent = "Turbo Lister";
            }
            else
            {
                //Add the Keys to the HTTP Headers
                request.Headers.Add("X-EBAY-API-DEV-NAME: " + devID);
                request.Headers.Add("X-EBAY-API-APP-NAME: " + appID);
                request.Headers.Add("X-EBAY-API-CERT-NAME: " + certID);

                //Add Compatability Level to HTTP Headers
                //Regulates versioning of the XML interface for the API
                request.Headers.Add("X-EBAY-API-COMPATIBILITY-LEVEL: 551");
            }

            //Add function name, SiteID and Detail Level to HTTP Headers
            request.Headers.Add("X-EBAY-API-CALL-NAME: " + _callName);
            request.Headers.Add("X-EBAY-API-SITEID: " + siteID.ToString());

            // WebHeaderCollection headers = request.Headers;
            if (requestHeaders.Count > 0)
            {
                foreach (String header in requestHeaders)
                {
                    request.Headers.Add(header);
                }
            }

            //Time out = 300 seconds,  set to -1 for no timeout.
            //If times-out - throws a WebException with the
            //Status property set to WebExceptionStatus.Timeout.
            request.Timeout = 300000;

            #endregion

            #region Send The Request

            Stream          responseStream = null;
            String          Html           = String.Empty;
            HttpWebResponse response       = null;

            byte[] lbPostBuffer = Encoding.Default.GetBytes(xmlText);
            request.ContentLength = lbPostBuffer.Length;

            try
            {
                Stream PostStream = request.GetRequestStream();
                PostStream.Write(lbPostBuffer, 0, lbPostBuffer.Length);
                PostStream.Close();


                response       = (HttpWebResponse)request.GetResponse();
                responseStream = response.GetResponseStream();

                StreamReader Reader = new StreamReader(responseStream, Encoding.Default);
                Html = Reader.ReadToEnd();
            }
            catch (WebException wEx)
            {
                //Error has occured whilst requesting
                //Display error message and exit.
                if (wEx.Status == WebExceptionStatus.Timeout)
                {
                    Console.WriteLine("Request Timed-Out.");
                }
                else
                {
                    Console.WriteLine(wEx.Message);
                }

                Html = "<" + _callName + "Request>"
                       + Xml.Formatters.ErrorAsXml("Web Request Timeout", wEx.Message, "Error")
                       + "</" + _callName + "Request>";
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    responseStream.Close();
                }
            }
            #endregion


            #region Process Response

            ResponseXml.LoadXml(Html);


            //get the root node, for ease of use
            // The root node will be called the name of this class
            // (idealistic thinking)

            // XmlNode root = xmlDoc["GeteBaySellingResponse"]; // "GeteBayOfficialTimeResponse"];

            // This look a bit silly, but it's automatic at least.
            // XmlNode test = ResponseXml[_callName + "Response"];
            // XmlNode root = ResponseXml[ResponseXml.DocumentElement.Name.ToString()];
            //There have been Errors

            //if (root["Errors"] != null)
            //{
            //    try
            //    {
            //        ErrorCode = root["Errors"]["ErrorCode"].InnerText;
            //        ErrorShort = root["Errors"]["ShortMessage"].InnerText;
            //        ErrorLong = root["Errors"]["LongMessage"].InnerText;
            //        ErrorSeverity = root["Errors"]["SeverityCode"].InnerText;
            //    }
            //    catch
            //    {
            //        Console.WriteLine(root["Errors"].OuterXml);
            //    }
            //}

            _Result = Html;
            #endregion
        }
Esempio n. 36
0
        private byte[] BuildPacket()
        {
            byte[] buffer;
            if (DataBuffer == null)
            {
                DataBuffer = new Byte[0];
            }

            if (Version == "1.0")
            {
                if ((Method == "") && (ResponseCode == -1))
                {
                    return(DataBuffer);
                }
            }


            UTF8Encoding          UTF8 = new UTF8Encoding();
            String                sbuf;
            IDictionaryEnumerator en = TheHeaders.GetEnumerator();

            en.Reset();

            if (Method != "")
            {
                if (Version != "")
                {
                    sbuf = Method + " " + EscapeString(MethodData) + " HTTP/" + Version + "\r\n";
                }
                else
                {
                    sbuf = Method + " " + EscapeString(MethodData) + "\r\n";
                }
            }
            else
            {
                sbuf = "HTTP/" + Version + " " + ResponseCode.ToString() + " " + ResponseData + "\r\n";
            }
            while (en.MoveNext())
            {
                if (en.Value != null && ((String)en.Key != "CONTENT-LENGTH" || OverrideContentLength == true))
                {
                    if (en.Value.GetType() == typeof(string))
                    {
                        sbuf += (String)en.Key + ": " + (String)en.Value + "\r\n";
                    }
                    else
                    {
                        sbuf += (String)en.Key + ":";
                        foreach (string v in (ArrayList)en.Value)
                        {
                            sbuf += (" " + v + "\r\n");
                        }
                    }
                }
            }
            if (StatusCode == -1 && DontShowContentLength == false)
            {
                sbuf += "Content-Length: " + DataBuffer.Length.ToString() + "\r\n";
            }
            else if (Version != "1.0" && Version != "0.9" && Version != "" && DontShowContentLength == false)
            {
                if (OverrideContentLength == false)
                {
                    sbuf += "Content-Length: " + DataBuffer.Length.ToString() + "\r\n";
                }
            }

            sbuf += "\r\n";

            buffer = new byte[UTF8.GetByteCount(sbuf) + DataBuffer.Length];
            UTF8.GetBytes(sbuf, 0, sbuf.Length, buffer, 0);
            Array.Copy(DataBuffer, 0, buffer, buffer.Length - DataBuffer.Length, DataBuffer.Length);
            return(buffer);
        }
Esempio n. 37
0
    //2011.05.10
    // ------------------------------------------------------
    private Byte[] SaveZap(String IDSession, Int32 IDM)
    {
        String sprav, rsp, ind1, ind2, ident, MARKER;
        Int32 KSZ, met, AllbyteCount, byteCount;
        Byte[] br = new Byte[1] { 0x00 };
        MARKER = "nam  22";
        //CREATE TABLE [dbo].[RUSM2](
        //    [ID] [int] IDENTITY(1,1) NOT NULL,
        //    [IDMAIN] [int] NULL,
        //    [IDBLOCK] [int] NULL,
        //    [MET] [smallint] NULL,
        //    [IND1] [char](1) NULL,
        //    [IND2] [char](1) NULL,
        //    [IDENT] [char](1) NULL,
        //    [POL] [nvarchar](3500) NULL
        da.SelectCommand = new SqlCommand();
        da.SelectCommand.CommandText = " SELECT ID,IDBLOCK,MET,IND1,IND2,IDENT,POL "
            + " FROM TECHNOLOG_VVV..RUSM2 "
            + " WHERE IDMAIN=" + IDM.ToString() + " and session='" + IDSession + "'"
            + " ORDER BY IDBLOCK,MET,IND1,IND2,IDENT";
        da.SelectCommand.Connection = conbase01;
        da.SelectCommand.CommandTimeout = 1200;
        DataSet dsZ = new DataSet();
        KSZ = da.Fill(dsZ, "listKSZ");
        if (KSZ > 0)
        {
            rsp = ""; // Сумма длин всех полей
            for (Int32 count = 0; count < KSZ; count++)
            {
                met = Int32.Parse(dsZ.Tables["listKSZ"].Rows[count]["MET"].ToString());
                if (met != 0) rsp = rsp + dsZ.Tables["listKSZ"].Rows[count]["POL"].ToString() + (char)30;
            }
            rsp = rsp.Replace("~", "'");
            UTF8Encoding utf8 = new UTF8Encoding();
            AllbyteCount = utf8.GetByteCount(rsp); // Сумма длин всех полей UTF-8
            sprav = "";
            posbrr = 0;
            mrc = new Byte[AllbyteCount];
            String tr = "";
            for (Int32 count = 0; count < KSZ; count++)
            {
                //              GetTranslitStr(p980,0);
                tr = dsZ.Tables["listKSZ"].Rows[count]["POL"].ToString() + (char)30;
                met = Int32.Parse(dsZ.Tables["listKSZ"].Rows[count]["MET"].ToString());
                if (met == 0) MARKER = tr;
                else
                {
                    Int32 IDB = Int32.Parse(dsZ.Tables["listKSZ"].Rows[count]["IDBLOCK"].ToString());
                    Int32 IDR2 = Int32.Parse(dsZ.Tables["listKSZ"].Rows[count][0].ToString());
                    ind1 = dsZ.Tables["listKSZ"].Rows[count]["IND1"].ToString();
                    ind2 = dsZ.Tables["listKSZ"].Rows[count]["IND2"].ToString();
                    ident = dsZ.Tables["listKSZ"].Rows[count]["IDENT"].ToString();
                    tr = tr.Replace("~", "'");
                    //UTF8Encoding utf8 = new UTF8Encoding();
                    byteCount = utf8.GetBytes(tr, 0, tr.Length, mrc, posbrr);

                    sprav += met.ToString().PadLeft(3, '0') + byteCount.ToString().PadLeft(4, '0');
                    sprav += posbrr.ToString().PadLeft(5, '0');
                    posbrr += byteCount;
                }
            }
            sprav += (char)30; // Конец поля
            Int32 ls = sprav.Length + 24; // Длина справочника и маркера = базовый адрес
            Int32 lz = ls + AllbyteCount + 1; // Длина записи

            rs = lz.ToString().PadLeft(5, '0') + MARKER.Substring(5, 7) + ls.ToString().PadLeft(5, '0');
            rs += "3  450 " + sprav;

            br = new Byte[lz]; // Результирующий массив
            // Encode the entire string.
            // public override int GetBytes(
            //    string s,
            //    int charIndex,
            //    int charCount,
            //    byte[] bytes,
            //    int byteIndex
            //)
            Int32 L = utf8.GetBytes(rs, 0, ls, br, 0); // Запись Маркера и Справочника
            utf8.GetBytes(rsp, 0, rsp.Length, br, ls); // Добавление полей
            br[lz - 1] = Convert.ToByte((char)29);
        }
        R = "DELETE TECHNOLOG_VVV..RUSM2 WHERE session='" + IDSession + "'";
        command = new SqlCommand(R, conbase01);
        conbase01.Open();
        command.CommandTimeout = 1200;
        command.ExecuteNonQuery();
        conbase01.Close();

        return br;
    }
Esempio n. 38
0
 public static int GetEncodedLength(string str)
 {
     return(_encoding.GetByteCount(str));
 }
Esempio n. 39
0
    public bool NegTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentNullException is not thrown when chars is a null reference  ");

        try
        {
            Byte[] bytes;
            Char[] chars = new Char[] {
                            '\u0023', 
                            '\u0025', 
                            '\u03a0', 
                            '\u03a3'  };

            UTF8Encoding utf8 = new UTF8Encoding();

            int byteCount = utf8.GetByteCount(chars, 1, 2);
            bytes = new Byte[byteCount];
            chars = null;
            int charsEncodedCount = utf8.GetChars(bytes, 1, 2, chars, 0);

            TestLibrary.TestFramework.LogError("102.1", "ArgumentNullException is not thrown when chars is a null reference  ");
            retVal = false;
        }
        catch (ArgumentNullException) { }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Esempio n. 40
0
        static void Main(string[] args)
        {
            var logClient = new AmazonCloudWatchLogsClient();
            // Add a new log group for testing
            const string newLogGroupName   = "NewLogGroup";
            DescribeLogGroupsResponse dlgr = logClient.DescribeLogGroups();
            var groups = new List <LogGroup> {
            };

            groups = dlgr.LogGroups;
            LogGroup lg = new LogGroup();

            lg.LogGroupName = newLogGroupName;
            // Look for our new log group name to determine if we need to do setup
            LogGroup result = groups.Find(
                delegate(LogGroup bk)
            {
                return(bk.LogGroupName == newLogGroupName);
            }
                );

            if (result != null)
            {
                Console.WriteLine(result.LogGroupName + " found");
            }
            else
            {
                //Haven't seen this log group, set it up
                CreateLogGroupRequest clgr = new CreateLogGroupRequest(newLogGroupName);
                logClient.CreateLogGroup(clgr);
                // Create a file to sace next SequenceToken in
                File.CreateText("..\\..\\" + lg.LogGroupName + ".txt");
                CreateLogStreamRequest csr = new CreateLogStreamRequest(lg.LogGroupName, newLogGroupName);
                logClient.CreateLogStream(csr);
            }

            string tokenFile = "";

            try
            {
                Console.WriteLine(lg.LogGroupName);
                //Pick up the next sequence token from the last run
                tokenFile = lg.LogGroupName;
                StreamReader sr            = File.OpenText("..\\..\\" + tokenFile + ".txt");
                string       sequenceToken = sr.ReadLine();
                sr.Close();
                lg.RetentionInDays = 30;
                string groupName                  = lg.LogGroupName;;
                TestMetricFilterRequest tmfr      = new TestMetricFilterRequest();
                List <InputLogEvent>    logEvents = new List <InputLogEvent>(3);
                InputLogEvent           ile       = new InputLogEvent();
                ile.Message = "Test Event 1";
                //DateTime dt = new DateTime(1394793518000);
                DateTime dt = new DateTime(2017, 01, 11);
                ile.Timestamp = dt;
                logEvents.Add(ile);
                ile.Message = "Test Event 2";
                logEvents.Add(ile);
                ile.Message = "This message also contains an Error";
                logEvents.Add(ile);
                DescribeLogStreamsRequest dlsr = new DescribeLogStreamsRequest(groupName);

                PutLogEventsRequest pler = new PutLogEventsRequest(groupName, tokenFile, logEvents);
                pler.SequenceToken = sequenceToken; //use last sequence token
                PutLogEventsResponse plerp = new PutLogEventsResponse();
                plerp = logClient.PutLogEvents(pler);
                Console.WriteLine("Next sequence token = " + plerp.NextSequenceToken);
                FileStream fs = File.OpenWrite("..\\..\\" + tokenFile + ".txt");
                fs.Position = 0;
                UTF8Encoding utf8         = new UTF8Encoding();
                Byte[]       encodedBytes = utf8.GetBytes(plerp.NextSequenceToken);
                fs.Write(encodedBytes, 0, utf8.GetByteCount(plerp.NextSequenceToken));
                fs.Close();
                List <string> lem = new List <string>(1);
                lem.Add("Error");
                tmfr.LogEventMessages = lem;
                tmfr.FilterPattern    = "Error";
                TestMetricFilterResponse tmfrp = new TestMetricFilterResponse();
                tmfrp = logClient.TestMetricFilter(tmfr);
                var results = new List <MetricFilterMatchRecord> {
                };
                results = tmfrp.Matches;
                Console.WriteLine("Found " + results.Count.ToString() + " match records");
                IEnumerator ie = results.GetEnumerator();
                while (ie.MoveNext())
                {
                    MetricFilterMatchRecord mfmr = (MetricFilterMatchRecord)ie.Current;
                    Console.WriteLine("Event Message = " + mfmr.EventMessage);
                }
                Console.WriteLine("Metric filter test done");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Esempio n. 41
0
    public bool NegTest6()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest6: ArgumentOutOfRangeException is not thrown when byteIndex and byteCount do not denote a valid range in chars.  ");

        try
        {
            Byte[] bytes;
            Char[] chars = new Char[] {
                            '\u0023', 
                            '\u0025', 
                            '\u03a0', 
                            '\u03a3'  };

            UTF8Encoding utf8 = new UTF8Encoding();

            int byteCount = utf8.GetByteCount(chars, 1, 2);
            bytes = new Byte[byteCount];
            int charsEncodedCount = utf8.GetChars(bytes, 2, 2, chars, 1);

            TestLibrary.TestFramework.LogError("106.1", "ArgumentOutOfRangeException is not thrown when byteIndex and byteCount do not denote a valid range in chars.");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException) { }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("106.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Esempio n. 42
0
        public ScriptForm(PBObjLib.Application app)
        {
            m_App = app;
            InitializeComponent();
            editor.ShowEOLMarkers   = false;
            editor.ShowSpaces       = false;
            editor.ShowTabs         = false;
            editor.ShowInvalidLines = false;
            editor.SetHighlighting("C#");
            workDir           = Path.GetTempPath() + "gPBToolKit\\";
            fullPathDummyFile = workDir + DummyFileName;

            if (!Directory.Exists(workDir))
            {
                Directory.CreateDirectory(workDir);
            }
            if (!Directory.Exists(workDir + "\\CSharpCodeCompletion\\"))
            {
                Directory.CreateDirectory(workDir + "\\CSharpCodeCompletion");
            }



            string indexFile = workDir + "CSharpCodeCompletion\\index.dat";

            if (!File.Exists(fullPathDummyFile))
            {
                string       sh           = @"using System;
using System.Collections.Generic;
using System.Text;
using PBObjLib;
using PBSymLib;
using VBIDE;
using System.Windows.Forms;

namespace gPBToolKit
{
    public class gkScript
    {   
        // ���������� �������� �������
        public static void StartScript(Display d)
        {
            foreach (Symbol s in d.Symbols)
            {
                if (s.Type == 7)
                {
                    Value v = (Value)s;
                    v.BackgroundColor = 32768;  
                    v.ShowUOM = true;
                }           
            }
            Action(d.Application);
        }
        
        public static void Action(PBObjLib.Application m_App)
        {
            try
            {
                VBProject project = null;
                CodeModule codeModule = null;
                for (int i = 1; i <= ((VBE)m_App.VBE).VBProjects.Count; i++)
                {
                    VBProject bufProject = ((VBE)m_App.VBE).VBProjects.Item(i);
                    if (bufProject.FileName.ToLower() == m_App.ActiveDisplay.Path.ToLower()) // ���� �� ��������� ����� ������
                    {
                        project = bufProject;
                        break;
                    }
                }

                if (project == null)
                {
                    MessageBox.Show(""VBProject not found"");
                    return;
                }

                codeModule = project.VBComponents.Item(""ThisDisplay"").CodeModule;
                try
                {
                    string procName = ""Display_Open"";
                    int procCountLine = -1, procStart = -1;
                    try{
						procStart = codeModule.get_ProcBodyLine(procName, vbext_ProcKind.vbext_pk_Proc);
                        procCountLine = codeModule.get_ProcCountLines(procName, vbext_ProcKind.vbext_pk_Proc);	
                    }
                    catch{}
                    
                    if (procStart > 0) 
                        codeModule.DeleteLines(procStart, procCountLine);
                    
                    string srvName = ""do51-dc1-du-pis.sgpz.gpp.gazprom.ru"";
                    string rootModule = ""����"";                   
                    string dispOpenText = string.Format(@""
Private Sub Display_Open()
    AVExtension1.Initialize """"{0}"""", """"{1}"""", ThisDisplay, Trend1
End Sub"", srvName, rootModule);
                    codeModule.AddFromString(dispOpenText);			
                }
                catch (Exception ex) {
                    MessageBox.Show(ex.Message + "" ""+ ex.StackTrace);
                }
            }
            catch { }
        }
    }
}
";
                UTF8Encoding asciEncoding = new UTF8Encoding();
                FileStream   fs           = File.Create(fullPathDummyFile);
                fs.Write(asciEncoding.GetBytes(sh), 0, asciEncoding.GetByteCount(sh));
                fs.Close();
            }
            if (!File.Exists(indexFile))
            {
                File.Create(indexFile).Close();
            }


            editor.LoadFile(fullPathDummyFile);

            refList.Items.Add("System.dll");
            refList.Items.Add("System.Drawing.dll");
            refList.Items.Add("System.Windows.Forms.dll");
            refList.Items.Add(@"C:\Program Files (x86)\PIPC\Procbook\OSIsoft.PBObjLib.dll");
            refList.Items.Add(@"C:\Program Files (x86)\PIPC\Procbook\OSIsoft.PBSymLib.dll");
            refList.Items.Add(@"C:\Program Files (x86)\PIPC\Procbook\Interop.VBIDE.dll");

            CodeCompletionKeyHandler.Attach(this, editor);
            HostCallbackImplementation.Register(this);

            pcRegistry = new Dom.ProjectContentRegistry(); // Default .NET 2.0 registry

            // Persistence caches referenced project contents for faster loading.
            // It also activates loading XML documentation files and caching them
            // for faster loading and lower memory usage.
            pcRegistry.ActivatePersistence(Path.Combine(workDir, "CSharpCodeCompletion"));

            myProjectContent          = new Dom.DefaultProjectContent();
            myProjectContent.Language = Dom.LanguageProperties.CSharp;
        }
Esempio n. 43
0
    public bool NegTest7()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest7: ArgumentException is not thrown when chars does not have enough capacity from charIndex to the end of the array to accommodate the resulting characters");

        try
        {
            Byte[] bytes;
            Char[] chars = new Char[] {
                            '\u0023', 
                            '\u0025', 
                            '\u03a0', 
                            '\u03a3'  };

            UTF8Encoding utf8 = new UTF8Encoding();

            int byteCount = utf8.GetByteCount(chars, 1, 2);
            bytes = new Byte[byteCount];
            int charsEncodedCount = utf8.GetChars(bytes, 1, 2, chars, chars.Length);

            TestLibrary.TestFramework.LogError("107.1", "ArgumentException is not thrown when byteIndex is not a valid index in bytes.");
            retVal = false;
        }
        catch (ArgumentException) { }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("107.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Esempio n. 44
0
        public bool TryReadChars(char[] chars, int offset, int count, out int actual)
        {
            DiagnosticUtility.DebugAssert(offset + count <= chars.Length, string.Format("offset '{0}' + count '{1}' MUST BE <= chars.Length '{2}'", offset, count, chars.Length));

            if (_type == ValueHandleType.Unicode)
            {
                return(TryReadUnicodeChars(chars, offset, count, out actual));
            }

            if (_type != ValueHandleType.UTF8)
            {
                actual = 0;
                return(false);
            }

            int charOffset = offset;
            int charCount  = count;

            byte[] bytes      = _bufferReader.Buffer;
            int    byteOffset = _offset;
            int    byteCount  = _length;
            bool   insufficientSpaceInCharsArray = false;

            var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

            while (true)
            {
                while (charCount > 0 && byteCount > 0)
                {
                    // fast path for codepoints U+0000 - U+007F
                    byte b = bytes[byteOffset];
                    if (b >= 0x80)
                    {
                        break;
                    }
                    chars[charOffset] = (char)b;
                    byteOffset++;
                    byteCount--;
                    charOffset++;
                    charCount--;
                }

                if (charCount == 0 || byteCount == 0 || insufficientSpaceInCharsArray)
                {
                    break;
                }

                int actualByteCount;
                int actualCharCount;

                try
                {
                    // If we're asking for more than are possibly available, or more than are truly available then we can return the entire thing
                    if (charCount >= encoding.GetMaxCharCount(byteCount) || charCount >= encoding.GetCharCount(bytes, byteOffset, byteCount))
                    {
                        actualCharCount = encoding.GetChars(bytes, byteOffset, byteCount, chars, charOffset);
                        actualByteCount = byteCount;
                    }
                    else
                    {
                        Decoder decoder = encoding.GetDecoder();

                        // Since x bytes can never generate more than x characters this is a safe estimate as to what will fit
                        actualByteCount = Math.Min(charCount, byteCount);

                        // We use a decoder so we don't error if we fall across a character boundary
                        actualCharCount = decoder.GetChars(bytes, byteOffset, actualByteCount, chars, charOffset);

                        // We might have gotten zero characters though if < 4 bytes were requested because
                        // codepoints from U+0000 - U+FFFF can be up to 3 bytes in UTF-8, and represented as ONE char
                        // codepoints from U+10000 - U+10FFFF (last Unicode codepoint representable in UTF-8) are represented by up to 4 bytes in UTF-8
                        //                                    and represented as TWO chars (high+low surrogate)
                        // (e.g. 1 char requested, 1 char in the buffer represented in 3 bytes)
                        while (actualCharCount == 0)
                        {
                            // Note the by the time we arrive here, if actualByteCount == 3, the next decoder.GetChars() call will read the 4th byte
                            // if we don't bail out since the while loop will advance actualByteCount only after reading the byte.
                            if (actualByteCount >= 3 && charCount < 2)
                            {
                                // If we reach here, it means that we're:
                                // - trying to decode more than 3 bytes and,
                                // - there is only one char left of charCount where we're stuffing decoded characters.
                                // In this case, we need to back off since decoding > 3 bytes in UTF-8 means that we will get 2 16-bit chars
                                // (a high surrogate and a low surrogate) - the Decoder will attempt to provide both at once
                                // and an ArgumentException will be thrown complaining that there's not enough space in the output char array.

                                // actualByteCount = 0 when the while loop is broken out of; decoder goes out of scope so its state no longer matters

                                insufficientSpaceInCharsArray = true;
                                break;
                            }
                            else
                            {
                                DiagnosticUtility.DebugAssert(byteOffset + actualByteCount < bytes.Length,
                                                              string.Format("byteOffset {0} + actualByteCount {1} MUST BE < bytes.Length {2}", byteOffset, actualByteCount, bytes.Length));

                                // Request a few more bytes to get at least one character
                                actualCharCount = decoder.GetChars(bytes, byteOffset + actualByteCount, 1, chars, charOffset);
                                actualByteCount++;
                            }
                        }

                        // Now that we actually retrieved some characters, figure out how many bytes it actually was
                        actualByteCount = encoding.GetByteCount(chars, charOffset, actualCharCount);
                    }
                }
                catch (FormatException exception)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(bytes, byteOffset, byteCount, exception));
                }

                // Advance
                byteOffset += actualByteCount;
                byteCount  -= actualByteCount;

                charOffset += actualCharCount;
                charCount  -= actualCharCount;
            }

            _offset = byteOffset;
            _length = byteCount;

            actual = (count - charCount);
            return(true);
        }
Esempio n. 45
0
        public bool TryReadChars(char[] chars, int offset, int count, out int actual)
        {
            if (_type == ValueHandleType.Unicode)
            {
                return(TryReadUnicodeChars(chars, offset, count, out actual));
            }

            if (_type != ValueHandleType.UTF8)
            {
                actual = 0;
                return(false);
            }

            int charOffset = offset;
            int charCount  = count;

            byte[] bytes      = _bufferReader.Buffer;
            int    byteOffset = _offset;
            int    byteCount  = _length;

            while (true)
            {
                while (charCount > 0 && byteCount > 0)
                {
                    byte b = bytes[byteOffset];
                    if (b >= 0x80)
                    {
                        break;
                    }
                    chars[charOffset] = (char)b;
                    byteOffset++;
                    byteCount--;
                    charOffset++;
                    charCount--;
                }

                if (charCount == 0 || byteCount == 0)
                {
                    break;
                }

                int actualByteCount;
                int actualCharCount;

                UTF8Encoding encoding = new UTF8Encoding(false, true);
                try
                {
                    // If we're asking for more than are possibly available, or more than are truly available then we can return the entire thing
                    if (charCount >= encoding.GetMaxCharCount(byteCount) || charCount >= encoding.GetCharCount(bytes, byteOffset, byteCount))
                    {
                        actualCharCount = encoding.GetChars(bytes, byteOffset, byteCount, chars, charOffset);
                        actualByteCount = byteCount;
                    }
                    else
                    {
                        Decoder decoder = encoding.GetDecoder();

                        // Since x bytes can never generate more than x characters this is a safe estimate as to what will fit
                        actualByteCount = Math.Min(charCount, byteCount);

                        // We use a decoder so we don't error if we fall across a character boundary
                        actualCharCount = decoder.GetChars(bytes, byteOffset, actualByteCount, chars, charOffset);

                        // We might've gotten zero characters though if < 3 chars were requested
                        // (e.g. 1 char requested, 1 char in the buffer represented in 3 bytes)
                        while (actualCharCount == 0)
                        {
                            // Request a few more bytes to get at least one character
                            actualCharCount = decoder.GetChars(bytes, byteOffset + actualByteCount, 1, chars, charOffset);
                            actualByteCount++;
                        }

                        // Now that we actually retrieved some characters, figure out how many bytes it actually was
                        actualByteCount = encoding.GetByteCount(chars, charOffset, actualCharCount);
                    }
                }
                catch (FormatException exception)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(bytes, byteOffset, byteCount, exception));
                }

                // Advance
                byteOffset += actualByteCount;
                byteCount  -= actualByteCount;

                charOffset += actualCharCount;
                charCount  -= actualCharCount;
            }

            _offset = byteOffset;
            _length = byteCount;

            actual = (count - charCount);
            return(true);
        }
Esempio n. 46
0
 private static void ThrowDocumentIdTooBig(string str)
 {
     throw new ArgumentException(
               $"Document ID cannot exceed 512 bytes, but the ID was {Encoding.GetByteCount(str)} bytes. The invalid ID is '{str}'.",
               nameof(str));
 }
Esempio n. 47
0
        public static void RestYap(string data, string digesturl, string requesturl, string listrequesturl, bool ifmatch, bool merge, bool delete, bool put)
        {
            XmlNamespaceManager xmlnspm = new XmlNamespaceManager(new NameTable());

            xmlnspm.AddNamespace("atom", "http://www.w3.org/2005/Atom");
            xmlnspm.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
            xmlnspm.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");

            HttpWebRequest contextinfoRequest = (HttpWebRequest)HttpWebRequest.Create(digesturl);

            contextinfoRequest.Method        = "POST";
            contextinfoRequest.Proxy         = new WebProxy();
            contextinfoRequest.ContentType   = "text/xml;charset=utf-8";
            contextinfoRequest.ContentLength = 0;
            contextinfoRequest.Credentials   = CredentialCache.DefaultCredentials;

            HttpWebResponse contextinfoResponse = (HttpWebResponse)contextinfoRequest.GetResponse();
            StreamReader    contextinfoReader   = new StreamReader(contextinfoResponse.GetResponseStream(), System.Text.Encoding.UTF8);
            var             formDigestXML       = new XmlDocument();

            formDigestXML.LoadXml(contextinfoReader.ReadToEnd());
            var    formDigestNode = formDigestXML.SelectSingleNode("//d:FormDigestValue", xmlnspm);
            string formDigest     = formDigestNode.InnerXml;

            HttpWebRequest listRequest = (HttpWebRequest)HttpWebRequest.Create(listrequesturl);

            listRequest.Method      = "GET";
            listRequest.Proxy       = new WebProxy();
            listRequest.Accept      = "application/atom+xml";
            listRequest.ContentType = "application/atom+xml;type=entry";
            listRequest.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse listResponse = (HttpWebResponse)listRequest.GetResponse();
            StreamReader    listReader   = new StreamReader(listResponse.GetResponseStream());
            var             listXml      = new XmlDocument();

            listXml.LoadXml(listReader.ReadToEnd());

            var entityTypeNode = listXml.SelectSingleNode("//atom:entry/atom:content/m:properties/d:ListItemEntityTypeFullName", xmlnspm);
            var listNameNode   = listXml.SelectSingleNode("//atom:entry/atom:content/m:properties/d:Title", xmlnspm);

            string entityTypeName = entityTypeNode.InnerXml;
            string listName       = listNameNode.InnerXml;

            string   itemPostBody = data;
            Encoding utf8NoBom    = new UTF8Encoding(false);

            Byte[]         itemPostData = utf8NoBom.GetBytes(itemPostBody);
            var            datak        = utf8NoBom.GetString(itemPostData);
            HttpWebRequest itemRequest  = (HttpWebRequest)HttpWebRequest.Create(requesturl);

            itemRequest.Method = "POST";
            //itemRequest.Proxy = new WebProxy("127.0.0.1", 8888); İsteğinizin Fiddler’a düşmesini sağlamak için local makinenizin 8888 portunu kullanmalısınız.
            //itemRequest.ContentLength = itemPostBody.Length;
            itemRequest.ContentLength = utf8NoBom.GetByteCount(datak);
            itemRequest.ContentType   = "application/json;odata=verbose";
            itemRequest.MaximumResponseHeadersLength = -1;
            itemRequest.Proxy       = new WebProxy();
            itemRequest.Accept      = "application/json;odata=verbose";
            itemRequest.Credentials = CredentialCache.DefaultCredentials;
            itemRequest.Headers.Add("X-RequestDigest", formDigest);

            if (merge)
            {
                itemRequest.Headers.Add("X-HTTP-Method", "PATCH");
            }
            if (ifmatch)
            {
                itemRequest.Headers.Add("IF-MATCH", "*");
            }
            if (delete)
            {
                itemRequest.Headers.Add("X-HTTP-Method", "DELETE");
            }

            if (put)
            {
                itemRequest.Headers.Add("X-HTTP-Method", "PUT");
            }
            /// karşılaştırma file upload da if match ve delete true ise  yeni oluşturulacak  aksi taktirde üzerine yazıcak
            if (ifmatch && delete)
            {
                itemRequest.ContentLength = 0;
            }
            else
            {
                Stream itemRequestStream = itemRequest.GetRequestStream();
                itemRequestStream.Write(itemPostData, 0, itemPostData.Length);
                itemRequestStream.Close();
            }
        }
    public bool NegTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException is not thrown when count is less than zero.");

        try
        {
            Char[] chars = new Char[] {
                            '\u0023', 
                            '\u0025', 
                            '\u03a0', 
                            '\u03a3'  };

            UTF8Encoding utf8 = new UTF8Encoding();
            int byteCount = utf8.GetByteCount(chars, 1, -2);

            TestLibrary.TestFramework.LogError("103.1", "ArgumentOutOfRangeException is not thrown when count is less than zero.");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException) { }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Esempio n. 49
0
 /// <summary>
 /// Encrypt the password
 /// </summary>
 /// <param name="password">password</param>
 /// <returns>encrypted password</returns>
 private string HashPassword(string password)
 {
     byte[] bytes = new Byte[utf8Encoding.GetByteCount(password)];
     bytes = utf8Encoding.GetBytes(password);
     return(Convert.ToBase64String(md5Service.ComputeHash(bytes)));
 }
Esempio n. 50
0
        public override void WriteString(string value, UTF8Encoding encoding)
        {
            var length = encoding.GetByteCount(value);

            Position += 4 + length + 1;
        }
Esempio n. 51
0
        /// <summary>
        /// Construct an HttpWebRequest object using the specified CIXAPI function, format
        /// and method. Any authentication rider is attached to the header as required and
        /// the appropriate content type set.
        /// </summary>
        /// <param name="apiFunction">The API function name</param>
        /// <param name="username">Authentication username</param>
        /// <param name="password">Authentication password</param>
        /// <param name="format">The API format requested (JSON or XML)</param>
        /// <param name="method">The API method required (GET or POST)</param>
        /// <param name="postObject">For POST, this is the object to be posted</param>
        /// <param name="queryString">Optional query string for the URL</param>
        /// <returns>A constructed HttpWebRequest</returns>
        private static HttpWebRequest Create(string apiFunction, string username, string password, APIFormat format, APIMethod method, object postObject, string queryString)
        {
            HttpWebRequest wrGeturl;

            byte[] postMessageBytes;

            if (username == null || password == null)
            {
                return(null);
            }

            if (method == APIMethod.POST)
            {
                var o = postObject as Image;
                if (o != null)
                {
                    Image postImage = o;

                    ImageConverter converter = new ImageConverter();
                    postMessageBytes = (byte[])converter.ConvertTo(postImage, typeof(byte[]));

                    if (postMessageBytes == null)
                    {
                        return(null);
                    }

                    wrGeturl        = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString));
                    wrGeturl.Method = APIMethodToString(method);

                    if (ImageFormat.Jpeg.Equals(postImage.RawFormat))
                    {
                        wrGeturl.ContentType = "image/jpeg";
                    }
                    if (ImageFormat.Gif.Equals(postImage.RawFormat))
                    {
                        wrGeturl.ContentType = "image/gif";
                    }
                    if (ImageFormat.Png.Equals(postImage.RawFormat))
                    {
                        wrGeturl.ContentType = "image/png";
                    }
                    if (ImageFormat.Bmp.Equals(postImage.RawFormat))
                    {
                        wrGeturl.ContentType = "image/bitmap";
                    }
                    wrGeturl.ContentLength = postMessageBytes.Length;
                }
                else
                {
                    var s = postObject as string;
                    if (s != null)
                    {
                        string postString = s;

                        ASCIIEncoding encoder = new ASCIIEncoding();
                        postMessageBytes = encoder.GetBytes(postString);

                        wrGeturl        = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString));
                        wrGeturl.Method = APIMethodToString(method);

                        wrGeturl.ContentLength = postMessageBytes.Length;
                        wrGeturl.ContentType   = "application/text";
                    }
                    else
                    {
                        StringBuilder postMessageXml = new StringBuilder();

                        using (XmlWriter writer = XmlWriter.Create(postMessageXml))
                        {
                            XmlSerializer serializer = new XmlSerializer(postObject.GetType());
                            serializer.Serialize(writer, postObject);
                        }

                        // Remove the header
                        postMessageXml.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "");

                        // Messages are posted as 7-bit ASCII.
                        UTF8Encoding encoder = new UTF8Encoding();
                        postMessageBytes = encoder.GetBytes(postMessageXml.ToString());

                        wrGeturl        = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString));
                        wrGeturl.Method = APIMethodToString(method);

                        wrGeturl.ContentLength = encoder.GetByteCount(postMessageXml.ToString());
                        wrGeturl.ContentType   = "application/xml; charset=utf-8";
                        wrGeturl.Accept        = "application/xml; charset=utf-8";
                    }
                }
            }
            else
            {
                wrGeturl        = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString));
                wrGeturl.Method = APIMethodToString(method);

                postMessageBytes = null;

                if (format == APIFormat.XML)
                {
                    wrGeturl.ContentType = "application/xml; charset=utf-8";
                    wrGeturl.Accept      = "application/xml; charset=utf-8";
                }
                else
                {
                    wrGeturl.ContentType = "application/json";
                    wrGeturl.Accept      = "application/json";
                }
            }

            string authInfo = username + ":" + password;

            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            wrGeturl.Headers.Add("Authorization", "Basic " + authInfo);
            wrGeturl.PreAuthenticate = true;

            if (postMessageBytes != null)
            {
                Stream dataStream = wrGeturl.GetRequestStream();
                dataStream.Write(postMessageBytes, 0, postMessageBytes.Length);
                dataStream.Close();
            }

            return(wrGeturl);
        }
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown when chars is a null reference");

        try
        {
            Char[] chars = null;

            UTF8Encoding utf8 = new UTF8Encoding();
            int byteCount = utf8.GetByteCount(chars, 0, 0);

            TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown when chars is a null reference.");
            retVal = false;
        }
        catch (ArgumentNullException) { }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Esempio n. 53
0
        public void Call(string url, HttpListenerContext ctx)
        {
            if (url == "favicon.ico")
            {
                return;
            }

            url = url.ToLower();

            Dictionary <string, string> get  = new Dictionary <string, string>();
            Dictionary <string, string> post = new Dictionary <string, string>();
            Encoding utf       = new UTF8Encoding(false);
            Head     head      = new Head(ctx.Request.Headers);
            bool     allow     = false;
            string   totalPost = "";

            string response = null;
            string guid     = null;

            Console.WriteLine(url);

            url = url.ToLower();

            List <string> urlsp = url.Split('/').ToList <string>();

            if (ctx.Request.HttpMethod == Constants.METHOD_GET)
            {
                url = string.Join("/", urlsp);
                //url = urlsp.First();
                //for (int i = 1; i < urlsp.Count; i++)
                //    get.Add(i.ToString(), urlsp[i]);
            }
            else
            {
                url = string.Join("/", urlsp);
            }

            if (url.Contains(".css"))
            {
                response = FileManager.LoadCSSFile(url);
                ctx.Response.ContentEncoding = utf;
                ctx.Response.ContentType     = Constants.CONTENT_CSS;
                ctx.Response.ContentLength64 = utf.GetByteCount(response);
                ctx.Response.StatusCode      = Constants.StatusCodes.OK;

                if (!RestServer.Developer)
                {
                    ctx.Response.AddHeader("Cache-Control", "max-age=86400");
                }

                ctx.Response.OutputStream.Write(utf.GetBytes(response), 0, utf.GetByteCount(response));
                ctx.Response.Close();

                return;
            }
            else if (url.Contains(".js"))
            {
                response = FileManager.LoadCSSFile(url);
                ctx.Response.ContentEncoding = utf;
                ctx.Response.ContentType     = Constants.CONTENT_JAVASCRIPT;
                ctx.Response.ContentLength64 = utf.GetByteCount(response);
                ctx.Response.StatusCode      = Constants.StatusCodes.OK;

                if (!RestServer.Developer)
                {
                    ctx.Response.AddHeader("Cache-Control", "private, max-age=86400");
                }

                ctx.Response.OutputStream.Write(utf.GetBytes(response), 0, utf.GetByteCount(response));
                ctx.Response.Close();

                return;
            }
            else if (url.Contains(".png") || url.Contains(".jpg") || url.Contains(".ico"))
            {
                ImageFile image = FileManager.LoadImagefile(url);

                ctx.Response.ContentType     = image.GetContentType();
                ctx.Response.ContentLength64 = image.GetStream().Length;

                if (!RestServer.Developer)
                {
                    ctx.Response.AddHeader("Cache-Control", "max-age=86400");
                }

                image.GetStream().WriteTo(ctx.Response.OutputStream);

                ctx.Response.OutputStream.Flush();
                ctx.Response.OutputStream.Close();
                ctx.Response.Close();

                return;
            }
            else if (url.Contains(".pdf"))
            {
                FileStream fs = File.OpenRead(FileManager.BaseDir + url);

                ctx.Response.ContentType     = Constants.CONTENT_PDF;
                ctx.Response.ContentLength64 = fs.Length;
                ctx.Response.StatusCode      = Constants.StatusCodes.OK;

                fs.CopyTo(ctx.Response.OutputStream);

                if (!RestServer.Developer)
                {
                    ctx.Response.AddHeader("Cache-Control", "max-age=86400");
                }

                ctx.Response.OutputStream.Flush();
                ctx.Response.OutputStream.Close();
                ctx.Response.Close();

                return;
            }

            NoAuth.ForEach(x => { if (!url.Contains(x))
                                  {
                                      guid = head.Session;
                                  }
                                  else
                                  {
                                      allow = true;
                                  } });

            if (ctx.Request.Cookies["guid"] != null)
            {
                guid = ctx.Request.Cookies["guid"].Value;
            }

            if (guid == "user" || guid == "admin")
            {
                allow = true;
            }

            if (allow || Sessions.sessions.Any(i => i.Value.Item2 == guid && i.Value.Item1 == ctx.Request.RemoteEndPoint.Address.ToString()))
            {
                try
                {
                    if (!allow)
                    {
                        Tuple <string, string, DateTime> sess    = Sessions.sessions[(from s in Sessions.sessions where s.Value.Item2 == guid select s.Key).First <int>()];
                        Tuple <string, string, DateTime> newSess = Tuple.Create <string, string, DateTime>(sess.Item1, sess.Item2, DateTime.Now);
                        Sessions.sessions[(from s in Sessions.sessions where s.Value.Item2 == guid select s.Key).First <int>()] = newSess;
                    }

                    //Routing.ToList<KeyValuePair<string, List<Page>>>().ForEach(x => Console.WriteLine(x.Key));
                    Console.WriteLine("test");
                    foreach (Page page in Routing[url])
                    {
                        MemoryStream memoryStream = new MemoryStream();
                        using (Stream input = ctx.Request.InputStream)
                        {
                            byte[] buffer = new byte[32 * 1024]; // 32K buffer for example
                            int    bytesRead;
                            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                memoryStream.Write(buffer, 0, bytesRead);
                            }
                        }
                        memoryStream.Position = 0;

                        using (StreamReader reader = new StreamReader(memoryStream, ctx.Request.ContentEncoding))
                        {
                            string postR = reader.ReadToEnd();

                            totalPost += postR;

                            memoryStream.Position = 0;

                            if (postR.Contains("Content-Disposition"))
                            {
                                SaveFile(memoryStream, ctx.Request.ContentType);
                            }
                            else
                            {
                                if (postR.Length > 0)
                                {
                                    postR.Split('&').ToList <string>().ForEach(x => { var spl = x.Split('='); post.Add(spl[0], Uri.UnescapeDataString(spl[1])); });
                                }
                            }
                        }

                        using (SHA1Managed sha1 = new SHA1Managed())
                        {
                            byte[]        hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(url + totalPost));
                            StringBuilder sb   = new StringBuilder(hash.Length * 2);

                            foreach (byte b in hash)
                            {
                                sb.Append(b.ToString("X2"));
                            }

                            if (Caching.ContainsKey(sb.ToString()))
                            {
                                Cache cache = Caching[sb.ToString()];

                                ctx.Response.ContentEncoding = cache.ContentEncoding;
                                ctx.Response.ContentType     = cache.ContentType;
                                ctx.Response.ContentLength64 = cache.ContentLength64;

                                ctx.Response.OutputStream.Write(utf.GetBytes(cache.Response), 0, utf.GetByteCount(cache.Response));
                                ctx.Response.OutputStream.Flush();
                                ctx.Response.OutputStream.Close();
                                ctx.Response.Close();
                                return;
                            }
                        }

                        page._POST = post;
                        page._GET  = get;
                        page.Url   = url;

                        page.HTTPMethod = ctx.Request.HttpMethod;
                        page.Headers    = head;
                        page.Init(ctx);
                        response += page.Send();
                        page.CleanUp();

                        if (page.Location != null)
                        {
                            ctx.Response.Redirect(page.Location);
                        }
                        break;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
#if DEBUG
                    Console.WriteLine("Route doesn't exist!");
                    response = Constants.STATUS_FALSE;
                    ctx.Response.ContentEncoding = utf;
                    ctx.Response.ContentType     = Constants.CONTENT_JSON;
                    ctx.Response.ContentLength64 = utf.GetByteCount(response);
                    //ctx.Response.StatusCode = Routing[url][0].StatusCode;

                    ctx.Response.OutputStream.Write(utf.GetBytes(response), 0, utf.GetByteCount(response));
                    ctx.Response.Close();
                    return;
#endif
                    if (Routing.ContainsKey("404"))
                    {
                        Routing["404"][0].Init();
                        response = Routing["404"][0].Send();
                    }
                }
                ctx.Response.ContentEncoding = utf;
                ctx.Response.ContentType     = Routing[url][0].ContentType;
                ctx.Response.ContentLength64 = utf.GetByteCount(response);
                //ctx.Response.StatusCode = Routing[url][0].StatusCode;

                //if (!RestServer.Developer)
                //{
                //    ctx.Response.AddHeader("Cache-Control", "max-age=86400");
                //}

                ctx.Response.OutputStream.Write(utf.GetBytes(response), 0, utf.GetByteCount(response));
                ctx.Response.OutputStream.Flush();
                ctx.Response.OutputStream.Close();
                ctx.Response.Close();

                using (SHA1Managed sha1 = new SHA1Managed())
                {
                    byte[]        hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(url + totalPost));
                    StringBuilder sb   = new StringBuilder(hash.Length * 2);

                    foreach (byte b in hash)
                    {
                        sb.Append(b.ToString("X2"));
                    }

                    Cache cache = new Cache();
                    cache.ContentEncoding = utf;
                    cache.ContentType     = Routing[url][0].ContentType;
                    cache.ContentLength64 = utf.GetByteCount(response);
                    cache.Response        = response;

                    Caching.Add(sb.ToString(), cache);
                }
            }
            else
            {
                response = Constants.STATUS_UNAUTHORIZED;
                ctx.Response.ContentEncoding = utf;
                Console.WriteLine(url);
                ctx.Response.ContentType     = Constants.CONTENT_JSON;
                ctx.Response.ContentLength64 = utf.GetByteCount(response);
                ctx.Response.StatusCode      = Constants.StatusCodes.UNAUTHORIZED;

                ctx.Response.OutputStream.Write(utf.GetBytes(response), 0, utf.GetByteCount(response));
                ctx.Response.Close();
            }
        }