Send Message To Unity Connection using CUMI API

Version 1
    This document was generated from CDN thread

    Created by: Sergey Knyazev on 23-11-2011 09:14:27 AM
    Hi ,
    I'm trying to use CUMI API for sending Message to Unity Connection.
    I'm following DocWiki example,but all the time get Response  from Unity:The remote server returned an error 400 Bad Request
    Here is the Code:
    private void button1_Click(object sender, EventArgs e)
            {
                string str;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://10.0.0.201:8443/vmrest/messages");
                System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
                byte[] bytes = Encoding.UTF8.GetBytes("******:*******");
                string base64 = Convert.ToBase64String(bytes);
                req.Method = "Post";
                req.Accept = "application/xml";
                req.ProtocolVersion = System.Net.HttpVersion.Version11;
                req.ContentType = "multipart/mixed";
                req.Headers.Add("Authorization", "Basic " + base64);
                byte[] sentData = Check();
                req.ContentLength = sentData.Length;
                Stream sendStream = req.GetRequestStream();
                sendStream.Write(sentData, 0, sentData.Length);
                sendStream.WriteTimeout = 10;
                sendStream.Close();
                try
                {
                    WebResponse res = req.GetResponse();
                    StreamReader readl = new StreamReader(res.GetResponseStream());
                    str = readl.ReadLine();
                    MessageBox.Show(str);
                    readl.Close();//
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

    public byte[] Check()
            {
               
                string data;
                TextReader tr = new StreamReader(File.OpenRead("c:\\1.txt"));
                Chilkat.Mime mime = new Chilkat.Mime();
                bool success;
                success = mime.UnlockComponent("Anything for 30-day trial");
                if (success == false)
                {
                    MessageBox.Show("Failed to unlock component");
                    return mime.GetMimeBytes();
                }
                //  Initialize this MIME object as a multipart/mixed:
                success = mime.NewMultipartMixed();
                mime.ContentType = "multipart/mixed";
                //  Now insert some files:
                data = tr.ReadLine();
                Chilkat.Mime textBody = new Chilkat.Mime();
                textBody.SetBodyFromPlainText(data);
                textBody.ContentType = "application/json";
                success = mime.AppendPart(textBody);
                if (success == false)
                {
                    MessageBox.Show(mime.LastErrorText);
                    return  mime.GetMimeBytes();
                }
                data = tr.ReadLine();
                Chilkat.Mime textBody1 = new Chilkat.Mime();
                textBody1.SetBodyFromPlainText(data);
                textBody1.ContentType = "application/json";
                success = mime.AppendPart(textBody1);
                if (success == false)
                {
                    MessageBox.Show(mime.LastErrorText);
                    return mime.GetMimeBytes();
                }
                
                /*
                Chilkat.Mime textBody2 = new Chilkat.Mime();
                textBody2.SetBodyFromFile("C://2020.wav");
                textBody2.ContentType = "audio/wav";
                success = mime.AppendPart(textBody2);
                if (success == false)
                {
                    MessageBox.Show(mime.LastErrorText);
                    return mime.GetMimeBytes();
                }
                */      
          
                return mime.GetMimeBytes();
            }

    DATA Of Message Sent To Server in JSON
    {"Subject":"subscriber send message test","ArrivalTime":"0","FromSub":"false"}
    {"Recipient":{"Type":"TO","Address":{"ObjectId":"fae5a39d-2ef3-490b-8750-e4a54193cd73","Type":"SUBSCRIBER"}}}
     
    The response from EchoServer is:
    POST / HTTP/1.1
    Accept: application/xml
    Content-Type: multipart/mixed
    Authorization: Basic ********
    Host: 127.0.0.1:8081
    Content-Length: 580
    Expect: 100-continue
    Connection: Keep-Alive

    Content-Type: multipart/mixed;
            boundary="------------070200000807000300060601"

    This is a multi-part message in MIME format.

    --------------070200000807000300060601
    Content-Transfer-Encoding: 7bit
    Content-Type: application/json

    {"Subject":"subscriber send message test","ArrivalTime":"0","FromSub":"false"}
    --------------070200000807000300060601
    Content-Transfer-Encoding: 7bit
    Content-Type: application/json 

     {"Recipient":{"Type":"TO","Address":{"ObjectId":"fae5a39d-2ef3-490b-8750-e4a541
    93cd73","Type":"SUBSCRIBER"}}}
    --------------070200000807000300060601--

    Any Help or Example?
    Thanks

    Subject: RE: Send Message To Unity Connection using CUMI API
    Replied by: David Wanagel on 28-11-2011 04:58:35 PM
    A 400 error usually has content along with the HTTP header that gives more detail on the error.  If that doesn't provide enough information, I would suggest setting the VMREST micro traces to debug, reproduce the error and take a look at the connection tomcat diagnostic logs.
     
    -Dave

    Subject: RE: Send Message To Unity Connection using CUMI API
    Replied by: Brian Ward on 28-11-2011 12:50:04 PM
    Quick example to post a message...remember that the WAV file also needs to be PCM 16/8/1.  That'll be your next barrier based on my experience.  On first glance of your code, it looks like your not setting the content types correctly...are you setting your boundary correctly with a prefix of "--"?  Boundary looks the same to me across both boundaries.

            public string PostBroadcastMessage(string fileAndPath, string fileName, string startdate, string enddate)
            {
                //Allow untrusted SSL sites
                ServicePointManager.ServerCertificateValidationCallback += delegate(
                    object sender,
                    X509Certificate certificate,
                    X509Chain chain,
                    SslPolicyErrors sslPolicyErrors)
                {
                    return true;
                };

                //Disable Expect 100-Continue in header
                ServicePointManager.Expect100Continue = false;

                string uri = "https://" + Server + "/vmrest/mailbox/broadcastmessages";

                CookieContainer cookies = new CookieContainer();

                string boundary = DateTime.Now.Ticks.ToString("x");
                HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
                webrequest.CookieContainer = cookies;
                webrequest.UserAgent = "UCBroadcastMessageTool";
                webrequest.KeepAlive = true;
                webrequest.Accept = "application/xml";
                webrequest.Timeout = 15 * 1000;
                webrequest.ContentType = "multipart/form-data;boundary=" + boundary;
                webrequest.Method = "POST";
                webrequest.Credentials = new NetworkCredential(UserName, Password);

                string partXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
                        + "<BroadcastMessage>"
                            + "<StartDate>" + startdate + "</StartDate>" //2011-07-09 14:23:10.000
                            + "<EndDate>" + enddate + "</EndDate>" //2011-08-07 14:22:42.000
                            + "<StreamFile>" + fileName + "</StreamFile>"  //44.wav
                        + "</BroadcastMessage>";

                // Build up the post message header
                StringBuilder sb = new StringBuilder();
                sb.Append("\r\n");
                sb.Append("--" + boundary);
                sb.Append("\r\n");

                sb.Append("Content-Type: ");
                sb.Append("application/xml");
                sb.Append("\r\n");
                sb.Append("\r\n");
                sb.Append(partXML);
                sb.Append("\r\n");
                sb.Append("\r\n");
                sb.Append("--" + boundary);

                sb.Append("\r\n");
                sb.Append("Content-Type: ");
                sb.Append("audio/wav");

                sb.Append("\r\n");
                sb.Append("\r\n");

                string postHeader = sb.ToString();
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

                // Build the trailing boundary string as a byte array
                // ensuring the boundary appears on a line by itself
                byte[] boundaryBytes =
                       Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

                FileStream fileStream = new FileStream(fileAndPath,
                                            FileMode.Open, FileAccess.Read);

                Stream memStream = new System.IO.MemoryStream();

                memStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);
                }

                memStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                fileStream.Close();

                webrequest.ContentLength = memStream.Length;
                Stream requestStream = webrequest.GetRequestStream();

                memStream.Position = 0;
                byte[] tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();

                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();

                HttpWebResponse response = null;
                string responseAndLogEntry = string.Empty;

                using (response = webrequest.GetResponse() as HttpWebResponse)
                {
                    if (webrequest.HaveResponse == true && response != null)
                    {
                        var reader = new StreamReader(response.GetResponseStream());

                        responseAndLogEntry = webrequest.Method.ToString() + " ";
                        responseAndLogEntry += uri + "\r\n";
                        responseAndLogEntry += "filename: " + fileAndPath + "\r\n"
                            + "startdatetime: " + startdate + "\r\n"
                            + "enddatetime: " + enddate + "\r\n";
                        responseAndLogEntry += (int)response.StatusCode + " ";
                        responseAndLogEntry += response.StatusCode + "\r\n";
                    }
                }
                return responseAndLogEntry;
            }


        }

    Subject: RE: Send Message To Unity Connection using CUMI API
    Replied by: Sergey Knyazev on 28-11-2011 05:03:57 PM
    Brian Thank you so much for your help