YongboZhu
8/12/2017 - 6:37 AM

Microsoft Translator

Microsoft Translator

using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using Think.Formica.Extensions;

namespace Think.Formica.Translation
{
  public class MicrosoftTranslator : ITranslator
	{
		private string _clientID;
		private string _clientSecret;
		private string _translatorAccessUri;
		private string _accessHeader;
		private string _translatorUrl;
	
		public MicrosoftTranslator()
		{
			_translatorAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
			_translatorUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=";
			_clientID = "FormicaTestData";
			_clientSecret = "aJXPEJSKO2kOcC2mMdySE9SwK2pqBdjZ8MBTAjpTF00=";
		}
	
		public string ClientID
		{
			get { return _clientID ?? (_clientID = ConfigurationManager.AppSettings["Bing.ClientID"]); }
			set { _clientID = value; }
		}
	
		public string ClientSecret
		{
			get { return _clientSecret ?? (_clientSecret = ConfigurationManager.AppSettings["Bing.ClientSecret"]); }
			set { _clientSecret = value; }
		}
	
		public string TranslatorAccessUri
		{
			get { return _translatorAccessUri ?? (_translatorAccessUri = ConfigurationManager.AppSettings["Bing.AuthUrl"]); }
			set { _translatorAccessUri = value; }
		}
	
		public string TranslatorUrl
		{
			get { return _translatorUrl ?? (_translatorUrl = ConfigurationManager.AppSettings["Bing.TranslatorUrl"]); }
			set { _translatorUrl = value; }
		}
	
		private string GetAccessTokenheader()
		{
			var requestDetails = CreateTranslatorAuthUri();
	
			var webRequest = WebRequest.Create(TranslatorAccessUri);
			webRequest.ContentType = "application/x-www-form-urlencoded";
			webRequest.Method = "POST";
	
			var bytes = Encoding.ASCII.GetBytes(requestDetails);
	
			webRequest.ContentLength = bytes.Length;
			using (var outputStream = webRequest.GetRequestStream())
			{
				outputStream.Write(bytes, 0, bytes.Length);
			}
	
			var webResponse = (HttpWebResponse)webRequest.GetResponse();
	
			AdmAccessToken token = null;
			
			using (var stream = webResponse.GetResponseStream())
			{
				var serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));
				if (stream != null) token = (AdmAccessToken)serializer.ReadObject(stream);
			}
	
			return (token != null) ? "Bearer " + token.access_token : null;
		}
	
		private string CreateTranslatorAuthUri()
		{
			var requestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(ClientID), HttpUtility.UrlEncode(ClientSecret));
			return requestDetails;
		}
	
		public string Translate(string textTobeTranslated, string languageFrom, string languageTo)
		{
			textTobeTranslated.ThrowIfNullOrEmpty("textTobeTranslated");
			languageFrom.ThrowIfNullOrEmpty("languageFrom");
			languageTo.ThrowIfNullOrEmpty("languageTo");
	
			var accessheader = _accessHeader ?? (_accessHeader = GetAccessTokenheader());
	
			var uri = CreateTranslatorUri(textTobeTranslated, languageFrom, languageTo);
	
			var translationWebRequest = WebRequest.Create(uri);
			translationWebRequest.Headers.Add("Authorization", accessheader);
	
			var response = translationWebRequest.GetResponse();
	
			string translatedText = null;
			var encode = Encoding.GetEncoding("utf-8");
			using (var stream = response.GetResponseStream())
				if (stream != null)
					using(var translatedStream = new StreamReader(stream, encode))
					{
						var xTranslation = new System.Xml.XmlDocument();
						xTranslation.LoadXml(translatedStream.ReadToEnd());
						translatedText = xTranslation.InnerText;
					}
	
			return translatedText;
		}
	
		private string CreateTranslatorUri(string textTobeTranslated, string languageFrom, string languageTo)
		{
			var uri = string.Format("{0}{1}&from={2}&to={3}", TranslatorUrl, HttpUtility.UrlEncode(textTobeTranslated), languageFrom, languageTo);
			return uri;
		}
	}
}
public interface ITranslator
{
    string Translate(string originalString, string originalLanguageIso, string targetLanguageIso);
}
public class AdmAccessToken
{
  public string access_token { get; set; }
  
  public string token_type { get; set; }
  
  public string expires_in { get; set; }
  
  public string scope { get; set; }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*用法
int[] iArrary=new int[]{
1,5,13,6,10,55,99,2,87,12,34,75,33,47
}; 
BubbleSorter sh=new BubbleSorter(); 
sh.Sort(iArrary); 
for(int m=0;m< iArrary.Length;m++) 
Console.Write("{
0
} ",iArrary[m]); 
Console.WriteLine(); 
 */
namespace Search
{
 
    /// <summary>
    /// 排序
    /// </summary>
    public class Sorted
    {
 
        /// <summary>
        /// 冒泡排序
        /// </summary>
        /// <param name="list"></param>
        public static int[] BubbleSorter(int[] list)
        {
 
             
            int i, j, temp;
            bool done = false;
            j = 1;
            while ((j < list.Length) && (!done))
            {
 
                done = true;
                for (i = 0; i < list.Length - j; i++)
                {
 
                    if (list[i] > list[i + 1])
                    {
 
                        done = false;
                        temp = list[i];
                        list[i] = list[i + 1];
                        list[i + 1] = temp;
                     
}
                 
}
                j++;
             
}
            return list;
         
}
         
        /// <summary>
        /// 选择排序算法(Selection)
        /// </summary>
        /// <param name="list"></param>
        public static int[] SelectionSorter(int[] list)
        {
  
            int min;
            for (int i = 0; i < list.Length - 1; i++)
            {
 
                min = i;
                for (int j = i + 1; j < list.Length; j++)
                {
 
                    if (list[j] < list[min])
                        min = j;
                 
}
                int t = list[min];
                list[min] = list[i];
                list[i] = t;
             
}
            return list;
         
}
        /// <summary>
        /// 插入排序算法(InsertionSorter)
        /// </summary>
        /// <param name="list"></param>
        public static int[] InsertionSorter(int[] list)
        {
 
            for (int i = 1; i < list.Length; i++)
            {
 
                int t = list[i];
                int j = i;
                while ((j > 0) && (list[j - 1] > t))
                {
 
                    list[j] = list[j - 1];
                    --j;
                 
}
                list[j] = t;
             
}
            return list;
         
}
        /// <summary>
        /// 希尔排序算法
        /// </summary>
        /// <param name="list"></param>
        public static int[] ShellSorter(int[] list)
        {
 
            int inc;
            for (inc = 1; inc <= list.Length / 9; inc = 3 * inc + 1) ;
            for (; inc > 0; inc /= 3)
            {
 
                for (int i = inc + 1; i <= list.Length; i += inc)
                {
 
                    int t = list[i - 1];
                    int j = i;
                    while ((j > inc) && (list[j - inc - 1] > t))
                    {
 
                        list[j - 1] = list[j - inc - 1];
                        j -= inc;
                     
}
                    list[j - 1] = t;
                 
}
             
}
            return list;
         
}
     
}
 
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;


namespace Exceltosql
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //getdata();
        }
        /// <summary>
        /// 打开并显示Excl表数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.Multiselect = false;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                foreach (string filename in this.openFileDialog1.FileNames)
                {
                    this.textBox1.Text= filename;
                    string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + textBox1.Text + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
                    OleDbConnection conn = new OleDbConnection(strConn);
                    conn.Open();
                    DataSet ds = new DataSet();
                    OleDbDataAdapter odda = new OleDbDataAdapter("select * from [Sheet1$]", conn);
                    odda.Fill(ds);
                    dataGridView1.DataSource = ds.Tables[0].DefaultView;
                }
            }
            else
            {
                this.textBox1.Text = "请重新浏览";
            }
        }
        /// <summary>
        /// 装载Execl数据
        /// </summary>
        /// <param name="filenameurl"></param>
        /// <param name="table"></param>
        /// <returns></returns>
        public DataSet ExecleDs(string filenameurl, string table)
        {
            string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + filenameurl + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataSet ds = new DataSet();
            OleDbDataAdapter odda = new OleDbDataAdapter("select * from [Sheet1$]", conn);
            odda.Fill(ds, table);
            return ds;
        }
        /// <summary>
        /// 开始导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            string strConn = "Data Source=192.168.65.128;DataBase=hhaspx;Uid=sa;Pwd=7521"; //链接SQL数据库
            SqlConnection cn = new SqlConnection(strConn);
            cn.Open();
            string filename = this.openFileDialog1.FileName;
            string filenameurl = textBox1.Text;
            DataSet ds = ExecleDs(filenameurl, filename);           //调用自定义方法
            DataRow[] dr = ds.Tables[0].Select();            //定义一个DataRow数组
            int rowsnum = ds.Tables[0].Rows.Count;
            if (rowsnum == 0)
            {
                MessageBox.Show("Excel表为空表,无数据!");//当Excel表为空时提示
                
            }
            else
            {
                int temp = 0;
                for (int i = 0; i < dr.Length; i++)
                {
                   
                    string jiaoys = dr[i]["交易所"].ToString();// excel列名
                    string G_date = dr[i]["日期"].ToString();
                    string code = dr[i]["代码"].ToString();
                    string danwei = dr[i]["单位"].ToString();
                    string kaipanjia = dr[i]["开盘价"].ToString();
                    string zgaojia = dr[i]["最高价"].ToString();
                    string zdijia = dr[i]["最低价"].ToString();
                    string shoupanjia = dr[i]["收盘价"].ToString();
                    string chengjl = dr[i]["成交量"].ToString();
                    string zhangdf = dr[i]["涨跌幅"].ToString();
                    string zhangd = dr[i]["涨跌"].ToString();
                    string sqlcheck = "select count(*) from Gujia where jiaoys='" + jiaoys + "'And G_date='" + G_date + "'";  //检查交易所是否开盘
                    SqlCommand sqlcmd = new SqlCommand(sqlcheck, cn);
                    int count = Convert.ToInt32(sqlcmd.ExecuteScalar());
                    if (count < 1)
                    {
                        string insertstr = "insert into Gujia (jiaoys,G_date,code,danwei,kaipanjia,zgaojia,zdijia,shoupanjia,chengjl,zhangdf,zhangd) values('" + jiaoys + "','" + G_date + "','" + code + "','" + danwei + "','" + kaipanjia + "','" + zgaojia + "','" + zdijia + "','" + shoupanjia + "','" + chengjl + "','" + zhangdf + "','" + zhangd + "')";

                        SqlCommand cmd = new SqlCommand(insertstr, cn);
                        try
                        {
                            cmd.ExecuteNonQuery();
                            temp++;
                        }
                        catch (Exception ex)       //捕捉异常
                        {
                           MessageBox.Show(ex.Message);
                            
                        }
                    }
                    else
                    {
                        MessageBox.Show("内容重复!禁止导入", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        break;
                    }
                }
                if (temp==dr.Length)
                {
                    MessageBox.Show("Excle表导入成功!");
                    getdata();
                }
            }
            cn.Close();
        }
        /// <summary>
        /// 绑定导入后的数据
        /// </summary>
        private void  getdata() 
        {
          
            string strConn = "Data Source=192.168.65.128;DataBase=hhaspx;Uid=sa;Pwd=7521"; //链接SQL数据库
            SqlConnection cn = new SqlConnection(strConn);
            string sql = "select top 10 *  from Gujia";
            cn.Open();
            DataSet ds = new DataSet();
            SqlDataAdapter sda = new SqlDataAdapter(sql, cn);
            sda.Fill(ds);
            dataGridView2.DataSource = ds.Tables[0].DefaultView;
        }
    }
}