Пример #1
0
        /// <summary>
        /// 文件加密
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEncrpt_Click(object sender, EventArgs e)
        {
            if (txtMagPDF.Text == "")
            {
                string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0085I", db.Language);
                MessageBox.Show(msg);
                return;
            }
            string password = getPassword();

            if (string.IsNullOrEmpty(password))
            {
                string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0116I", db.Language);
                MessageBox.Show(msg);
                return;
            }
            string destFile = Path.Combine(Path.GetDirectoryName(txtMagPDF.Text), "_" + Path.GetFileName(txtMagPDF.Text));

            try
            {
                NCPDF.DecriptPdfDoc(txtMagPDF.Text, destFile, password);
                File.Delete(txtMagPDF.Text);
                File.Move(destFile, txtMagPDF.Text);
                string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0117I", db.Language);
                MessageBox.Show(msg);
            }
            catch (Exception ex)
            {
                string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0118I", db.Language);
                MessageBox.Show(msg);
                NCLogger.GetInstance().WriteExceptionLog(ex);
            }
        }
Пример #2
0
        /// <summary>
        /// 配置
        /// </summary>
        /// <returns></returns>
        private bool GetConfigValue()
        {
            bool ret = true;

            ///取得配置信息
            NCLogger.GetInstance().WriteInfoLog("GetConfigValue Start");
            NdnXmlConfig xmlConfig;

            xmlConfig = new NdnXmlConfig(NCConst.CONFIG_FILE_DIR + NCUtility.GetAppConfig());
            if (!xmlConfig.ReadXmlData("config", "ftpserver", ref ftpserver))
            {
                ret = false;
            }
            if (!xmlConfig.ReadXmlData("config", "ftpuser", ref userName))
            {
                ret = false;
            }
            if (!xmlConfig.ReadXmlData("config", "ftppassword", ref password))
            {
                ret = false;
            }
            password = NCCryp.Decrypto(password);

            NCLogger.GetInstance().WriteInfoLog("GetConfigValue end");
            return(ret);
        }
Пример #3
0
 /// <summary>
 /// 初始化
 /// </summary>
 /// <returns></returns>
 internal static bool Init()
 {
     NCLogger.GetInstance().WriteInfoLog("Init Start");
     if (!GetConfigValue())
     {
         NCLogger.GetInstance().WriteInfoLog("not GetConfigValue");
         return(false);
     }
     try
     {
         process_timer          = new System.Timers.Timer();
         process_timer.Interval = 30000;
         process_timer.Elapsed += new System.Timers.ElapsedEventHandler(DoUploadProcess);
         process_timer.Elapsed += new System.Timers.ElapsedEventHandler(DoDownloadProcess);
         process_timer.Elapsed += new System.Timers.ElapsedEventHandler(DoFtpUploadProcess);
         process_timer.Elapsed += new System.Timers.ElapsedEventHandler(DoCustomerSyncProcess);
         process_timer.Elapsed += new System.Timers.ElapsedEventHandler(DoSendMailProcess);
         process_timer.Start();
     }
     catch (Exception ex)
     {
         NCLogger.GetInstance().WriteExceptionLog(ex);
     }
     NCLogger.GetInstance().WriteInfoLog("Init end");
     return(true);
 }
Пример #4
0
        /// <summary>
        /// executeCjwScriptを実行する。
        /// </summary>
        private bool executeCjwScript(string dbName, string scriptFile)
        {
            string strConnectionString = string.Format(
                "Data Source={0};Initial Catalog={1};User ID={2};Password={3}",
                txtDataSource.Text, dbName, txtUser.Text, txtPwd.Text);
            SqlConnection conn = new SqlConnection(strConnectionString);

            try
            {
                FileInfo file   = new FileInfo(scriptFile);
                string   script = file.OpenText().ReadToEnd();
                conn.Open();
                IEnumerable <string> commands = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                foreach (string command in commands)
                {
                    if (command.Trim() != "")
                    {
                        new SqlCommand(command, conn).ExecuteNonQuery();
                    }
                }
                lblInfor.Text = NCMessage.GetInstance(db.Language).GetMessageById("CM0163I", db.Language);
                Application.DoEvents();
                conn.Close();
            }
            catch (Exception ex)
            {
                NCLogger.GetInstance().WriteExceptionLog(ex);
                lblInfor.Text = NCMessage.GetInstance(db.Language).GetMessageById("CM0163E", db.Language);
                Application.DoEvents();
                conn.Close();
                return(false);
            }
            return(true);
        }
Пример #5
0
        /// <summary>
        /// 配置値设定
        /// </summary>
        private Boolean SetDatabaseConfig()
        {
            NdnXmlConfig xmlConfig;

            xmlConfig = new NdnXmlConfig(NCConst.CONFIG_FILE_DIR + NCUtility.GetAppConfig());
            string strConnectionString = string.Format(
                "Data Source={0};Initial Catalog={1};User ID={2};Password={3}",
                txtDataSource.Text, txtDatabase.Text, txtUser.Text, NCCryp.Encrypto(txtPwd.Text));
            string str = "ConnectionString";

            if (!xmlConfig.WriteValue("database", str, strConnectionString))
            {
                string msg = string.Format(NCMessage.GetInstance(db.Language).GetMessageById("CM0450E", db.Language), str);
                NCLogger.GetInstance().WriteErrorLog(msg);
                return(false);
            }
            strConnectionString = string.Format(
                "Data Source={0};Initial Catalog={1};User ID={2};Password={3}",
                txtDataSource.Text, "master", txtUser.Text, NCCryp.Encrypto(txtPwd.Text));
            str = "MConnectionString";
            if (!xmlConfig.WriteValue("database", str, strConnectionString))
            {
                string msg = string.Format(NCMessage.GetInstance(db.Language).GetMessageById("CM0450E", db.Language), str);
                NCLogger.GetInstance().WriteErrorLog(msg);
                return(false);
            }
            return(SetDatabaseConfig2());
        }
Пример #6
0
        /// <summary>
        /// 创建数据库
        /// </summary>
        private Boolean restoreDatabase(string dbName, string dbFile)
        {
            string strConnectionString = string.Format(
                "Data Source={0};Initial Catalog={1};User ID={2};Password={3}",
                txtDataSource.Text, "master", txtUser.Text, txtPwd.Text);
            SqlConnection RestoreCon = new SqlConnection(strConnectionString);

            try
            {
                RestoreCon.Open();
                SqlCommand RestoreCmd1 = new SqlCommand();
                RestoreCmd1.CommandText    = string.Format("RESTORE DATABASE [{0}] FROM DISK=N'{1}' with FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 10", dbName, dbFile);
                RestoreCmd1.Connection     = RestoreCon;
                RestoreCmd1.CommandTimeout = 300000;
                RestoreCmd1.ExecuteNonQuery();
                lblInfor.Text = NCMessage.GetInstance(db.Language).GetMessageById("CM0162I", db.Language);
                Application.DoEvents();
                RestoreCon.Close();
            }
            catch (Exception ex)
            {
                NCLogger.GetInstance().WriteExceptionLog(ex);
                RestoreCon.Close();

                lblInfor.Text = NCMessage.GetInstance(db.Language).GetMessageById("CM0162E", db.Language);
                Application.DoEvents();
                return(false);
            }
            return(true);
        }
Пример #7
0
        /// <summary>
        /// 应用程序启动
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="localworkpath"></param>
        /// <returns></returns>
        public static int ExecuteCommand(string cmd, string para, string localworkpath, bool userShell)
        {
            int exitCode = -1;

            try
            {
                Process process = new Process();
                process.StartInfo.UseShellExecute = userShell;
                process.StartInfo.FileName        = cmd;
                if (!string.IsNullOrEmpty(para))
                {
                    process.StartInfo.Arguments = para;
                }
                process.StartInfo.WorkingDirectory = localworkpath;
                process.Start();
                //process.WaitForExit();
                exitCode = process.ExitCode;
                process.Close();
            }
            catch (Exception ex)
            {
                NCLogger.GetInstance().WriteExceptionLog(ex);
                exitCode = -1;
            }
            return(exitCode);
        }
Пример #8
0
 /// <summary>
 /// 释放
 /// </summary>
 internal static void Dispose()
 {
     NCLogger.GetInstance().WriteInfoLog("Dispose Start");
     process_timer.Stop();
     process_timer.Close();
     process_timer.Dispose();
     NCLogger.GetInstance().WriteInfoLog("Dispose end");
 }
Пример #9
0
        /// <summary>
        /// Post
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bntPost_Click(object sender, EventArgs args)
        {
            pgbPost.Value   = 0;
            pgbPost.Maximum = ds_media.Tables[0].Rows.Count;
            for (int idx = 0; idx < ds_media.Tables[0].Rows.Count; idx++)
            {
                String mediaPublishId = ds_media.Tables[0].Rows[idx]["发布编号"].ToString();
                setMediaPublishStatus(mediaPublishId, "发行中");
                string content = ds_media.Tables[0].Rows[CurrentIndex - 1]["名称"].ToString()
                                 + ds_media.Tables[0].Rows[CurrentIndex - 1]["发行期号"].ToString()
                                 + "[" + ds_media.Tables[0].Rows[CurrentIndex - 1]["发行日期"].ToString() + "]\r\n"
                                 + ds_media.Tables[0].Rows[CurrentIndex - 1]["文本内容"].ToString();
                string picpath = ds_media.Tables[0].Rows[CurrentIndex - 1]["本地图片"].ToString();

                try
                {
                    string msg      = HttpUtility.UrlEncode(content);
                    string endpoint = null;
                    switch (provider_type)
                    {
                    case PROVIDER_TYPE.FACEBOOK:
                        endpoint = "https://graph.facebook.com/me/feed?message=" + msg + "&access_token="
                                   + SocialAuthUser.GetCurrentUser().GetConnection(PROVIDER_TYPE.FACEBOOK).GetConnectionToken().AccessToken;
                        break;

                    case PROVIDER_TYPE.TWITTER:
                        endpoint = "http://api.twitter.com/1.1/statuses/update.json?status=" + msg;
                        break;
                    }

                    string body = String.Empty;
                    //byte[] reqbytes = new ASCIIEncoding().GetBytes(body);
                    byte[] reqbytes = File.ReadAllBytes(ds_media.Tables[0].Rows[idx]["本地图片"].ToString());
                    Dictionary <string, string> headers = new Dictionary <string, string>();
                    //headers.Add("contentType", "application/x-www-form-urlencoded");
                    headers.Add("contentType", "image/jpeg");
                    headers.Add("FileName", Path.GetFileName(ds_media.Tables[0].Rows[idx]["本地图片"].ToString()));
                    var response = manager.ExecuteFeed(
                        endpoint,
                        TRANSPORT_METHOD.POST,
                        provider_type,
                        reqbytes,
                        headers
                        );
                    setMediaPublishStatus(mediaPublishId, "发行完");
                }
                catch (Exception ex)
                {
                    setMediaPublishStatus(mediaPublishId, "未发行");
                    NCLogger.GetInstance().WriteExceptionLog(ex);
                }
            }
        }
Пример #10
0
 protected override void OnStart(string[] args)
 {
     NCLogger.GetInstance().WriteInfoLog("OnStart start");
     try
     {
         NGProcess.Init();
     }
     catch (Exception ex)
     {
         NCLogger.GetInstance().WriteExceptionLog(ex);
     }
     NCLogger.GetInstance().WriteInfoLog("OnStart end");
 }
Пример #11
0
 protected override void OnStop()
 {
     NCLogger.GetInstance().WriteInfoLog("OnStop start");
     try
     {
         NGProcess.Dispose();
     }
     catch (Exception ex)
     {
         NCLogger.GetInstance().WriteExceptionLog(ex);
     }
     NCLogger.GetInstance().WriteInfoLog("OnStop start");
 }
Пример #12
0
 /// <summary>
 /// 画面初期化
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void FormRegist_Load(object sender, EventArgs e)
 {
     try
     {
         if (GetProductValue())
         {
             string[] products = product.Split(';');
             foreach (string prod in products)
             {
                 cmbProduct.Items.Add(prod);
             }
             cmbProduct.SelectedIndex = 0;
         }
         txtProductID.Text = NCCryp.getProductID();
         if (txtProductID.Text == "")
         {
             string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0106I", db.Language);
             MessageBox.Show(msg);
             return;
         }
     }
     catch (Exception ex)
     {
         NCLogger.GetInstance().WriteExceptionLog(ex);
         return;
     }
     if (GetConfigValue())
     {
         txtLicId.Text = lic;
         if (txtLicId.Text != "" && NCCryp.checkLic(txtLicId.Text))
         {
             btnRegist.Enabled = false;
             btnSend.Enabled   = false;
             btnAdd.Enabled    = false;
         }
     }
     if (isOwner())
     {
         txtProductID.ReadOnly = false;
         btnCreate.Enabled     = true;
         btnCreate.Visible     = true;
         btnAdd.Enabled        = true;
     }
     else
     {
         btnCreate.Enabled = false;
         btnCreate.Visible = false;
         btnAdd.Enabled    = false;
     }
 }
Пример #13
0
        /// <summary>
        /// 配置値设定
        /// </summary>
        private void SetProductValue(string product)
        {
            string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0460I", db.Language);

            NCLogger.GetInstance().WriteInfoLog(msg);
            NdnXmlConfig xmlConfig;

            xmlConfig = new NdnXmlConfig(NCConst.CONFIG_FILE_DIR + NCUtility.GetAppConfig());
            if (!xmlConfig.WriteValue("config", "Product", product))
            {
                msg = string.Format(NCMessage.GetInstance(db.Language).GetMessageById("CM0450E", db.Language), product);
                NCLogger.GetInstance().WriteErrorLog(msg);
            }
            msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0470I", db.Language);
            NCLogger.GetInstance().WriteInfoLog(msg);
        }
Пример #14
0
        /// <summary>
        /// 创建数据库
        /// </summary>
        private Boolean createDatabase(string dbName, string dbFile)
        {
            string createsql           = @"IF NOT EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'{0}')
                BEGIN
                DECLARE @data_path nvarchar(1024), @db_path nvarchar(1024), @log_path nvarchar(1024)
                EXEC master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\Microsoft SQL Server\Setup', N'SQLDataRoot', @data_path OUTPUT    
                SET @db_path = @data_path + N'\Data\{0}_Data.MDF';
                SET @log_path = @data_path + N'\Data\{0}_log.ldf';
                EXECUTE (N'
                    CREATE DATABASE [{0}]  ON (NAME = N''{0}_Data'', 
                     FILENAME = N''' + @db_path  + N''',
                     SIZE = 5, FILEGROWTH = 10%) LOG ON (NAME = N''{0}_Log'',
                     FILENAME = N''' + @log_path + N''',
                     SIZE = 5, FILEGROWTH = 10%)
                     COLLATE Chinese_PRC_CI_AS')
                END";
            string strConnectionString = string.Format(
                "Data Source={0};Initial Catalog={1};User ID={2};Password={3}",
                txtDataSource.Text, "master", txtUser.Text, txtPwd.Text);
            SqlConnection createCon = new SqlConnection(strConnectionString);

            try
            {
                createCon.Open();
                SqlCommand RestoreCmd = new SqlCommand();
                RestoreCmd.CommandText = string.Format(createsql, dbName);
                RestoreCmd.Connection  = createCon;
                RestoreCmd.ExecuteNonQuery();

                lblInfor.Text = NCMessage.GetInstance(db.Language).GetMessageById("CM0161I", db.Language);
                Application.DoEvents();
                createCon.Close();
            }
            catch (Exception ex)
            {
                NCLogger.GetInstance().WriteExceptionLog(ex);
                createCon.Close();

                lblInfor.Text = NCMessage.GetInstance(db.Language).GetMessageById("CM0161E", db.Language);
                Application.DoEvents();
                return(false);
            }
            return(true);
        }
Пример #15
0
        /// <summary>
        /// Post
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bntPost_Click(object sender, EventArgs args)
        {
            pgbPost.Value   = 0;
            pgbPost.Maximum = ds_media.Tables[0].Rows.Count;
            for (int idx = 0; idx < ds_media.Tables[0].Rows.Count; idx++)
            {
                String mediaPublishId = ds_media.Tables[0].Rows[idx]["发布编号"].ToString();
                setMediaPublishStatus(mediaPublishId, "发行中");

                string content = ds_media.Tables[0].Rows[idx]["名称"].ToString()
                                 + ds_media.Tables[0].Rows[idx]["发行期号"].ToString()
                                 + "[" + ds_media.Tables[0].Rows[idx]["发行日期"].ToString() + "]\r\n"
                                 + ds_media.Tables[0].Rows[idx]["文本内容"].ToString();
                string picpath = ds_media.Tables[0].Rows[idx]["本地图片"].ToString();

                try
                {
                    Dictionary <string, Stream> data = new Dictionary <string, Stream>();
                    data.Add(Path.GetFileName(picpath),
                             new FileStream(picpath, FileMode.Open, FileAccess.Read));
                    if (content.Length > 70)
                    {
                        content = content.Substring(0, 70);
                    }
                    string userid  = null;
                    string photoId = null;
                    if (((OffsiteContext)service.Context).MakeRequest(
                            string.Format(/*V1Endpoints.PHOTO_URL*/ "", userid, photoId),
                            ResponseFormatType.JSON, HttpMethodType.GET, null, true, true) != null)
                    {
                        setMediaPublishStatus(mediaPublishId, "发行完");
                    }
                    else
                    {
                        setMediaPublishStatus(mediaPublishId, "未发行");
                    }
                }
                catch (Exception ex)
                {
                    setMediaPublishStatus(mediaPublishId, "未发行");
                    NCLogger.GetInstance().WriteExceptionLog(ex);
                }
            }
        }
        /// <summary>
        /// Post
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bntPost_Click(object sender, EventArgs args)
        {
            pgbPost.Value   = 0;
            pgbPost.Maximum = ds_media.Tables[0].Rows.Count;
            for (int idx = 0; idx < ds_media.Tables[0].Rows.Count; idx++)
            {
                String mediaPublishId = ds_media.Tables[0].Rows[idx]["发布编号"].ToString();
                setMediaPublishStatus(mediaPublishId, "发行中");

                string content = ds_media.Tables[0].Rows[idx]["名称"].ToString()
                                 + ds_media.Tables[0].Rows[idx]["发行期号"].ToString()
                                 + "[" + ds_media.Tables[0].Rows[idx]["发行日期"].ToString() + "]\r\n"
                                 + ds_media.Tables[0].Rows[idx]["文本内容"].ToString();
                string picpath = ds_media.Tables[0].Rows[idx]["本地图片"].ToString();

                try
                {
                    SendTweetWithMediaOptions sendOptions = new SendTweetWithMediaOptions();
                    sendOptions.Images = new Dictionary <string, Stream>();
                    sendOptions.Images.Add(Path.GetFileName(picpath),
                                           new FileStream(picpath, FileMode.Open, FileAccess.Read));
                    if (content.Length > 70)
                    {
                        content = content.Substring(0, 70);
                    }
                    sendOptions.Status = content;

                    if (service.SendTweetWithMedia(sendOptions) != null)
                    {
                        setMediaPublishStatus(mediaPublishId, "发行完");
                    }
                    else
                    {
                        setMediaPublishStatus(mediaPublishId, "未发行");
                    }
                }
                catch (Exception ex)
                {
                    setMediaPublishStatus(mediaPublishId, "未发行");
                    NCLogger.GetInstance().WriteExceptionLog(ex);
                }
            }
        }
        /// <summary>
        /// Post
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bntPost_Click(object sender, EventArgs args)
        {
            pgbPost.Value   = 0;
            pgbPost.Maximum = ds_media.Tables[0].Rows.Count;
            for (int idx = 0; idx < ds_media.Tables[0].Rows.Count; idx++)
            {
                String mediaPublishId = ds_media.Tables[0].Rows[idx]["发布编号"].ToString();
                setMediaPublishStatus(mediaPublishId, "发行中");

                string content = ds_media.Tables[0].Rows[idx]["名称"].ToString()
                                 + ds_media.Tables[0].Rows[idx]["发行期号"].ToString()
                                 + "[" + ds_media.Tables[0].Rows[idx]["发行日期"].ToString() + "]\r\n"
                                 + ds_media.Tables[0].Rows[idx]["文本内容"].ToString();
                string picpath = ds_media.Tables[0].Rows[idx]["本地图片"].ToString();

                try
                {
                    OauthKey oauthKey = new OauthKey();
                    oauthKey.customKey    = appKey;
                    oauthKey.customSecret = appSecret;
                    oauthKey.tokenKey     = accessKey;
                    oauthKey.tokenSecret  = accessSecret;

                    ///发送带图片微博
                    t            twit = new t(oauthKey, "json");
                    UTF8Encoding utf8 = new UTF8Encoding();

                    string ret = twit.add_pic(utf8.GetString(utf8.GetBytes(content)),
                                              utf8.GetString(utf8.GetBytes("127.0.0.1")),
                                              utf8.GetString(utf8.GetBytes("")),
                                              utf8.GetString(utf8.GetBytes("")),
                                              utf8.GetString(utf8.GetBytes(picpath))
                                              );
                    setMediaPublishStatus(mediaPublishId, "发行完");
                }
                catch (Exception ex)
                {
                    setMediaPublishStatus(mediaPublishId, "未发行");
                    NCLogger.GetInstance().WriteExceptionLog(ex);
                }
            }
        }
Пример #18
0
 /// <summary>
 /// 文档下载处理
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 internal static void DoDownloadProcess(object sender, ElapsedEventArgs e)
 {
     NCLogger.GetInstance().WriteInfoLog("DoDownloadProcess Start");
     time_span++;
     if (time_span.ToString() == notice_span)
     {
         time_span = 0;
         try
         {
             process_timer.Stop();
             DownloadProcess();
         }
         catch (Exception ex)
         {
             NCLogger.GetInstance().WriteExceptionLog(ex);
         }
         finally
         {
             process_timer.Start();
         }
     }
     NCLogger.GetInstance().WriteInfoLog("DoDownloadProcess end");
 }
Пример #19
0
        /// <summary>
        /// executeCjwScriptを実行する。
        /// </summary>
        private bool executeCjwScript(string scriptFile)
        {
            string strConnectionString = string.Format(
                "Data Source={0};Initial Catalog={1};User ID={2};Password={3}",
                strDataSource, strDbName, strUserName, strPassword);
            SqlConnection conn = new SqlConnection(strConnectionString);

            try
            {
                FileInfo file = new FileInfo(scriptFile);
                using (StreamReader sr = file.OpenText())
                {
                    string script = sr.ReadToEnd();

                    conn.Open();
                    IEnumerable <string> commands = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                    foreach (string command in commands)
                    {
                        if (command.Trim() != "")
                        {
                            new SqlCommand(command, conn).ExecuteNonQuery();
                        }
                    }
                    Application.DoEvents();
                    conn.Close();
                }
                //file.Delete();
            }
            catch (Exception ex)
            {
                NCLogger.GetInstance().WriteExceptionLog(ex);
                Application.DoEvents();
                conn.Close();
                return(false);
            }
            return(true);
        }
Пример #20
0
        /// <summary>
        /// 初期化
        /// </summary>
        public CmWinServiceAPI()
        {
            try
            {
                string       constr = null;
                NdnXmlConfig xmlConfig;
                string       path   = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "Config");
                string       dbpath = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "DB");
                xmlConfig = new NdnXmlConfig(Path.Combine(path, "HPSTest.Config"));

                if (!xmlConfig.ReadXmlData("database", "ConnectionString", ref constr))
                {
                    string msg = string.Format(NCMessage.GetInstance("").GetMessageById("CM0440E", ""), "サンプル間隙(秒)");
                    NCLogger.GetInstance().WriteErrorLog(msg);
                }

                Connection = new OleDbConnection(string.Format(constr, dbpath));
                Connection.Open();
            }
            catch (Exception e)
            {
                NCLogger.GetInstance().WriteExceptionLog(e);
            }
        }
Пример #21
0
        /// <summary>
        /// 媒体连接测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTest_Click(object sender, EventArgs ex)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                string mediaType   = cmbMediaType.Text;
                string mediaUrl    = txtMediaURL.Text;
                string appKey      = txtAppKey.Text;
                string appPassword = txtAppPassword.Text;
                string user        = txtUserName.Text;
                string password    = txtPassword.Text;
                string content     = txtOther.Text;
                string pic         = txtTestImage.Text;
                if (File.Exists(pic))
                {
                    switch (mediaType)
                    {
                    case "TENCENT":
                        FormQWeiboLogin LoginDlg = new FormQWeiboLogin(appKey, appPassword, user, password);
                        LoginDlg.ShowDialog();
                        if (LoginDlg.Comfirm)
                        {
                            OauthKey oauthKey = new OauthKey();
                            oauthKey.customKey    = LoginDlg.AppKey;
                            oauthKey.customSecret = LoginDlg.AppSecret;
                            oauthKey.tokenKey     = LoginDlg.AccessKey;
                            oauthKey.tokenSecret  = LoginDlg.AccessSecret;

                            ///发送带图片微博
                            t            twit = new t(oauthKey, "json");
                            UTF8Encoding utf8 = new UTF8Encoding();

                            string ret = twit.add_pic(utf8.GetString(utf8.GetBytes(content)),
                                                      utf8.GetString(utf8.GetBytes("127.0.0.1")),
                                                      utf8.GetString(utf8.GetBytes("")),
                                                      utf8.GetString(utf8.GetBytes("")),
                                                      utf8.GetString(utf8.GetBytes(pic))
                                                      );

                            string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0057I", db.Language);
                            MessageBox.Show(msg);
                        }
                        break;

                    case "WORDPRESS":
                        IMetaWeblog          metaWeblog     = (IMetaWeblog)XmlRpcProxyGen.Create(typeof(IMetaWeblog));
                        XmlRpcClientProtocol clientProtocol = (XmlRpcClientProtocol)metaWeblog;
                        clientProtocol.Url = mediaUrl;
                        string picURL   = null;
                        string filename = pic;
                        if (File.Exists(filename))
                        {
                            FileData fileData = default(FileData);
                            fileData.name = Path.GetFileName(filename);
                            fileData.type = Path.GetExtension(filename);
                            try
                            {
                                FileInfo fi = new FileInfo(filename);
                                using (BinaryReader br = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read)))
                                {
                                    fileData.bits = br.ReadBytes((int)fi.Length);
                                }
                                UrlData urlData = metaWeblog.newMediaObject("6", user, password, fileData);
                                picURL = urlData.url;
                            }
                            catch (Exception exc)
                            {
                                NCLogger.GetInstance().WriteExceptionLog(exc);
                            }
                        }

                        Post newBlogPost = default(Post);
                        newBlogPost.title         = content;
                        newBlogPost.description   = "";
                        newBlogPost.categories    = new string[1];
                        newBlogPost.categories[0] = cmbCategry.Text;
                        newBlogPost.dateCreated   = System.DateTime.Now;
                        if (picURL != null)
                        {
                            newBlogPost.description += "<br><img src='" + picURL + "'/>";
                        }

                        try
                        {
                            string result = metaWeblog.newPost("6", user,
                                                               password, newBlogPost, true);
                        }
                        catch (Exception ex2)
                        {
                            NCLogger.GetInstance().WriteExceptionLog(ex2);
                        }

                        break;

                    case "FACEBOOK":
                        var fbLoginDlg = new FormFacebookLogin(appKey, user, password);
                        fbLoginDlg.ShowDialog();
                        if (fbLoginDlg.FacebookOAuthResult != null && fbLoginDlg.FacebookOAuthResult.IsSuccess)
                        {
                            string _accessToken = fbLoginDlg.FacebookOAuthResult.AccessToken;
                            var    fb           = new FacebookClient(_accessToken);

                            // make sure to add event handler for PostCompleted.
                            fb.PostCompleted += (o, e) =>
                            {
                                // incase you support cancellation, make sure to check
                                // e.Cancelled property first even before checking (e.Error!=null).
                                if (e.Cancelled)
                                {
                                    // for this example, we can ignore as we don't allow this
                                    // example to be cancelled.

                                    // you can check e.Error for reasons behind the cancellation.
                                    var cancellationError = e.Error;
                                }
                                else if (e.Error != null)
                                {
                                    // error occurred
                                    this.BeginInvoke(new MethodInvoker(
                                                         () =>
                                    {
                                        MessageBox.Show(e.Error.Message);
                                    }));
                                }
                                else
                                {
                                    // the request was completed successfully

                                    // make sure to be on the right thread when working with ui.
                                    this.BeginInvoke(new MethodInvoker(
                                                         () =>
                                    {
                                        //MessageBox.Show("Picture uploaded successfully");

                                        Application.DoEvents();
                                    }));
                                }
                            };

                            dynamic parameters = new ExpandoObject();
                            parameters.message = content;
                            parameters.source  = new FacebookMediaObject
                            {
                                ContentType = "image/jpeg",
                                FileName    = Path.GetFileName(pic)
                            }.SetValue(File.ReadAllBytes(pic));

                            fb.PostAsync("me/photos", parameters);
                        }

                        break;

                    case "TWITTER":
                        TwitterService   service = new TwitterService(appKey, appPassword);
                        FormTwitterLogin form    = new FormTwitterLogin(db, service);
                        if (form.ShowDialog() == DialogResult.OK)
                        {
                            SendTweetWithMediaOptions sendOptions = new SendTweetWithMediaOptions();
                            sendOptions.Images = new Dictionary <string, Stream>();
                            sendOptions.Images.Add(Path.GetFileName(pic),
                                                   new FileStream(pic, FileMode.Open, FileAccess.Read));
                            if (content.Length > 70)
                            {
                                content = content.Substring(0, 70);
                            }
                            sendOptions.Status = content;

                            if (service.SendTweetWithMedia(sendOptions) != null)
                            {
                                string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0057I", db.Language);
                                MessageBox.Show(msg);
                            }
                        }
                        break;

                    case "LINKEDIN":
                        OAuth1 _OAuthLinkedin = new OAuth1(db);
                        _OAuthLinkedin.Settings_Provider              = "Linkedin";
                        _OAuthLinkedin.Settings_ConsumerKey           = appKey;
                        _OAuthLinkedin.Settings_ConsumerSecret        = appPassword;
                        _OAuthLinkedin.Settings_AccessToken_page      = "https://api.linkedin.com/uas/oauth/accessToken";
                        _OAuthLinkedin.Settings_Authorize_page        = "https://api.linkedin.com/uas/oauth/authorize";
                        _OAuthLinkedin.Settings_RequestToken_page     = "https://api.linkedin.com/uas/oauth/requestToken";
                        _OAuthLinkedin.Settings_Redirect_URL          = "http://www.chojo.co.jp/";
                        _OAuthLinkedin.Settings_User_agent            = "CJW";
                        _OAuthLinkedin.Settings_OAuth_Realm_page      = "https://api.linkedin.com/";
                        _OAuthLinkedin.Settings_GetProfile_API_page   = "https://api.linkedin.com/v1/people/~/";
                        _OAuthLinkedin.Settings_StatusUpdate_API_page = "https://api.linkedin.com/v1/people/~/current-status";
                        _OAuthLinkedin.getRequestToken();
                        _OAuthLinkedin.authorizeToken();
                        String accessToken = _OAuthLinkedin.getAccessToken();
                        try
                        {
                            string ret = _OAuthLinkedin.APIWebRequest("POST", _OAuthLinkedin.Settings_StatusUpdate_API_page, pic);
                            string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
                            xml += "<current-status>" + txtOther.Text + "<img src =" + ret + "/>" + "</current-status>";
                            _OAuthLinkedin.APIWebRequest("PUT", _OAuthLinkedin.Settings_StatusUpdate_API_page, xml);
                        }
                        catch (Exception exp)
                        {
                            MessageBox.Show(exp.Message);
                        }

                        break;

                    case "MSN":
                    case "GOOGLE":
                    case "YAHOO":
                        PROVIDER_TYPE provider_type = (PROVIDER_TYPE)Enum.Parse(typeof(PROVIDER_TYPE), mediaType);
                        setConfigure(user, password, mediaType);
                        FormAuthSocialLogin loginForm = new FormAuthSocialLogin(db, provider_type, socialAuthManager);
                        if (loginForm.ShowDialog() == DialogResult.OK)
                        {
                            string msgs     = HttpUtility.UrlEncode(content);
                            string endpoint = mediaUrl + msgs;

                            string body = String.Empty;
                            //byte[] reqbytes = new ASCIIEncoding().GetBytes(body);
                            byte[] reqbytes = File.ReadAllBytes(pic);
                            Dictionary <string, string> headers = new Dictionary <string, string>();
                            //headers.Add("contentType", "application/x-www-form-urlencoded");
                            headers.Add("contentType", "image/jpeg");
                            headers.Add("FileName", Path.GetFileName(pic));
                            var response = socialAuthManager.ExecuteFeed(
                                endpoint,
                                TRANSPORT_METHOD.POST,
                                provider_type,
                                reqbytes,
                                headers
                                );
                        }
                        break;
                    }
                }
                else
                {
                    string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0058I", db.Language);
                    MessageBox.Show(msg);
                }
            }
            else
            {
                string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0050I", db.Language);
                MessageBox.Show(msg);
            }
        }
        /// <summary>
        /// Post
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bntPost_Click(object sender, EventArgs args)
        {
            if (lstCategory.SelectedItems.Count < 1)
            {
                MessageBox.Show("Please select a category!");
                return;
            }
            pgbPost.Value   = 0;
            pgbPost.Maximum = ds_media.Tables[0].Rows.Count;
            for (int idx = 0; idx < ds_media.Tables[0].Rows.Count; idx++)
            {
                String mediaPublishId = ds_media.Tables[0].Rows[idx]["发布编号"].ToString();
                setMediaPublishStatus(mediaPublishId, "发行中");
                IMetaWeblog          metaWeblog     = (IMetaWeblog)XmlRpcProxyGen.Create(typeof(IMetaWeblog));
                XmlRpcClientProtocol clientProtocol = (XmlRpcClientProtocol)metaWeblog;
                clientProtocol.Url = ds_media.Tables[0].Rows[idx]["MediaURL"].ToString();
                string userName = ds_media.Tables[0].Rows[idx]["MediaUser"].ToString();
                string password = ds_media.Tables[0].Rows[idx]["MediaPassword"].ToString();
                string picURL   = null;
                string filename = ds_media.Tables[0].Rows[idx]["本地图片"].ToString();
                if (File.Exists(filename))
                {
                    FileData fileData = default(FileData);
                    fileData.name = Path.GetFileName(filename);
                    fileData.type = Path.GetExtension(filename);
                    try
                    {
                        FileInfo fi = new FileInfo(filename);
                        using (BinaryReader br = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read)))
                        {
                            fileData.bits = br.ReadBytes((int)fi.Length);
                        }
                        UrlData urlData = metaWeblog.newMediaObject("1", userName, password, fileData);
                        picURL = urlData.url;
                    }
                    catch (Exception ex)
                    {
                        NCLogger.GetInstance().WriteExceptionLog(ex);
                    }
                }

                Post newBlogPost = default(Post);
                newBlogPost.title = ds_media.Tables[0].Rows[idx]["名称"].ToString()
                                    + ds_media.Tables[0].Rows[idx]["发行期号"].ToString()
                                    + "[" + ds_media.Tables[0].Rows[idx]["发行日期"].ToString() + "]";
                newBlogPost.description = ds_media.Tables[0].Rows[idx]["文本内容"].ToString();
                if (picURL != null)
                {
                    newBlogPost.description += "<br><img src='" + picURL + "'/>";
                }
                string[] cats = new string[lstCategory.SelectedItems.Count];
                lstCategory.SelectedItems.CopyTo(cats, 0);
                newBlogPost.categories  = cats;
                newBlogPost.dateCreated = System.DateTime.Now;

                try
                {
                    string result = metaWeblog.newPost("1", userName,
                                                       password, newBlogPost, true);
                    //MessageBox.Show("Post Successful!Post ID:" + result);
                    setMediaPublishStatus(mediaPublishId, "发行完");
                }
                catch (Exception ex)
                {
                    setMediaPublishStatus(mediaPublishId, "未发行");
                    NCLogger.GetInstance().WriteExceptionLog(ex);
                }
            }
        }