2012년 11월 12일 월요일

[코드]bing 번역기 (postID=5310951502590631750)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Web;
using System.ServiceModel.Channels;
using System.ServiceModel;

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.GraphicsInterface;

using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using WinApp = System.Windows.Forms.Application;

namespace MSTranslatorSdk
{
    [DataContract]
    public class AdmAccessToken
    {
        [DataMember]
        public string access_token { get; set; }
        [DataMember]
        public string token_type { get; set; }
        [DataMember]
        public string expires_in { get; set; }
        [DataMember]
        public string scope { get; set; }
    }

    public class AdmAuthentication
    {
        public static readonly string DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
        private string clientId;
        private string cientSecret;
        private string request;

        public AdmAuthentication(string clientId, string clientSecret)
        {
            this.clientId = clientId;
            this.cientSecret = clientSecret;
            //If clientid or client secret has special characters, encode before sending request
            this.request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientId), HttpUtility.UrlEncode(clientSecret));
        }

        public AdmAccessToken GetAccessToken()
        {
            return HttpPost(DatamarketAccessUri, this.request);
        }

        private AdmAccessToken HttpPost(string DatamarketAccessUri, string requestDetails)
        {
            //Prepare OAuth request
            WebRequest webRequest = WebRequest.Create(DatamarketAccessUri);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";
            byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
            webRequest.ContentLength = bytes.Length;
            using (Stream outputStream = webRequest.GetRequestStream())
            {
                outputStream.Write(bytes, 0, bytes.Length);
            }
            using (WebResponse webResponse = webRequest.GetResponse())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));
                //Get deserialized object from JSON stream
                AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
                return token;
            }
        }
    }
}

public class Script
{
    private ObjectId _idField;
    private ObjectId _idFrom;
    private ObjectId _idTo;

    private static void WriteLine(string msg)
    {
        Document doc = AcadApp.DocumentManager.MdiActiveDocument;
        Editor ed = doc.Editor;
        ed.WriteMessage(msg);
    }

    public string Open(string hField, string hFrom, string hTo)
    {
        Document doc = AcadApp.DocumentManager.MdiActiveDocument;
        Editor ed = doc.Editor;
        try
        {
            Database db = doc.Database;

            long ln1 = Convert.ToInt64(hField, 16);
            Handle hn1 = new Handle(ln1);
            _idField = db.GetObjectId(false, hn1, 0);

            long ln2 = Convert.ToInt64(hFrom, 16);
            if(ln2>0){
            Handle hn2 = new Handle(ln2);
            _idFrom = db.GetObjectId(false, hn2, 0);
            }

            long ln3 = Convert.ToInt64(hTo, 16);
            if(ln3>0){
            Handle hn3 = new Handle(ln3);
            _idTo = db.GetObjectId(false, hn3, 0);
            }
        }
        catch(Autodesk.AutoCAD.Runtime.Exception e)
        {
            return e.Message;
        }
        return "Loaded";
    }

        private void DetectMethod(string authToken)
        {
            string textToDetect = "Console";
            //Keep appId parameter blank as we are sending access token in authorization header.
            string uri = "http://api.microsofttranslator.com/v2/Http.svc/Detect?text=" + textToDetect;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            httpWebRequest.Headers.Add("Authorization", authToken);
            WebResponse response = null;
            try
            {
                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                    string languageDetected = (string)dcs.ReadObject(stream);
                    WriteLine(string.Format("\nLanguage detected:{0}", languageDetected));
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }

        private string TranslateMethod(string authToken)
        {
            string text = "Use pixels to express measurements for padding and margins.";
            string from = "en";
            string to = "de";

            string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(text) + "&from=" + from + "&to=" + to;

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            httpWebRequest.Headers.Add("Authorization", authToken);
            WebResponse response = null;
            try
            {
                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                    string translation = (string)dcs.ReadObject(stream);
                    WriteLine(string.Format("\nTranslation for source text '{0}' from {1} to {2} is", text, "en", "de"));
                    return translation;

                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
            return "fail";
        }

        private void ProcessWebException(WebException e)
        {
            WriteLine(string.Format("{0}", e.ToString()));
            // Obtain detailed error information
            string strResponse = string.Empty;
            using (HttpWebResponse response = (HttpWebResponse)e.Response)
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.ASCII))
                    {
                        strResponse = sr.ReadToEnd();
                    }
                }
            }
            WriteLine(string.Format("Http status code={0}, error message={1}", e.Status, strResponse));
        }


    public string Regen(string hField, string hFrom, string hTo)
    {
        string result = string.Empty;

            MSTranslatorSdk.AdmAccessToken admToken;
            string headerValue;
            string client_id = "mytranslator_arx119";
            string client_secret = "<??>";
            MSTranslatorSdk.AdmAuthentication admAuth = new MSTranslatorSdk.AdmAuthentication(client_id, client_secret);
            try
            {
                admToken = admAuth.GetAccessToken();
                headerValue = "Bearer " + admToken.access_token;
                DetectMethod(headerValue);
                result = TranslateMethod(headerValue);
            }
            catch (WebException e)
            {
                ProcessWebException(e);
            }
            catch (System.Exception ex)
            {
                WriteLine(ex.Message);
            }

        return result;
    }

    public void Modified(string hnd)
    {
    }

    public void Erased(string isErasing)
    {
    }

    public void Copied(string newId)
    {
    }

    public void Exit(string msg)
    {
    }
}

댓글 없음:

댓글 쓰기