0 Replies Latest reply on Dec 3, 2009 3:30 AM by Intellixion

    Getting problem to integrate Acrobat.com's Document Service's APIs in ASP.Net3.5

    Intellixion

      Hello All,

       

      We want to integrate Acrobat.com's Document Service's APIs in our site (build in ASP.Net 3.5, IIS 6/7). We are getting an error when we trying to  post a doc file or jpg file to adobe server for pdf conversion.

       

      We have got the following error :
      /*******************************************/

      Server Error in '/' Application.

      The remote server returned an error: (400) Bad Request.

      Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

      Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.

      Source Error:

      An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

      Stack Trace:

      [WebException: The remote server returned an error: (400) Bad Request.]
         System.Net.HttpWebRequest.GetResponse() +5314029
         Paradigm.AdobAPI.UploadFileEx(String uploadfile, String URL, String requestBody) in D:\mywebsite\Paradigm\Paradigm\Paradigm\AdobAPI.aspx.cs:486
         Paradigm.AdobAPI.addFile(String fileName, String description, ShareAPINode parentNode, Boolean withRenditions, Boolean createPdf) in D:\mywebsite\Paradigm\Paradigm\Paradigm\AdobAPI.aspx.cs:125
         Paradigm.AdobAPI.Page_Load(Object sender, EventArgs e) in D:\mywebsite\Paradigm\Paradigm\Paradigm\AdobAPI.aspx.cs:36
         System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
         System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
         System.Web.UI.Control.OnLoad(EventArgs e) +99
         System.Web.UI.Control.LoadRecursive() +50
         System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627


       

      Version Information: Microsoft .NET Framework Version:2.0.50727.3082; ASP.NET Version:2.0.50727.3082


      /************************************** *******/

       

      Following are asp.net c# code:

       

      using System;
      using System.IO;
      using System.Net;
      using System.Security.Cryptography;
      using System.Text;
      using System.Xml;
      using EntityLayer;

       

      namespace Paradigm
      {
          public partial class AdobAPI : System.Web.UI.Page
          {
              protected static String DEFAULT_ENDPOINT = "https://api.share.acrobat.com/webservices/api/v1/";
              protected String ENDPOINT_AUTH = DEFAULT_ENDPOINT + "auth/";
              protected String ENDPOINT_SESSIONS = DEFAULT_ENDPOINT + "sessions/";
              protected String ENDPOINT_DC = DEFAULT_ENDPOINT + "dc/";
              public string requestBody = string.Empty;
              protected ShareAPIUser user = new ShareAPIUser();
              protected ShareAPINode ParentNode = new ShareAPINode();

       

              protected void Page_Load(object sender, EventArgs e)
              {
                  string authtoken1 = string.Empty; string sessionid1 = string.Empty; string secretID1 = string.Empty; string Name1 = string.Empty;
                  UserLogin(out authtoken1, out sessionid1, out secretID1, out Name1); // successfull

       

                  ParentNode = addFolder("tapas", "ttaa", null); // successfull

                  ParentNode = addFile("Test document.doc", "ss ff", ParentNode, true, true); // throw error
                  UserLogOut(sessionid1);
               }
              public void UserLogin(out string authtoken, out string sessionid, out string secretID, out string Name)
              {
                  string Res = string.Empty; string authtoken1 = string.Empty; string sessionid1 = string.Empty; string secretID1 = string.Empty; string Name1 = string.Empty;

       

                  requestBody =
                            "<request>" +
                                "<username>" + "tapas.ghosh@indusnet.co.in" + "</username>" +
                                "<password>" + "123456" + "</password>" +
                            "</request>";
                  Res = GetWebResponce(user, "POST", ENDPOINT_AUTH, true, requestBody, "application/x-www-form-urlencoded");
                  /**************************************************************************************** ***/
                  authtoken1 = GetXMLNodeValue(Res, "authtoken"); Res = "";
                  requestBody =
                          "<request>" +
                              "<authtoken>" + authtoken1 + "</authtoken>" +
                          "</request>";
                  Res = GetWebResponce(user, "POST", ENDPOINT_SESSIONS, true, requestBody, "application/x-www-form-urlencoded");
                  sessionid1 = GetXMLNodeValue(Res, "sessionid");
                  secretID1 = GetXMLNodeValue(Res, "secret");
                  Name1 = GetXMLNodeValue(Res, "name"); Res = "";
                  authtoken = authtoken1; Name = Name1;
                  user.sessionid = sessionid = sessionid1;
                  user.secret = secretID = secretID1;
              }

       

              public bool UserLogOut(string SessionID)
              {
                  bool Res = false;
                  string Responce = GetWebResponce(user, "DELETE", ENDPOINT_SESSIONS + SessionID + "/", false, "", "");
                  if (Responce.Contains("ok"))
                      Res = true;
                  return Res;
              }

       

              public ShareAPINode addFile(string fileName, String description, ShareAPINode parentNode, bool withRenditions, bool createPdf)
              {
                  string Responce = string.Empty;
                  if (parentNode != null)
                  {
                      //assertValidNode(parentNode);
                  }

       


                //  try
                //  {
                      String requestBody =
                          "<request>" +
                              "<file>" +
                                  "<name>" + fileName + "</name>" +
                                  "<description>" + description + "</description>" +
                                  "<renditions>" + withRenditions + "</renditions>" +
                                  "<createpdf>" + createPdf + "</createpdf>" +
                              "</file>" +
                          "</request>";
                      if (parentNode != null)
                      {
                          Responce = UploadFileEx(Server.MapPath("~/UploadedFiles/" + fileName), ENDPOINT_DC + parentNode.Id + "/", requestBody);
                      }
                      else
                      {
                          Responce = UploadFileEx(Server.MapPath("~/UploadedFiles/" + fileName), ENDPOINT_DC, requestBody);
                      }
                      //JSONObject node = json.getJSONObject("response").optJSONObject("node");

       

                 // }
                 // catch
                  //{ }
                  return parentNode;
              }

       

              public ShareAPINode addFolder(String name, String description, ShareAPINode parentNode)
              {
                  string Responce = string.Empty;
                  if (parentNode != null)
                  {
                      //assertFolderNode(parentNode);
                  }

       


                //  try
               //   {
                      String requestBody =
                          "<request>" +
                              "<folder>" +
                                  "<name>" + name + "</name>" +
                                  "<description>" + description + "</description>" +
                              "</folder>" +
                          "</request>";
                      if (parentNode != null)
                      { Responce = GetWebResponce(user, "POST", ENDPOINT_DC + parentNode.Id + "/", false, requestBody, "application/x-www-form-urlencoded"); }
                      else
                      { Responce = GetWebResponce(user, "POST", ENDPOINT_DC, false, requestBody, "application/x-www-form-urlencoded"); }

       

                      if (parentNode == null)
                          parentNode = new ShareAPINode();

       

                      string[] SplitMSG = Responce.Split(' ');
                      foreach (string s in SplitMSG)
                      {
                          if (s.Contains("nodeid="))
                              parentNode.Id = RemoveExtraContent(s, "nodeid=");
                          else if (s.Contains("name="))
                              parentNode.Name = RemoveExtraContent(s, "name=");
                          else if (s.Contains("description="))
                              parentNode.Description = RemoveExtraContent(s, "description=");
                          else if (s.Contains("createddate="))
                              parentNode.CreatedDate = RemoveExtraContent(s, "createddate=");
                          else if (s.Contains("modifieddate="))
                              parentNode.ModifiedDate = RemoveExtraContent(s, "modifieddate=");
                      }

       

                 // }
                //  catch { }
                  return parentNode;
              }

       

              #region This Section For Web Responce Out Put
              public string RemoveExtraContent(string OriginalContent, string RemoveContentName)
              {
                  string Res = string.Empty;
                  Res = OriginalContent.Replace(RemoveContentName, "");
                  Res = Res.Replace("\"", "");
                  return Res;
              }
              public string GetWebResponce(ShareAPIUser user, string Method, string URL, bool anon, string requestBody, string ContentType)
              {
                  string Res = string.Empty;
                  byte[] bytes = Encoding.UTF8.GetBytes(requestBody);
                  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
                  request.Method = Method;
                  request.ContentLength = bytes.Length;
                  request.ContentType = ContentType;
                  request.Headers.Set("Authorization", generateAuthorization(user, anon, Method, URL));
                  using (Stream requestStream = request.GetRequestStream())
                  {
                      requestStream.Write(bytes, 0, bytes.Length);
                  }
                  using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                  {
                      if ((response.ContentLength > 0))
                      {
                          System.IO.StreamReader str = new System.IO.StreamReader(response.GetResponseStream());
                          Res = str.ReadToEnd();
                          if (str != null)
                              str.Close();
                      }
                  }
                  return Res;
              }
              protected string generateAuthorization(ShareAPIUser user, bool anon, string method, string url)
              {
                  StringBuilder sb = new StringBuilder();
                  sb.Append("AdobeAuth ");
                  if (!anon && user.sessionid != null)
                  {
                      sb.Append("sessionid=\"").Append(user.sessionid).Append("\",");
                  }
                  sb.Append("apikey=\"").Append(user.apikey).Append("\",");
                  string calltime = DateTime.Now.ToShortTimeString();
                  StringBuilder data = new StringBuilder();
                  data.Append(method).Append(" ").Append(url).Append(" ").Append(calltime);
                  sb.Append("data=\"").Append(data).Append("\",");
                  sb.Append("sig=\"").Append(generateSig(user, data.ToString())).Append("\"");
                  return sb.ToString();
              }
              protected string generateSig(ShareAPIUser user, string data)
              {
                  try
                  {
                      MD5CryptoServiceProvider md = new MD5CryptoServiceProvider();
                      if (user.secret == null)
                          return GetMD5Hash(data + user.secret);
                      else
                          return GetMD5Hash(data + user.secret);
                  }
                  catch
                  { }
                  return null;
              }
              public string GetMD5Hash(string input)
              {
                  System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
                  byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
                  bs = x.ComputeHash(bs);
                  System.Text.StringBuilder s = new System.Text.StringBuilder();
                  foreach (byte b in bs)
                  {
                      s.Append(b.ToString("x2").ToLower());
                  }
                  string Res = s.ToString();
                  return Res;
              }
              public string GetXMLNodeValue(string strXml, string TagName)
              {
                  XmlDocument xml = new XmlDocument();
                  xml.LoadXml(strXml);
                  XmlNode Node = xml.DocumentElement;
                  XmlNodeList NList = Node.SelectNodes(TagName);
                  if (NList != null)
                      return NList.Item(0).InnerText;
                  else
                      return "Not Found";
              }
              #endregion

       

              #region This Section for File upload to web site. It is not working
              public string UploadFileEx(string uploadfile, string URL, string requestBody)
              {
                  string Res = string.Empty;
                 // try
                 // {
                      string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
                      HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(URL);
                      webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
                      webrequest.Method = "POST";
                      webrequest.Headers.Set("Authorization", generateAuthorization(user, false, "POST", URL));

       

                      // Build up the post message header
                      StringBuilder sb = new StringBuilder();
                      sb.Append("--");
                      sb.Append(boundary);
                      sb.Append("\r\n");
                      sb.Append("Content-Disposition: form-data; name=\"request");
                      sb.Append("\"");
                      sb.Append("\r\n");
                      sb.Append("\r\n");
                      sb.Append(requestBody);
                      sb.Append("\r\n");
                      sb.Append("\r\n");
                      sb.Append("--");
                      sb.Append(boundary);
                      sb.Append("\r\n");
                      sb.Append("Content-Disposition: form-data; name=\"file");
                      sb.Append("\"; ");
                      sb.Append(" filename=\"");
                      sb.Append(Path.GetFileName(uploadfile));
                      sb.Append("\"");
                      sb.Append("\r\n");
                      sb.Append("Content-Type: application/octet-stream");
                      sb.Append("\r\n");
                      sb.Append("Content-Transfer-Encoding: binary");
                      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(uploadfile, FileMode.Open, FileAccess.Read);
                      long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
                      webrequest.ContentLength = length;

       

                      Stream requestStream = webrequest.GetRequestStream();

       

                      // Write out our post header
                      requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

       

                      // Write out the file contents
                      byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
                      int bytesRead = 0;
                      while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                          requestStream.Write(buffer, 0, bytesRead);

       

                      // Write out the trailing boundary
                      requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                      WebResponse responce = webrequest.GetResponse(); // throw error in this line

       

                      Stream s = responce.GetResponseStream();
                      StreamReader sr = new StreamReader(s);

       

                      Res = sr.ReadToEnd().ToString();

       

               //   }
               //   catch
               //   { }
                  return Res;
              }
              #endregion

       

          }
      }

       

       

      We want to purchase this service for converting different type of document and adobe files to pdf. But before that we want to make sure that it is working fine with ASP.Net3.5 c#.

       

      We are in a hurry to implement it in our site. Please point out the problem in our code. You can refer any sample code for ASP.Net C#.

       

      Thanks & Regards,

       

      Avijit.