Log in or register to post comments

VMS API Using C#

July 25, 2013 - 6:43pm #1

I have tried to use C# to implement the code,but I get 401

This is my code :

ASCIIEncoding Encoding = new ASCIIEncoding();
            MD5 md5 = MD5.Create();          
            string requestPath = "/targets";
            string serviceURI = "https://vws.vuforia.com" + requestPath;
            string httpVerb = "GET";
            var contentMD5bytes = md5.ComputeHash(Encoding.GetBytes(""));
            string contentMD5 = BitConverter.ToString(contentMD5bytes).Replace("-", "");
            string contentType = "";
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            string date = string.Format("{0:r}", DateTime.Now.ToUniversalTime());
            string StringToSign = String.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpVerb, contentMD5, contentType, date, requestPath); // HTTP-Verb, Content-MD5, Content-Type, Date, Request-Path;
            HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(Global.secret_key));
            byte[] sha1Bytes = Encoding.GetBytes(StringToSign);
            MemoryStream stream = new MemoryStream(sha1Bytes);
            byte[] sha1Hash = sha1.ComputeHash(stream);
            string signature = System.Convert.ToBase64String(sha1Hash);           
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceURI);
            request.Headers.Add("Authorization", string.Format("VWS {0}:{1}", Global.access_key, signature));
            request.Date = DateTime.Now.ToUniversalTime();           
            try
            {
                var response = await request.GetResponseAsync();
            }
            catch (WebException ex)
            {
           
            }

Can somebody help me,thanks.

VMS API Using C#

January 16, 2020 - 12:32pm #14

hi ziya786

I'm trying to upload my target with this code.

But the http request has exception.

I don't know why this happen.

Please help me.

VMS API Using C#

August 21, 2018 - 7:01pm #13

Awesome sample!  Does anyone have a C# sample for the multipart/form-data cloudreco query?

VMS API Using C#

June 12, 2018 - 1:24am #12

This is my code  it is working.

using Newtonsoft.Json;

using System;

using System.IO;

using System.Net;

using System.Net.Http;

using System.Net.Security;

using System.Reflection;

using System.Security.Cryptography;

using System.Security.Cryptography.X509Certificates;

using System.Text;

using System.Web.Script.Serialization;

namespace VWSConnection

{

    public class Program

    {

        private static string access_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";

        private static string secret_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";

        private static string url = @"https://vws.vuforia.com";

        private static string targetName = "Mobile";

        private static string imageLocation = Directory.GetCurrentDirectory() + "/Mobile.png";

        private static byte[] requestBytesArray;

        static void Main(string[] args)

        {

            PostNewTargets();

        }

        public static void PostNewTargets()

        {

            WebResponse response = null;

            try

            {

                string requestPath = "/targets";

                string serviceURI = url + requestPath;

                string httpAction = "POST";

                string contentType = "application/json";

                string date = string.Format("{0:r}", DateTime.Now.ToUniversalTime());

                var imageFile = File.Open(imageLocation, FileMode.Open);

                byte[] image;

                using (var br = new BinaryReader(imageFile))

                    image = br.ReadBytes((int)imageFile.Length);

                string metadataStr = "Mobile";

                byte[] metadata = ASCIIEncoding.ASCII.GetBytes(metadataStr);

                PostNewTrackableRequest model = new PostNewTrackableRequest();

                model.name = targetName;

                model.width = 8.0f;

                model.image = Convert.ToBase64String(image);

                model.active_flag = true;

                model.application_metadata = Convert.ToBase64String(metadata);

                var serializer = new JavaScriptSerializer();

                string requestBody = serializer.Serialize(model);

                HttpWebRequest httpWReq = (HttpWebRequest)HttpWebRequest.Create(serviceURI);                

                httpWReq.Method = httpAction;

                MethodInfo priMethod = httpWReq.Headers.GetType().GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);

                priMethod.Invoke(httpWReq.Headers, new[] { "Date", DateTime.UtcNow.ToString("ddd, dd MMM yyy HH:mm:ss") + " GMT" });

                httpWReq.ContentType = contentType;

                httpWReq.UseDefaultCredentials = true;

                httpWReq.PreAuthenticate = true;

                httpWReq.Credentials = CredentialCache.DefaultCredentials;

                MD5 md5 = MD5.Create();

                var contentMD5bytes = md5.ComputeHash(Encoding.ASCII.GetBytes(requestBody));

                StringBuilder sb = new StringBuilder();

                for (int i = 0; i < contentMD5bytes.Length; i++)

                {

                    sb.Append(contentMD5bytes[i].ToString("x2"));

                }

                string contentMD5 = sb.ToString();

                string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpAction, contentMD5, contentType, date, requestPath);

                HMACSHA1 sha1 = new HMACSHA1(Encoding.ASCII.GetBytes(secret_key));

                byte[] sha1Bytes = Encoding.ASCII.GetBytes(stringToSign);

                MemoryStream stream = new MemoryStream(sha1Bytes);

                byte[] sha1Hash = sha1.ComputeHash(stream);

                string signature = Convert.ToBase64String(sha1Hash);

                httpWReq.Headers.Add("Authorization", string.Format("VWS {0}:{1}", access_key, signature));

                var streamWriter = httpWReq.GetRequestStream();

                byte[] buffer = Encoding.ASCII.GetBytes(requestBody);

                requestBytesArray = buffer;

                streamWriter.Write(buffer, 0, buffer.Length);

                streamWriter.Flush();

                streamWriter.Close();

                response = httpWReq.GetResponse();

                Stream receiveStream = response.GetResponseStream();

                StreamReader sr = new StreamReader(receiveStream, Encoding.UTF8);

                string responseData = sr.ReadToEnd();

                response.Close();

                sr.Close();

                var result = JsonConvert.DeserializeObject(responseData);

            }

            catch (Exception e)

            {

                var message = e.Message;

                var innerException = e.InnerException;

            }

        }

        /// <summary>

        /// Method holds the certificates

        /// </summary>

        /// <param name="sender">Sender Id</param>

        /// <param name="certificate">Certificate object</param>

        /// <param name="chain">Chain object</param>

        /// <param name="sslPolicyErrors">policy errors</param>

        /// <returns>returns true</returns>

        public static bool ValidateServerCertificate(

                                                      object sender,

                                                      X509Certificate certificate,

                                                      X509Chain chain,

                                                      SslPolicyErrors sslPolicyErrors)

        {

            return true;

        }

    }

    public class PostNewTrackableRequest

    {

        public string name;

        public float width;

        public string image;

        public bool active_flag;

        public string application_metadata;

    }

}

VMS API Using C#

June 12, 2018 - 1:22am #11

--------------------

VMS API Using C#

May 6, 2018 - 2:01am #10

Hello are you done with your code ?

refer to the document you should add "d41d8cd98f00b204e9800998ecf8427e" to your MD5 hash code insted (contentMD5). please check and replay.

VMS API Using C#

January 11, 2018 - 12:40am #9

I tried your code to get response, I am also getting the same error.Can you please help me to figure out the error?

VMS API Using C#

August 4, 2013 - 12:43pm #8

Check the format of the Date field. It should look like this ..

Mon, 23 Apr 2012 12:45:19 GMT

* note the comma and that it ends w/ a space then GMT.

VMS API Using C#

August 2, 2013 - 5:34pm #7

This is my code :

ASCIIEncoding Encoding = new ASCIIEncoding();
            MD5 md5 = MD5.Create();          
            string requestPath = "/targets";
            string serviceURI = "https://vws.vuforia.com" + requestPath;
            string httpVerb = "GET";
            var contentMD5bytes = md5.ComputeHash(Encoding.GetBytes(""));
            string contentMD5 = BitConverter.ToString(contentMD5bytes).Replace("-", "");
            string contentType = "";
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            string date = string.Format("{0:r}", DateTime.Now.ToUniversalTime());
            string StringToSign = String.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpVerb, contentMD5, contentType, date, requestPath); // HTTP-Verb, Content-MD5, Content-Type, Date, Request-Path;
            HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(Global.secret_key));
            byte[] sha1Bytes = Encoding.GetBytes(StringToSign);
            MemoryStream stream = new MemoryStream(sha1Bytes);
            byte[] sha1Hash = sha1.ComputeHash(stream);
            string signature = System.Convert.ToBase64String(sha1Hash);           
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceURI);
            request.Headers.Add("Authorization", string.Format("VWS {0}:{1}", Global.access_key, signature));
            request.Date = DateTime.Now.ToUniversalTime();           
            try
            {
                var response = await request.GetResponseAsync();
            }
            catch (WebException ex)
            {
           
            }

VMS API Using C#

August 2, 2013 - 3:06pm #6

Are you still stuck? - if so post the code you are using.

VMS API Using C#

July 27, 2013 - 12:44pm #5

HI 

      I  too getting same exception  401 Unauthorized . Is any got any solution of intregating VWS API with c# or vb.net please help

 

VMS API Using C#

July 26, 2013 - 1:39pm #4

Check your date format, it should be in GMT and the string should end with " GMT".  Also it will be a good idea to post in the Cloud Recognition forum where other VWS devs will see your question. And it will be helpful to see the string that's being assigned to StringToSign.

VMS API Using C#

July 25, 2013 - 11:40pm #3

I have read that posts,so I  wrote the similar code,but I get 401,I don't know why?

Is there any C# sample that can be done right?

VMS API Using C#

July 25, 2013 - 10:50pm #2

Hi, if you search the Forum there are several threads discussing similar implementation issues in C#.

Also, may want to look at our Java samples for VWS; these are in Java, not in C#, but it may help yo by comparing the implementation with yours.

Check this link:

https://developer.vuforia.com/resources/dev-guide/managing-targets-cloud-database-using-developer-api

Log in or register to post comments