public override bool Action(string action)
        {
            bool result = base.Action(action);
            if (result && action == ACTION_IMPORT)
            {
                try
                {
                    using (var client = new Utils.API.GeocachingLiveV6(Core))
                    using (var wc = new System.Net.WebClient())
                    {
                        var resp = client.Client.GetGeocacheDataTypes(client.Token, true, true, true);
                        if (resp.Status.StatusCode == 0)
                        {
                            string defaultPath = Path.Combine(new string[] { _basePath, "Default", "attributes" });
                            if (!Directory.Exists(defaultPath))
                            {
                                Directory.CreateDirectory(defaultPath);
                            }
                            foreach (var attr in resp.AttributeTypes)
                            {
                                wc.DownloadFile(attr.YesIconName, Path.Combine(defaultPath, string.Format("{0}.gif", attr.ID)));
                                wc.DownloadFile(attr.NoIconName, Path.Combine(defaultPath, string.Format("_{0}.gif", attr.ID)));
                            }

                            defaultPath = Path.Combine(new string[] { _basePath, "Default", "cachetypes" });
                            if (!Directory.Exists(defaultPath))
                            {
                                Directory.CreateDirectory(defaultPath);
                            }

                            string smallPath = Path.Combine(new string[] { _basePath, "Small", "cachetypes" });
                            if (!Directory.Exists(smallPath))
                            {
                                Directory.CreateDirectory(smallPath);
                            }
                            foreach (var gt in resp.GeocacheTypes)
                            {
                                string fn = string.Format("{0}.gif", gt.GeocacheTypeId);
                                wc.DownloadFile(gt.ImageURL, Path.Combine(defaultPath, fn));
                            }

                            defaultPath = Path.Combine(new string[] { _basePath, "Default", "logtypes" });
                            if (!Directory.Exists(defaultPath))
                            {
                                Directory.CreateDirectory(defaultPath);
                            }
                            foreach (var gt in resp.WptLogTypes)
                            {
                                wc.DownloadFile(gt.ImageURL, Path.Combine(defaultPath, string.Format("{0}.gif", gt.WptLogTypeId)));
                            }
                        }
                    }
                }
                catch
                {
                }
            }
            return result;
        }
Exemple #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string siteid = Request["siteid"];
            string filename = Request["filename"];

            DataSet dsSite = DbHelper.GetSiteData(siteid, "");
            string tmpFolder = Server.MapPath("./") + "TempOutput" + "/" + Page.User.Identity.Name + "/";

            if (Directory.Exists(tmpFolder))
            {
                string[] files = Directory.GetFiles(tmpFolder);
                foreach (string file in files)
                    File.Delete(file);
            }
            else
            {
                Directory.CreateDirectory(tmpFolder);
            }

            foreach (DataRow drSite in dsSite.Tables[0].Rows)
            {
                string siteUrl = drSite["ZipApiUrl"].ToString() + "getfile.php?filename=" + filename;
                System.Net.WebClient client = new System.Net.WebClient();
                client.DownloadFile(siteUrl, tmpFolder + filename);

                Func.SaveLocalFile(tmpFolder + filename, "zip", "Mone\\CSV出力");
            }
        }
Exemple #3
0
 public virtual void Form1_DragDrop(object sender, DragEventArgs e)
 {
     if (_isUrl)
     {
         string url = e.Data.GetData("Text") as string;
         if (string.IsNullOrEmpty(url) || !IsImage(url))
         {
             return;
         }
         using (System.Net.WebClient wc = new System.Net.WebClient())
         {
             _currentUri = url;
             _currentFile = "Browser";
             try
             {
                 wc.DownloadFile(url, _currentFile);
             }
             catch
             {
                 MessageBox.Show("画像のダウンロードに失敗しました", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }
     }
     else
     {
         string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
         if (!File.Exists(files[0]) || !IsImage(files[0]))
         {
             return;
         }
         _currentFile = files[0];
         _currentUri = _currentFile;
     }
     FindImage(_currentFile);
 }
Exemple #4
0
 public static bool UpdateFileCached(string remoteUrl, string localUrl, int thresholdInHours = -1)
 {
     bool returnValue = false;
     DateTime threshold;
     if (thresholdInHours > -1)
     {
         threshold = DateTime.Now.AddHours(-thresholdInHours);
     }
     else
     {
         threshold = DateTime.MinValue;
     }
     try
     {
         if (!File.Exists(localUrl) || File.GetLastWriteTime(localUrl) < threshold)
         {
             Console.WriteLine("we need to re-download " + localUrl);
             using (System.Net.WebClient webClient = new System.Net.WebClient())
             {
                 webClient.DownloadFile(remoteUrl, localUrl);
                 returnValue = true;
             }
         }
         else
         {
             returnValue = true;
         }
     }
     catch(Exception e)
     {
         Debug.WriteLine(e);
         returnValue = false;
     }
     return returnValue;
 }
Exemple #5
0
        public List<Episode> GetAllEpisodes(int seriesId)
        {
            String zipPath = System.IO.Path.GetTempPath() + "en.zip";
            String unzipPath = System.IO.Path.GetTempPath() + "seriestracker unzip";
            String xmlPath = unzipPath + System.IO.Path.DirectorySeparatorChar + "en.xml";
            System.Net.WebClient client = new System.Net.WebClient();
            client.DownloadFile(GetZipUrl(seriesId), zipPath);
            using (ZipFile zip = ZipFile.Read(zipPath))
            {
                foreach (ZipEntry e in zip)
                {
                    e.Extract(unzipPath, ExtractExistingFileAction.OverwriteSilently);
                }
            }
            XDocument doc = XDocument.Load(xmlPath);
            var episodes = from episode in doc.Descendants("Episode")
                            where episode.Element("EpisodeName") != null && episode.Element("id") != null &&
                                  episode.Element("SeasonNumber") != null && episode.Element("EpisodeNumber") != null
                            select new Episode
                            {
                                Name = episode.Element("EpisodeName").Value,
                                Overview = episode.Element("Overview") != null ? episode.Element("Overview").Value : "",
                                Id = Convert.ToInt32(episode.Element("id").Value),
                                SeasonNumber = Convert.ToInt32(episode.Element("SeasonNumber").Value),
                                EpisodeNumber = Convert.ToInt32(episode.Element("EpisodeNumber").Value),
                                SeriesId = Convert.ToInt32(episode.Element("seriesid").Value),
                                FirstAired = Episode.DateToTimestamp(episode.Element("FirstAired").Value)
                            };

            return episodes.ToList();
        }
Exemple #6
0
 public int Run(Cli console,string[] args)
 {
     string source = null;
     string local  = null;
     Options opts = new Options("Downloads a specified file")
     {
         new Option((string s)=>source =s,"address","The source address of the file to be downloaded"),
         new Option((string l)=>local =l,"localFile","Save the remote file as this name"),
     };
     opts.Parse(args);
     if(source == null)
     {
         return 1;
     }
     using(var client = new System.Net.WebClient())
     {
         if(local !=null)
         {
             client.DownloadFile(new Uri(source),local);
         }
         else
         {
             var result = client.DownloadString(new Uri(source));
             console.Out.WriteLine(result);
         }
     }
     return 0;
 }
Exemple #7
0
 private void installGame()
 {
     //download and unpack game   
     try
     {
         String filename = installerExe.Substring(0, installerExe.Length - 4);
         if (!System.IO.Directory.Exists(getDosBoxPath() + "\\" + filename))
         {
             System.Net.WebClient webc = new System.Net.WebClient();
             webc.DownloadFile(new Uri("https://gamestream.ml/games/" + installerExe), getDosBoxPath() + installerExe);
             Process process1 = Process.Start(getDosBoxPath() + installerExe);
             process1.WaitForExit();
             startDosBox();
         }
         else
         {
             startDosBox();
         }
     }
     catch (Exception e) {
         MessageBox.Show(e.Message);
         Application.ExitThread();
         Application.Exit();
     }
 }
 public static System.Drawing.Image Webimage(this string s)
 {
     var wc = new System.Net.WebClient { Proxy = null };
     var filesavepath = System.Windows.Forms.Application.StartupPath + "\\" + System.Guid.NewGuid();
     wc.DownloadFile(s, filesavepath);
     return System.Drawing.Image.FromFile(filesavepath);
 }
        public CurrentWeather(string fetched, JObject json)
        {
            Fetched = fetched;
            Json = json;

            if (Json["current_observation"]["temp_f"] != null)
            {

                CurrentTempF = (double)Json["current_observation"]["temp_f"];
                FeelsLikeF = (double)Json["current_observation"]["feelslike_f"];
                CurrentTempC = (double)Json["current_observation"]["temp_c"];
                FeelsLikeC = (double)Json["current_observation"]["feelslike_c"];
                CityName = (string)Json["current_observation"]["display_location"]["full"];
                WindFeel = (string)Json["current_observation"]["wind_string"];
                WindSpeedMph = (double)Json["current_observation"]["wind_mph"];
                DewPointF = (double)Json["current_observation"]["dewpoint_f"];
                ForecastURL = (string)Json["current_observation"]["forecast_url"];
                VisibilityMi = (double)Json["current_observation"]["visibility_mi"];
                Weather = (string)Json["current_observation"]["weather"];
                Elevation = (string)Json["current_observation"]["observation_location"]["elevation"];

                ImageName = (string)Json["current_observation"]["icon"];
                ImageUrl = (string)Json["current_observation"]["icon_url"];

                string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                LocalUrl = System.IO.Path.Combine(folder, System.IO.Path.GetRandomFileName());
                System.Net.WebClient webClient = new System.Net.WebClient();
                webClient.DownloadFile(ImageUrl, LocalUrl);
            }
        }
Exemple #10
0
        protected override void ImportMethod()
        {
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORT, STR_DOWNLOAD, 1, 0))
            {
                using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                using (System.Net.WebClient wc = new System.Net.WebClient())
                {
                    wc.DownloadFile("http://www.globalcaching.eu/service/cachedistance.aspx?country=Netherlands&prefix=GC", tmp.Path);

                    using (var fs = System.IO.File.OpenRead(tmp.Path))
                    using (ZipInputStream s = new ZipInputStream(fs))
                    {
                        ZipEntry theEntry = s.GetNextEntry();
                        byte[] data = new byte[1024];
                        if (theEntry != null)
                        {
                            StringBuilder sb = new StringBuilder();
                            while (true)
                            {
                                int size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    if (sb.Length == 0 && data[0] == 0xEF && size > 2)
                                    {
                                        sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 3, size - 3));
                                    }
                                    else
                                    {
                                        sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 0, size));
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }

                            XmlDocument doc = new XmlDocument();
                            doc.LoadXml(sb.ToString());
                            XmlElement root = doc.DocumentElement;
                            XmlNodeList nl = root.SelectNodes("wp");
                            if (nl != null)
                            {
                                Core.Geocaches.AddCustomAttribute(CUSTOM_ATTRIBUTE);
                                foreach (XmlNode n in nl)
                                {
                                    var gc = Utils.DataAccess.GetGeocache(Core.Geocaches, n.Attributes["code"].InnerText);
                                    if (gc != null)
                                    {
                                        string dist = Utils.Conversion.StringToDouble(n.Attributes["dist"].InnerText).ToString("000.0");
                                        gc.SetCustomAttribute(CUSTOM_ATTRIBUTE, dist);
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
Exemple #11
0
        static void Main(string[] args)
        {
            string s = @"http://192.168.3.12:8080/imc/nti/imcExport_exportPDF.action?a=1";
            System.Net.WebClient wc = new System.Net.WebClient();
            wc.DownloadFile(s, "aa.pdf");

            Console.ReadLine();
        }
 public static void InstallNugetExe(string nugetExePath)
 {
     if (!File.Exists(nugetExePath))
     {
         var directory = Path.GetDirectoryName(nugetExePath);
         Directory.CreateDirectory(directory);
         var client = new System.Net.WebClient();
         client.DownloadFile("http://nuget.org/nuget.exe", nugetExePath);
     }
 }
Exemple #13
0
		public void DownloadXML(System.String XmlURL)
		{
			System.String TempFile = PathSettings.TempPath + "TheLastRipperData.xml";
			if (System.IO.File.Exists(TempFile))
			{
				System.IO.File.Delete(TempFile);
			}
			System.Net.WebClient Client = new System.Net.WebClient();
			Client.DownloadFile(XmlURL, TempFile);
			this.FetchXML(TempFile);
		}
Exemple #14
0
        /// <summary>
        /// WebPath -> Image
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
		public static System.Drawing.Image Webimage(this string s)
        {
            #region WebPath -> Image
            var wc = new System.Net.WebClient { Proxy = null };
            var filesavepath = System.Windows.Forms.Application.StartupPath + "\\" + System.Guid.NewGuid().ToString().Replace("-","");
            wc.DownloadFile(s, filesavepath);
            var img = System.Drawing.Image.FromFile(filesavepath);
            var bmp = new System.Drawing.Bitmap(img);
            filesavepath.ToDeleteFile();
            return bmp; 
            #endregion
        }
Exemple #15
0
        static void Main(string[] args)
        {
            DBUtil.Connect();

            Logger.Instance.Debug("aa");

            // YPからチャンネル情報を取得
            List<ChannelDetail> channelDetails = GetChannelDetails();

            // 配信者マスターの更新
            UpdateChannel(channelDetails);

            // スレッド情報の更新
            UpdateBBSThread(channelDetails);

            // レス情報の更新
            UpdateBBSResponse();

            /*
            List<string> imgList = new List<string>();
            // レス一覧の取得
            List<BBSResponse> resList = BBSResponseDao.Select();
            foreach (BBSResponse res in resList)
            {
                Match match = Regex.Match(res.Message, @"ttp://.*\.(jpg|JPG|jpeg|JPEG|bmp|BMP|png|PNG)");

                if (match.Success)
                {
                    string imageUrl = "h" + match.Value;
                    imgList.Add(imageUrl);
                    ImageLinkDao.Insert(res.ThreadUrl, res.ResNo, imageUrl, res.WriteTime);
                }
            }
             */

            List<ImageLink> imageList = ImageLinkDao.Select();

            foreach (ImageLink link in imageList)
            {
                try
                {
                    System.Net.WebClient wc = new System.Net.WebClient();
                    wc.DownloadFile(link.ImageUrl, @"S:\MyDocument_201503\dev\github\PecaTsu_BBS\src_BBS\img\" + (link.WriteTime.Replace("/", "").Replace(":", "")) + ".jpg");
                    wc.Dispose();
                }
                catch (Exception)
                {
                }
            }

            DBUtil.Close();
        }
Exemple #16
0
 /// <summary>
 /// Download File From Internet
 /// </summary>
 /// <param name="fileAddress">URL : http://nus.vn/logo-nus.jpg </param>
 /// <param name="savePath">Physical path contain this file : ~\Download\logo-nus.jpg</param>
 /// <returns></returns>
 public static bool DownLoadFileFromInternet(string fileAddress, string savePath)
 {
     try
     {
         System.Net.WebClient webClient = new System.Net.WebClient();
         webClient.DownloadFile(new Uri(fileAddress, UriKind.Absolute), savePath);
     }
     catch
     {
         return false;
     }
     return true;
 }
Exemple #17
0
 public void Download()
 {
     if (File.Exists(Filename)) {
         return;
     } else {
         using (System.Net.WebClient client = new System.Net.WebClient()) {
             Console.WriteLine("Downloading " + Filename);
             string targetDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\Downloads\Audios\";
             Directory.CreateDirectory(targetDir);
             client.DownloadFile(File_url, targetDir + Filename);
         }
     }
 }
        public void DownloadFile(string iPath, string iFileName, string iDestinationPath)
        {
            string myStringWebResource = null;

            // Create a new WebClient instance.
            using (System.Net.WebClient myWebClient = new System.Net.WebClient())
            {
                myStringWebResource = iPath + iFileName;
                // Download the Web resource and save it into the current filesystem folder.

                myWebClient.DownloadFile(myStringWebResource, iDestinationPath + DateTime.Now.Year + "_" + DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + iFileName);
            }
        }
    private static void Go(DateTime date_)
    {
      while (date_.DayOfWeek != DayOfWeek.Sunday)
        date_ = date_.AddDays(-1d);     System.Net.WebClient client = new System.Net.WebClient();

      string netAddress = string.Format("http://www.dailyfx.com/files/Calendar-{0}.csv", date_.ToString("MM-dd-yyyy"));
      string localAddress = string.Format(@"{1}\technology\calendars\{0}.csv", date_.ToString("dd-MMM-yyyy"), DIRECTORIES.S_DRIVE);

      try
      {
        client.DownloadFile(netAddress, localAddress);
      }
      catch { }
    }
Exemple #20
0
 public static void downloadFile(string url, string sourcefile, string user, string pwd)
 {
     try
     {
         System.Net.WebClient Client = new System.Net.WebClient();
         Client.Credentials = new System.Net.NetworkCredential(user, pwd);
         Client.DownloadFile(url, sourcefile);
         Client.Dispose();
     }
     catch (Exception e)
     {
         throw (e);
     }
 }
 /// <summary>
 /// Download the jar file for this Maven package.
 /// </summary>
 /// <param name="folder">Folder to download the file into.</param>
 public void Fetch(String folder)
 {
     if (!Directory.Exists(folder))
     {
         Directory.CreateDirectory(folder);
     }
     String destination = Path.Combine(folder, FileName);
     if (!File.Exists(destination))
     {
         var client = new System.Net.WebClient();
         Console.Error.WriteLine(Url + " --> " + destination);
         client.DownloadFile(new Uri(Url), destination);
     }
 }
Exemple #22
0
        public void Run()
        {
            System.ComponentModel.BackgroundWorker bw = new System.ComponentModel.BackgroundWorker();
            bw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerAsync();

            try
            {
                System.Net.WebClient myClient = new System.Net.WebClient();

                myClient.DownloadFile(update_location + updated_file, local_updated_file);
                myClient.DownloadFile(update_location + updater, updater);

                System.IO.FileInfo exe = new System.IO.FileInfo(System.Windows.Forms.Application.ExecutablePath);
                String param = "\"" + exe.Name + "\" " + "\"" + local_updated_file + "\"";
                System.Diagnostics.Process.Start(updater, param);
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message);
            }

            bw.CancelAsync();
        }
Exemple #23
0
        public static void installPython()
        {
            //Make a filename to download python to
            String filename = System.IO.Path.GetTempPath() + Char.ToString(System.IO.Path.DirectorySeparatorChar) + "python-2.7.1.msi";

            System.Net.WebClient web = new System.Net.WebClient();
            Console.WriteLine ("Downloading python 2.7");
            web.DownloadFile("http://www.python.org/ftp/python/2.7.1/python-2.7.1.msi",filename);
            Console.WriteLine ("python2.7 downloaded to " + filename);

            Console.WriteLine ("Installing python");
            //filename must be qouted or else msiexec will fail
            exec("msiexec","/qn","/i","\"" +filename + "\"");
            Console.WriteLine ("Python is now installed");
        }
Exemple #24
0
        private void installDosBox()
        {
            //download and install dosbox
            try {
                System.Net.WebClient webc = new System.Net.WebClient();
                webc.DownloadFile("https://gamestream.ml/dosbox_inst.exe", "dosbox_inst.exe");

                Process process = Process.Start("dosbox_inst.exe");
                process.WaitForExit();
            }catch(Exception e) {
                MessageBox.Show(e.Message);
                Application.ExitThread();
                Application.Exit();
            }
        }
Exemple #25
0
        public void CopyFile(string VIFormNumber,int RFQID)
        {
            string strconn = System.Configuration.ConfigurationManager.AppSettings["ConnVIDB"];
            string VIHost = System.Configuration.ConfigurationManager.AppSettings["VIHost"];
            string ServerPath = System.Configuration.ConfigurationManager.AppSettings["FilesFolder"]+"\\"+RFQID.ToString();
            DirectoryInfo di = new DirectoryInfo(ServerPath);

            if (!di.Exists)
            {

                di.Create();
            }

            System.Net.WebClient webclient = new System.Net.WebClient();
            SqlConnection conn=new SqlConnection(strconn);
            string strsql = "select * from [tVI_attachment] where rfq=@VIFormNumber";
             DataTable dt = SqlText.ExecuteDataset(conn, null, strsql, null, new SqlParameter("@VIFormNumber", VIFormNumber)).Tables[0];
             string strSgpFile = "select * from SGP_Files where RelationKey=@RelationKey and [status]=1";
            DataTable targetdt = DbHelperSQL.Query(strSgpFile, new SqlParameter("@RelationKey", RFQID.ToString())).Tables[0];

             if (dt.Rows.Count > 0)
             {

                 foreach (DataRow dr in dt.Rows)
                 {
                     string sourcefile = VIHost + dr["folder"].ToString() +"\\"+dr["filename"].ToString();
                     string stuffix = dr["filename"].ToString().Substring(dr["filename"].ToString().LastIndexOf('.'), dr["filename"].ToString().Length - dr["filename"].ToString().LastIndexOf('.'));
                     string filename = System.Guid.NewGuid().ToString();
                     string sourcename = dr["filename"].ToString();
                     string targetfile = ServerPath + "\\" +filename + stuffix;
                     webclient.DownloadFile(sourcefile,targetfile);
                     string filesize = GetAutoSizeString(new FileInfo(targetfile).Length, 2);
                     DataRow[] drs = targetdt.Select("SourceName='" + sourcename + "' and RelationKey='"+RFQID.ToString()+"'");
                     if (drs.Length>0)
                     {
                         strsql = "update SGP_Files set [status]=9 where SourceName=@SourceName and RelationKey=@RelationKey";
                         List<SqlParameter> spa = new List<SqlParameter>() { new SqlParameter("@SourceName", sourcename), new SqlParameter("@RelationKey", RFQID.ToString()) };
                         DbHelperSQL.ExecuteSql(strsql,spa.ToArray());
                     }
                     strsql = string.Format("insert into SGP_Files select '{0}','{1}','{2}','{3}','{4}',Null,Null,getdate(),'{5}',1",RFQID,filename+stuffix,dr["filename"].ToString(),RFQID,filesize
                         ,"VI System");
                     DbHelperSQL.ExecuteSql(strsql);

                     webclient.Dispose();
                 }

             }
        }
Exemple #26
0
        /// <summary>
        ///Web Client Method ,only For Small picture,else large please use FTP
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="url"></param>
        /// <param name="localPath"></param>
        public static bool DownloadOneFileByURLWithWebClient(string fileName, string url, string localPath)
        {
            try
             {
                 System.Net.WebClient wc = new System.Net.WebClient();
                 if (File.Exists(localPath + fileName)) { File.Delete(localPath + fileName); }
                 if (Directory.Exists(localPath) == false) { Directory.CreateDirectory(localPath); }
                 wc.DownloadFile(url, localPath + fileName);
                 return true;
             }
             catch (Exception ex)
             {
                 return false;

             }
        }
Exemple #27
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage :  ");
                Console.WriteLine("cssd http://example.com/styles.css");
                return;
            }
            // No options. Just URL of the css.
            string cssFile = args[0];

            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                Uri furi = new Uri(cssFile);
                string content = wc.DownloadString(furi);
                Console.WriteLine("File downloaded.. Looking for url() references to download.");
                DirectoryInfo di = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, furi.Segments[furi.Segments.Length - 1]));
                UriBuilder ub = new UriBuilder();
                ub.Host = furi.Host;
                ub.Scheme = furi.Scheme;
                System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex("url(\\((.*?)\\))");
                MatchCollection matches = rg.Matches(content);
                int i = 0;
                foreach (Match item in matches)
                {
                    string url = item.Groups[2].Value;
                    ub.Path = url;
                    wc.DownloadFile(ub.Uri, System.IO.Path.Combine(di.FullName, ub.Uri.Segments[ub.Uri.Segments.Length - 1]));
                    content = content.Replace(url, ub.Uri.Segments[ub.Uri.Segments.Length - 1]);
                    DrawProgressBar(i, matches.Count, 40, '=');
                    i++;
                }
                wc.Dispose();

                DrawProgressBar(matches.Count, matches.Count, 40, '=');
                Console.WriteLine("");
                Console.WriteLine("Complete!");
                System.Threading.Thread.Sleep(300);
                System.IO.File.WriteAllText(System.IO.Path.Combine(di.FullName, furi.Segments[furi.Segments.Length - 1]), content);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.ToString());
            }
        }
Exemple #28
0
        /// <summary>
        /// Download a public file from a URL
        /// </summary>
        /// <param name="httpPath"></param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public static bool DownloadHTTPFile(string httpPath, string savePath)
        {
            try
            {
                System.Net.WebClient Client = new System.Net.WebClient();
                Client.DownloadFile(httpPath, savePath);
                if (FileExists(savePath))
                    return true;
                else
                    return false;
            }

            catch (Exception ex)
            {
                sendLogEvent(ex.Message,"General",Enums.MessageType.Error);
                return false;
            }
        }
Exemple #29
0
        public static void GetImage(string value, string destinationFileName)
        {
            value = value.Replace('\\', '/').Trim();
            value = value.Replace("''", string.Empty);

            destinationFileName = destinationFileName.Replace('/', '\\').Trim();
            System.Net.WebClient wc = new System.Net.WebClient();

            try
            {
                byte[] imageDate = wc.DownloadData(value);
                if (imageDate != null && imageDate.Length > 0)
                    wc.DownloadFile(value, destinationFileName);
            }
            catch (Exception)
            {
            }
        }
 public static void RunUpdate()
 {
     //WebClient to get the new .exe
     System.Net.WebClient wc = new System.Net.WebClient();
     string appfile = "";
     string appfolder = AppDomain.CurrentDomain.BaseDirectory;
     foreach (string fil in System.IO.Directory.GetFiles(appfolder)) {
         System.IO.FileInfo filinf = new System.IO.FileInfo (fil);
         if (filinf.Extension == ".exe") {
             appfile = filinf.FullName;
             break;
         }
     }
     if (appfile != "") {
         wc.DownloadFile (NewDL, appfile);
         System.Diagnostics.Process.Start (appfile);
         Gtk.Application.Quit ();
     }
 }
Exemple #31
0
        private void Form1_Load(object sender, EventArgs e)
        {
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(AppClosing);
            if (File.Exists(Application.StartupPath + "\\" + "log.txt"))
            {
                File.Delete(Application.StartupPath + "\\" + "log.txt");
            }
            if (File.Exists(Application.StartupPath + "\\" + "exitlog.txt"))
            {
                File.Delete(Application.StartupPath + "\\" + "exitlog.txt");
            }
            if (File.Exists(Application.StartupPath + "\\" + "startuplist.txt"))
            {
                Char         splitter1 = '*';
                StreamReader ReadStartup;
                ReadStartup = new StreamReader(Application.StartupPath + "\\" + "startuplist.txt");
                String StartupText;
                StartupText       = ReadStartup.ReadToEnd();
                StartupImagesText = StartupText;
                ReadStartup.Close();
                StartupImages = StartupText.Split(splitter1);
                for (int count = 0; count < StartupImages.Length; count++)
                {
                    dataGridView2.Rows.Add(StartupImages[count]);
                }
            }
            richTextBox1.AppendText("------------Free Image Mounter------------");
            Logs = new StringBuilder();
            Logs.Append("------------Free Image Mounter------------");
            if (File.Exists(Application.StartupPath + "\\" + "version.txt"))
            {
                if (File.Exists(Application.StartupPath + "\\" + "config.ini"))
                {
                    richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       config.ini is present");
                    Logs.Append(Environment.NewLine + DateTime.Now + "       config.ini is present");
                    StreamReader ReadConfig;
                    ReadConfig = new StreamReader(Application.StartupPath + "\\" + "config.ini");
                    String FullConfig;
                    FullConfig = ReadConfig.ReadToEnd();
                    ReadConfig.Close();
                    Char Seperation = '&';
                    split1 = FullConfig.Split(Seperation);
                    Char Seperation2 = ':';
                    //String[] split2;
                    split2 = split1[0].Split(Seperation2);
                    if (split2[0].Contains("True"))
                    {
                        RunOnStartup = "TRUE";
                        button4.Text = "Dont run at startup";
                    }
                    if (split2[0].Contains("False"))
                    {
                        RunOnStartup = "FALSE";
                        button4.Text = "Run at startup";
                    }
                }
                else
                {
                    richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Error: cannot find config.ini");
                    Logs.Append(Environment.NewLine + DateTime.Now + "       Error: cannot find config.ini");
                }
                richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       version.txt is present");
                Logs.Append(Environment.NewLine + DateTime.Now + "       version.txt is present");
                StreamReader CheckVersion;
                CheckVersion = new StreamReader(Application.StartupPath + "\\" + "version.txt");
                String FullFile = CheckVersion.ReadToEnd();
                CheckVersion.Close();
                richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Successfully read version.txt");
                Logs.Append(Environment.NewLine + DateTime.Now + "       Successfully read version.txt");
                String[] output1;
                Char     Splitter = ':';
                output1        = FullFile.Split(Splitter);
                CurrentVersion = output1[0];
                CurrentVDate   = output1[1];
                AutoUpdate     = output1[2];
                LogStatus      = output1[3];
                if (LogStatus.Contains("true"))
                {
                    label5.Text = "Logging is currently enabled. The tickbox is to change logging status, regardless of whether it is ticked or not";
                    richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Starting to write to log file");
                    Logs.Append(Environment.NewLine + DateTime.Now + "       Starting to write to log file");
                    timer1.Start();
                }
                else
                {
                    label5.Text = "Logging is currently disabled. The tickbox is to change logging status, regardless of whether it is ticked or not";
                }
                AutoUpdate.TrimEnd('\r', '\n');
                richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Free Image Mounter v" + CurrentVersion + ", from " + CurrentVDate);
                Logs.Append(Environment.NewLine + DateTime.Now + "       Free Image Mounter v" + CurrentVersion + ", from " + CurrentVDate);
                //MessageBox.Show(AutoUpdate);
                if (AutoUpdate.Contains("true"))
                {
                    richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Autoupdates enabled");
                    Logs.Append(Environment.NewLine + DateTime.Now + "       Autoupdates enabled");
                    if (File.Exists(Application.StartupPath + "\\" + "latestversion.txt"))
                    {
                        richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Found obsolete latestversion.txt");
                        Logs.Append(Environment.NewLine + DateTime.Now + "       Found obsolete latestversion.txt");
                        File.Delete(Application.StartupPath + "\\" + "latestversion.txt");
                        richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Deleted old latestversion.txt");
                        Logs.Append(Environment.NewLine + DateTime.Now + "       Deleted old latestversion.txt");
                    }
                    //  MessageBox.Show("updatesection");
                    System.Net.NetworkInformation.Ping TestServer = new System.Net.NetworkInformation.Ping();
                    if (TestServer.Send("89.203.4.93", 300).Status == System.Net.NetworkInformation.IPStatus.Success)
                    {
                        richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Can successfully ping update server");
                        Logs.Append(Environment.NewLine + DateTime.Now + "       Can successfully ping update server");
                        //    MessageBox.Show("works");
                        System.Net.WebClient GetLatestInfo = new System.Net.WebClient();
                        richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Trying to download update config file");
                        Logs.Append(Environment.NewLine + DateTime.Now + "       Trying to download update config file");
                        GetLatestInfo.DownloadFile("ftp://89.203.4.93:2048/downloads/isomount/latestversion.txt", "latestversion.txt");
                        if (File.Exists(Application.StartupPath + "\\" + "latestversion.txt"))
                        {
                            richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Successfully downloaded update config files");
                            Logs.Append(Environment.NewLine + DateTime.Now + "       Successfully downloaded update config files");
                        }
                        else
                        {
                            richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Error in downloading update files, skipping autoupdate");
                            Logs.Append(Environment.NewLine + DateTime.Now + "       Error in downloading update files, skipping autoupdate");
                            goto EndCheckUpdate;
                        }
                        CheckVersion = new StreamReader(Application.StartupPath + "\\" + "latestversion.txt");
                        String LatestFile = CheckVersion.ReadToEnd();
                        CheckVersion.Close();
                        output1 = LatestFile.Split(Splitter);
                        String LatestVersion = output1[0];
                        if (LatestVersion == CurrentVersion)
                        {
                            richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Current version is already up to date");
                            Logs.Append(Environment.NewLine + DateTime.Now + "       Current version is already up to date");
                        }
                        else
                        {
                            richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       New version found");
                            Logs.Append(Environment.NewLine + DateTime.Now + "       New version found");
                            DialogResult UpdateResponse = MessageBox.Show("New version, " + output1[0] + ", from " + output1[1] + " found. Update?", "Update available", MessageBoxButtons.YesNoCancel);
                            if (UpdateResponse == DialogResult.Yes)
                            {
                                richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Starting download app");
                                Logs.Append(Environment.NewLine + DateTime.Now + "       Starting download app");
                                richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Update logs are found in update.txt, if enabled");
                                Logs.Append(Environment.NewLine + DateTime.Now + "       Update logs are found in update.txt, if enabled");
                                Form2 downloadform = new Form2();
                                downloadform.UpdateProgram();
                                downloadform.ShowDialog();
                            }
                        }
                    }
                    else
                    {
                        richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Cannot ping update server, skipping autoupdate");
                        Logs.Append(Environment.NewLine + DateTime.Now + "       Cannot ping update server, skipping autoupdate");
                    }
                }
                else
                {
                    richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Autoupdates disabled");
                    Logs.Append(Environment.NewLine + DateTime.Now + "       Autoupdates disabled");
                    button3.Text = "Updates disabled";
                }

                EndCheckUpdate :;
            }
            else
            {
                richTextBox1.AppendText(Environment.NewLine + DateTime.Now + "       Error: cannot find version.txt");
                Logs.Append(Environment.NewLine + DateTime.Now + "       Error: cannot find version.txt");
                EndStartup :;
                MessageBox.Show("Some files cannot be found. The program may run without them however cannot be updated and logs might not work");
                DialogResult UpdateResponse = MessageBox.Show("Would you like to download the newest version from online?", "Download latest version", MessageBoxButtons.YesNo);
            }
        }
Exemple #32
0
        private void CheckForUpdate()
        {
            //get the current version of IceChat 2009 in the Same Folder
            System.Diagnostics.FileVersionInfo fv;
            double currentVersion;

            try
            {
                fv = System.Diagnostics.FileVersionInfo.GetVersionInfo(currentFolder + Path.DirectorySeparatorChar + "IceChat2009.exe");
                System.Diagnostics.Debug.WriteLine(fv.FileVersion);
                labelCurrent.Text = "Current Version: " + fv.FileVersion;
                currentVersion    = Convert.ToDouble(fv.FileVersion.Replace(".", String.Empty));
            }
            catch (Exception)
            {
                currentVersion    = 000000000;
                labelCurrent.Text = "Current Version: 0.0.0000.0000";
                System.Diagnostics.Debug.WriteLine("IceChat EXE not found");
            }

            //delete the current update.xml file if it exists
            if (File.Exists(Application.StartupPath + System.IO.Path.DirectorySeparatorChar + "update9.xml"))
            {
                File.Delete(Application.StartupPath + System.IO.Path.DirectorySeparatorChar + "update9.xml");
            }

            System.Net.WebClient webClient = new System.Net.WebClient();
            webClient.DownloadFile("http://www.icechat.net/update9.xml", Application.StartupPath + System.IO.Path.DirectorySeparatorChar + "update9.xml");
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.Load(Application.StartupPath + System.IO.Path.DirectorySeparatorChar + "update9.xml");

            System.Xml.XmlNodeList version     = xmlDoc.GetElementsByTagName("version");
            System.Xml.XmlNodeList versiontext = xmlDoc.GetElementsByTagName("versiontext");

            labelLatest.Text = "Latest Version: " + versiontext[0].InnerText;

            if (Convert.ToDouble(version[0].InnerText) > currentVersion)
            {
                XmlNodeList files = xmlDoc.GetElementsByTagName("file");
                foreach (XmlNode node in files)
                {
                    DownloadItem dl = new DownloadItem();
                    dl.FileName  = node.InnerText;
                    dl.ShortName = Path.GetFileName(node.InnerText);
                    dl.FileType  = "core";
                    listFiles.Items.Add(dl);
                }

                buttonDownload.Visible = true;
                labelUpdate.Visible    = true;
            }
            else
            {
                labelNoUpdate.Visible = true;
            }

            //return;

            //check plugins that need to be updated as well
            //check the plugins folder
            if (Directory.Exists(currentFolder + System.IO.Path.DirectorySeparatorChar + "Plugins"))
            {
                string[] plugins = Directory.GetFiles(currentFolder + System.IO.Path.DirectorySeparatorChar + "Plugins", "*.dll");
                foreach (string fileName in plugins)
                {
                    //System.Diagnostics.Debug.WriteLine(fileName);
                    //look for a match to plugins online
                    FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(fileName);

                    XmlNodeList plgs = xmlDoc.GetElementsByTagName("plugin");

                    foreach (XmlNode plg in plgs)
                    {
                        //System.Diagnostics.Debug.WriteLine(plg["file"].InnerText);
                        //System.Diagnostics.Debug.WriteLine(plg["version"].InnerText);
                        if (Path.GetFileName(plg["pluginfile"].InnerText).ToLower() == fvi.InternalName.ToLower())
                        {
                            //check versions
                            //System.Diagnostics.Debug.WriteLine(fvi.FileVersion + ":" + plg["pluginversion"].InnerText + ":" + plg["pluginfile"].InnerText);
                            //System.Diagnostics.Debug.WriteLine(Convert.ToSingle(fvi.FileVersion));
                            if (Convert.ToSingle(fvi.FileVersion.Replace(".", "")) < Convert.ToSingle(plg["pluginversion"].InnerText.Replace(".", "")))
                            {
                                System.Diagnostics.Debug.WriteLine("Upgrade needed for " + fvi.InternalName);

                                DownloadItem dl = new DownloadItem();
                                dl.FileName  = plg["pluginfile"].InnerText;
                                dl.ShortName = Path.GetFileName(plg["pluginfile"].InnerText);
                                dl.FileType  = "plugin";
                                listFiles.Items.Add(dl);

                                buttonDownload.Visible = true;
                                labelUpdate.Visible    = true;
                            }
                        }
                    }
                }
            }
        }
Exemple #33
0
        private void DownloadUpdate(string filename, string destination)
        {
            var web = new System.Net.WebClient();

            web.DownloadFile(UpdatesPathUrl + filename, destination);
        }
        public IActionResult AuthCallback(string code)
        {
            var vm = new ActionResultVM();

            if (string.IsNullOrWhiteSpace(code))
            {
                vm.msg = "未授权,登录失败";
            }
            else
            {
                try
                {
                    //唯一标示
                    string openId = string.Empty;
                    //注册信息
                    var mo = new Domain.UserInfo()
                    {
                        LoginLimit     = 0,
                        UserSex        = 0,
                        UserCreateTime = DateTime.Now
                    };
                    //头像
                    string avatar = string.Empty;
                    //头像(高清)
                    string avatarhd = string.Empty;

                    if (Enum.TryParse(RouteData.Values["id"]?.ToString().ToLower(), out ValidateloginType vtype))
                    {
                        try
                        {
                            switch (vtype)
                            {
                            case ValidateloginType.qq:
                            {
                                //获取 access_token
                                var tokenEntity = QQ.AccessToken(new QQ_AccessToken_RequestEntity()
                                    {
                                        code = code
                                    });

                                //获取 OpendId
                                var openidEntity = QQ.OpenId(new QQ_OpenId_RequestEntity()
                                    {
                                        access_token = tokenEntity.access_token
                                    });

                                //获取 UserInfo
                                var userEntity = QQ.OpenId_Get_User_Info(new QQ_OpenAPI_RequestEntity()
                                    {
                                        access_token = tokenEntity.access_token,
                                        openid       = openidEntity.openid
                                    });

                                //身份唯一标识
                                openId     = openidEntity.openid;
                                mo.OpenId1 = openId;

                                mo.Nickname = userEntity.nickname;
                                mo.UserSex  = userEntity.gender == "男" ? 1 : 2;
                                mo.UserSay  = "";
                                mo.UserUrl  = "";

                                avatar   = userEntity.figureurl_qq_1;
                                avatarhd = userEntity.figureurl_qq_2;
                            }
                            break;

                            case ValidateloginType.weibo:
                            {
                                //获取 access_token
                                var tokenEntity = Weibo.AccessToken(new Weibo_AccessToken_RequestEntity()
                                    {
                                        code = code
                                    });

                                //获取 access_token 的授权信息
                                var tokenInfoEntity = Weibo.GetTokenInfo(new Weibo_GetTokenInfo_RequestEntity()
                                    {
                                        access_token = tokenEntity.access_token
                                    });

                                //获取 users/show
                                var userEntity = Weibo.UserShow(new Weibo_UserShow_RequestEntity()
                                    {
                                        access_token = tokenEntity.access_token,
                                        uid          = Convert.ToInt64(tokenInfoEntity.uid)
                                    });

                                openId     = tokenEntity.access_token;
                                mo.OpenId2 = openId;

                                mo.Nickname = userEntity.screen_name;
                                mo.UserSex  = userEntity.gender == "m" ? 1 : userEntity.gender == "f" ? 2 : 0;
                                mo.UserSay  = userEntity.description;
                                mo.UserUrl  = userEntity.domain;

                                avatar   = userEntity.profile_image_url;
                                avatarhd = userEntity.avatar_large;
                            }
                            break;

                            case ValidateloginType.github:
                            {
                                //获取 access_token
                                var tokenEntity = GitHub.AccessToken(new GitHub_AccessToken_RequestEntity()
                                    {
                                        code = code
                                    });

                                //获取 user
                                var userEntity = GitHub.User(new GitHub_User_RequestEntity()
                                    {
                                        access_token = tokenEntity.access_token
                                    });

                                openId     = userEntity.id.ToString();
                                mo.OpenId3 = openId;

                                mo.Nickname = userEntity.name;
                                mo.UserSay  = userEntity.bio;
                                mo.UserUrl  = userEntity.blog;
                                mo.UserMail = userEntity.email;

                                avatar   = userEntity.avatar_url;
                                avatarhd = userEntity.avatar_url;
                            }
                            break;

                            case ValidateloginType.taobao:
                            {
                                //获取 access_token
                                var tokenEntity = Taobao.AccessToken(new Taobao_AccessToken_RequestEntity()
                                    {
                                        code = code
                                    });

                                openId     = tokenEntity.open_uid;
                                mo.OpenId4 = openId;

                                mo.Nickname = "淘宝用户";
                            }
                            break;

                            case ValidateloginType.microsoft:
                            {
                                //获取 access_token
                                var tokenEntity = MicroSoft.AccessToken(new MicroSoft_AccessToken_RequestEntity()
                                    {
                                        code = code
                                    });

                                //获取 user
                                var userEntity = MicroSoft.User(new MicroSoft_User_RequestEntity()
                                    {
                                        access_token = tokenEntity.access_token
                                    });

                                openId     = userEntity.id.ToString();
                                mo.OpenId5 = openId;

                                mo.Nickname = userEntity.last_name + userEntity.first_name;
                                mo.UserMail = userEntity.emails["account"].ToStringOrEmpty();
                            }
                            break;
                            }
                        }
                        catch (Exception ex)
                        {
                            vm.msg = ex.Message;
                        }
                    }

                    mo.UserCreateTime = DateTime.Now;
                    mo.UserName       = openId;
                    mo.UserPwd        = Core.CalcTo.MD5(openId);
                    if (!string.IsNullOrWhiteSpace(avatar))
                    {
                        mo.UserPhoto = Core.UniqueTo.LongId().ToString() + ".jpg";
                    }

                    if (string.IsNullOrWhiteSpace(openId))
                    {
                        vm.msg = "身份验证失败";
                    }
                    else
                    {
                        //判断是绑定操作
                        bool isbind = false;
                        if (User.Identity.IsAuthenticated)
                        {
                            try
                            {
                                var aboa = Request.Cookies["AccountBindOAuth"];

                                if (!string.IsNullOrWhiteSpace(aboa) && (DateTime.Now - DateTime.Parse(aboa)).TotalSeconds < 120)
                                {
                                    int uid = new Func.UserAuthAid(HttpContext).Get().UserId;

                                    using (var db = new ContextBase())
                                    {
                                        //检测是否绑定其它账号
                                        var queryIsBind = db.UserInfo.Where(x => x.UserId != uid);
                                        switch (vtype)
                                        {
                                        case ValidateloginType.qq:
                                            queryIsBind = queryIsBind.Where(x => x.OpenId1 == openId);
                                            break;

                                        case ValidateloginType.weibo:
                                            queryIsBind = queryIsBind.Where(x => x.OpenId2 == openId);
                                            break;

                                        case ValidateloginType.github:
                                            queryIsBind = queryIsBind.Where(x => x.OpenId3 == openId);
                                            break;

                                        case ValidateloginType.taobao:
                                            queryIsBind = queryIsBind.Where(x => x.OpenId4 == openId);
                                            break;

                                        case ValidateloginType.microsoft:
                                            queryIsBind = queryIsBind.Where(x => x.OpenId5 == openId);
                                            break;
                                        }
                                        if (queryIsBind.Count() > 0)
                                        {
                                            return(Content("已绑定其它账号,不能重复绑定"));
                                        }

                                        var userInfo = db.UserInfo.Find(uid);

                                        switch (vtype)
                                        {
                                        case ValidateloginType.qq:
                                            userInfo.OpenId1 = openId;
                                            break;

                                        case ValidateloginType.weibo:
                                            userInfo.OpenId2 = openId;
                                            break;

                                        case ValidateloginType.github:
                                            userInfo.OpenId3 = openId;
                                            break;

                                        case ValidateloginType.taobao:
                                            userInfo.OpenId4 = openId;
                                            break;

                                        case ValidateloginType.microsoft:
                                            userInfo.OpenId5 = openId;
                                            break;
                                        }
                                        db.UserInfo.Update(userInfo);
                                        db.SaveChanges();
                                    }

                                    Response.Cookies.Delete("AccountBindOAuth");
                                    isbind = true;
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }

                        //是绑定操作
                        if (isbind)
                        {
                            return(Redirect("/user/setting"));
                        }
                        else
                        {
                            using (var db = new ContextBase())
                            {
                                Domain.UserInfo vmo = null;
                                switch (vtype)
                                {
                                case ValidateloginType.qq:
                                    vmo = db.UserInfo.FirstOrDefault(x => x.OpenId1 == openId);
                                    break;

                                case ValidateloginType.weibo:
                                    vmo = db.UserInfo.FirstOrDefault(x => x.OpenId2 == openId);
                                    break;

                                case ValidateloginType.github:
                                    vmo = db.UserInfo.FirstOrDefault(x => x.OpenId3 == openId);
                                    break;

                                case ValidateloginType.taobao:
                                    vmo = db.UserInfo.FirstOrDefault(x => x.OpenId4 == openId);
                                    break;

                                case ValidateloginType.microsoft:
                                    vmo = db.UserInfo.FirstOrDefault(x => x.OpenId5 == openId);
                                    break;
                                }
                                //未注册
                                if (vmo == null)
                                {
                                    var ruvm = RegisterUser(mo);
                                    if (ruvm.code == 200)
                                    {
                                        vm = ValidateLogin(vtype, mo);
                                        //拉取头像
                                        if (vm.code == 200 && (!string.IsNullOrWhiteSpace(avatar) || !string.IsNullOrWhiteSpace(avatarhd)))
                                        {
                                            try
                                            {
                                                System.Net.WebClient wc = new System.Net.WebClient();

                                                var rootdir  = GlobalTo.WebRootPath + "/" + (GlobalTo.GetValue("StaticResource:RootDir").TrimStart('/').TrimEnd('/') + "/");
                                                var path     = GlobalTo.GetValue("StaticResource:AvatarPath").TrimEnd('/').TrimStart('/') + '/';
                                                var fullpath = rootdir + path;

                                                if (!System.IO.Directory.Exists(fullpath))
                                                {
                                                    System.IO.Directory.CreateDirectory(fullpath);
                                                }
                                                if (!string.IsNullOrWhiteSpace(avatar))
                                                {
                                                    wc.DownloadFile(avatar, fullpath + mo.UserPhoto);
                                                }
                                                if (!string.IsNullOrWhiteSpace(avatarhd))
                                                {
                                                    wc.DownloadFile(avatarhd, fullpath + mo.UserPhoto.Replace(".jpg", "_lg.jpg"));
                                                }
                                            }
                                            catch (Exception)
                                            {
                                            }
                                        }
                                    }
                                    else
                                    {
                                        vm.msg = ruvm.msg;
                                    }
                                }
                                else
                                {
                                    vm = ValidateLogin(vtype, vmo);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    vm.msg = ex.Message;
                }
            }

            //成功
            if (vm.code == 200)
            {
                return(Redirect("/"));
            }
            else
            {
                string msg = "【登录失败】( " + vm.msg + " )".ToEncode();
                return(Redirect("/home/error?msg=" + msg));
            }
        }
Exemple #35
0
        public IActionResult DownloadTax(string month)
        {
            var organisaction = organisationService.Get(organisationService.OrganisationId);
            var url           = Request.Scheme + "://" + Request.Host;
            var temPath       = Path.Combine(webHostEnvironment.WebRootPath, "Temp");

            if (!Directory.Exists(temPath))
            {
                Directory.CreateDirectory(temPath);
            }
            var files = new DirectoryInfo(temPath).GetFiles().Where(u => u.CreationTime < DateTime.Now.AddHours(-4)).Select(u => u);

            foreach (var file in files)
            {
                file.Delete();
            }
            var folderName = Guid.NewGuid().ToString();

            temPath = Path.Combine(temPath, folderName);
            Directory.CreateDirectory(temPath);
            var templatPath = Path.Combine(webHostEnvironment.WebRootPath, "template", "tax");
            var tax         = reportService.GetTaxMonthly(month, reportService.OrganisationId);

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            using (var package = new ExcelPackage(new FileInfo(Path.Combine(templatPath, "Salary.xlsx"))))
            {
                var sheet = package.Workbook.Worksheets[0];
                sheet.Name = "Salary-" + month;
                sheet.Cells[1, 1].Value  = "ប្រាក់កាត់ទុកពីប្រាក់បៀវត្ស ប្រចាំខែ " + Utils.ConvertInternationalNumberToKhmer(month.Substring(4)) + " ឆ្នាំ " + Utils.ConvertInternationalNumberToKhmer(month.Substring(0, 4));
                sheet.Cells[2, 1].Value  = organisaction.LegalLocalName;
                sheet.Cells[3, 10].Value = "លេខអត្តសញ្ញាណកម្មៈ " + organisaction.TaxNumber;
                int i = 8;
                if (tax.Payroll.Payrolls.Any())
                {
                    if (tax.Payroll.ExchangeRate == 1)
                    {
                        sheet.Cells[4, 13].Value = "";
                        sheet.Cells[4, 14].Value = "";
                    }
                    else
                    {
                        sheet.Cells[4, 14].Value = tax.Payroll.ExchangeRate + " R/$";
                    }

                    foreach (var emp in tax.Payroll.Payrolls)
                    {
                        sheet.Cells[i, 1].Value = i - 7;
                        sheet.Cells[i, 2].Value = emp.Employee.IDOrPassportNumber;
                        sheet.Cells[i, 3].Value = emp.Employee.DisplayName;
                        sheet.Cells[i, 4].Value = emp.Employee.Country.Nationality;
                        sheet.Cells[i, 5].Value = emp.Employee.JobTitle;
                        if (tax.Payroll.ExchangeRate == 1)
                        {
                            sheet.Cells[i, 6].Value = "-";
                        }
                        else
                        {
                            sheet.Cells[i, 6].Value = tax.Payroll.Currency.Symbole + " " + Math.Round(emp.Salary, 0);
                        }
                        sheet.Cells[i, 7].Value = Math.Round(emp.Salary * tax.Payroll.ExchangeRate, 0);
                        if (emp.Employee.IsResidentEmployee)
                        {
                            sheet.Cells[i, 8].Value = emp.Employee.NumberOfChild;
                        }
                        else
                        {
                            sheet.Cells[i, 8].Value = "-";
                        }
                        if (emp.Employee.IsResidentEmployee)
                        {
                            sheet.Cells[i, 9].Value = emp.Employee.IsConfederationThatHosts ? "Yes" : "No";
                        }
                        else
                        {
                            sheet.Cells[i, 9].Value = "-";
                        }
                        if (emp.OtherBenefit == null)
                        {
                            sheet.Cells[i, 10].Value = "-";
                        }
                        else
                        {
                            sheet.Cells[i, 10].Value = Math.Round(emp.OtherBenefit.Value * tax.Payroll.ExchangeRate, 0);
                        }
                        sheet.Cells[i, 11].Value = Math.Round(emp.DeductSalary * tax.Payroll.ExchangeRate, 0);
                        if (emp.OtherBenefitTaxDeduct == null)
                        {
                            sheet.Cells[i, 12].Value = "-";
                        }
                        else
                        {
                            sheet.Cells[i, 12].Value = Math.Round(emp.OtherBenefitTaxDeduct.Value * tax.Payroll.ExchangeRate, 0);
                        }

                        var totalTax = emp.DeductSalary * tax.Payroll.ExchangeRate;
                        if (emp.OtherBenefit != null)
                        {
                            totalTax += emp.OtherBenefitTaxDeduct.Value * tax.Payroll.ExchangeRate;
                        }
                        sheet.Cells[i, 13].Value = Math.Round(totalTax, 0);
                        for (int k = 1; k <= 14; k++)
                        {
                            sheet.Cells[i, k].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                        }
                        i++;
                    }
                    sheet.Cells[i, 1, i, 5].Merge = true;
                    sheet.Cells[i, 1].Value       = "Total:";
                    sheet.Cells[i, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Right;
                    if (tax.Payroll.ExchangeRate == 1)
                    {
                        sheet.Cells[i, 6].Value = "-";
                    }
                    else
                    {
                        sheet.Cells[i, 6].Value = tax.Payroll.Currency.Symbole + " " + Math.Round(tax.Payroll.Payrolls.Sum(u => u.Salary), 0);
                    }
                    sheet.Cells[i, 7].Value  = Math.Round(tax.Payroll.Payrolls.Sum(u => u.Salary * tax.Payroll.ExchangeRate), 0);
                    sheet.Cells[i, 8].Value  = "-";
                    sheet.Cells[i, 9].Value  = "-";
                    sheet.Cells[i, 10].Value = Math.Round(tax.Payroll.Payrolls.Where(u => u.OtherBenefit != null).Sum(u => u.OtherBenefit.Value * tax.Payroll.ExchangeRate), 0);
                    sheet.Cells[i, 11].Value = Math.Round(tax.Payroll.Payrolls.Sum(u => u.DeductSalary * tax.Payroll.ExchangeRate), 0);
                    sheet.Cells[i, 12].Value = Math.Round(tax.Payroll.Payrolls.Where(u => u.OtherBenefitTaxDeduct != null).Sum(u => u.OtherBenefitTaxDeduct.Value * tax.Payroll.ExchangeRate), 0);
                    sheet.Cells[i, 13].Value = Math.Round(tax.TotalEmployeeTaxInTaxCurrency, 0);
                    for (int k = 1; k <= 14; k++)
                    {
                        sheet.Cells[i, k].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                        sheet.Cells[i, k].Style.Font.Bold = true;
                    }
                }

                i += 2;
                sheet.Cells[i, 1, i, 5].Merge               = true;
                sheet.Cells[i, 1].Value                     = "ធ្វើនៅ ភ្នំពេញ ថ្ងៃទី " + Utils.ConvertInternationalNumberToKhmer(Utils.CurrentCambodiaTime().Value.Day.ToString("00")) + " ខែ " + Utils.GetKhmerMonthName(Utils.CurrentCambodiaTime().Value) + " ឆ្នាំ " + Utils.ConvertInternationalNumberToKhmer(Utils.CurrentCambodiaTime().Value.Year.ToString());
                sheet.Cells[i, 1].Style.Font.Name           = "Khmer OS Siemreap";
                sheet.Cells[i, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                i++;
                sheet.Cells[i, 1, i, 5].Merge = true;
                sheet.Cells[i, 1].Value       = "ហត្ថលេខា";
                sheet.Cells[i, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells[i, 1].Style.Font.Name           = "Khmer OS Siemreap";
                package.SaveAs(new FileInfo(Path.Combine(Path.Combine(temPath, "Salary-" + month + ".xlsx"))));
            }
            using (var package = new ExcelPackage(new FileInfo(Path.Combine(templatPath, "Purchase.xlsx"))))
            {
                var sheet = package.Workbook.Worksheets[0];
                sheet.Name = "Purchase " + month;
                sheet.Cells[2, 1].Value = "ខែ " + Utils.ConvertInternationalNumberToKhmer(month.Substring(4)) + "  ឆ្នាំ  " + Utils.ConvertInternationalNumberToKhmer(month.Substring(0, 4));
                sheet.Cells[3, 1].Value = "ឈ្មោះសហគ្រាស៖ " + organisaction.LegalLocalName;
                sheet.Cells[4, 1].Value = organisaction.Contact.Address;
                sheet.Cells[4, 8].Value = "លេខអត្តសញ្ញាណកម្មៈ " + organisaction.TaxNumber;
                int     i                   = 10;
                var     expenseItems        = reportService.GetExpenseItemsTax(tax.Expenses.Select(u => u.Id).ToList());
                decimal totalInBaseCurrency = 0;
                decimal totalInTaxCurrency  = 0;
                decimal totalTax            = 0;
                foreach (var expense in tax.Expenses)
                {
                    var itemsInExpense = expenseItems.Where(u => u.ExpenseId == expense.Id);
                    sheet.Cells[i, 1].Value = expense.Date;
                    sheet.Cells[i, 2].Value = string.IsNullOrEmpty(expense.RefNo)? expense.OrderNumber:expense.RefNo;
                    sheet.Cells[i, 3].Value = string.IsNullOrEmpty(expense.Vendor.LocalLegalName) && string.IsNullOrEmpty(expense.Vendor.LegalName)
                        ? expense.Vendor.DisplayName :
                                              (string.IsNullOrEmpty(expense.Vendor.LocalLegalName)?expense.Vendor.LegalName:expense.Vendor.LocalLegalName);
                    sheet.Cells[i, 4].Value = expense.Vendor.TaxNumber;
                    sheet.Cells[i, 5].Value = itemsInExpense.First().Description;
                    sheet.Cells[i, 6].Value = "-";
                    if (expense.TaxCurrencyExchangeRate == 1)
                    {
                        sheet.Cells[i, 7].Value = "-";
                    }
                    else
                    {
                        sheet.Cells[i, 7].Value = expense.TaxCurrencyExchangeRate;
                    }
                    if (expense.TaxCurrencyExchangeRate == 1)
                    {
                        sheet.Cells[i, 8].Value = "-";
                    }
                    else
                    {
                        sheet.Cells[i, 8].Value = expense.Currency.Symbole + " " + Math.Round(expense.Total, 0);
                    }
                    sheet.Cells[i, 9].Value = Math.Round(expense.Total * expense.TaxCurrencyExchangeRate);

                    Dictionary <int, int> dicRate = new Dictionary <int, int>();
                    foreach (var t in itemsInExpense)
                    {
                        foreach (var r in t.Tax.Components)
                        {
                            if (!dicRate.ContainsKey((int)r.Rate))
                            {
                                dicRate.Add((int)r.Rate, (int)r.Rate);
                            }
                        }
                    }
                    string rateText = "";
                    foreach (var r in dicRate)
                    {
                        if (rateText != "")
                        {
                            rateText += ",";
                        }
                        rateText += r.Key + "%";
                    }

                    sheet.Cells[i, 10].Value = rateText;
                    sheet.Cells[i, 11].Value = Math.Round((expense.TotalIncludeTax - expense.Total) * expense.TaxCurrencyExchangeRate, 0);
                    sheet.Cells[i, 12].Value = Math.Round(expense.TotalIncludeTax * expense.TaxCurrencyExchangeRate, 0);
                    totalInBaseCurrency     += expense.Total * expense.BaseCurrencyExchangeRate;
                    totalInTaxCurrency      += expense.Total * expense.TaxCurrencyExchangeRate;
                    totalTax += (expense.TotalIncludeTax - expense.Total) * expense.TaxCurrencyExchangeRate;
                    for (int j = 1; j <= 12; j++)
                    {
                        sheet.Cells[i, j].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                    }
                    i++;
                }
                sheet.Cells[i, 1, i, 7].Merge = true;
                sheet.Cells[i, 1].Value       = "Total:";
                sheet.Cells[i, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Right;
                sheet.Cells[i, 8].Value  = tax.Currency.Symbole + " " + Math.Round(totalInBaseCurrency, 2);
                sheet.Cells[i, 9].Value  = Math.Round(totalInTaxCurrency, 0);
                sheet.Cells[i, 10].Value = "-";
                sheet.Cells[i, 11].Value = Math.Round(totalTax, 0);
                sheet.Cells[i, 12].Value = Math.Round(totalInTaxCurrency + totalTax, 0);
                for (int j = 1; j <= 12; j++)
                {
                    sheet.Cells[i, j].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                    sheet.Cells[i, j].Style.Font.Bold = true;
                }
                i += 2;
                sheet.Cells[i, 7, i, 12].Merge = true;
                sheet.Cells[i, 7].Value        = "ធ្វើនៅ ភ្នំពេញ ថ្ងៃទី " + Utils.ConvertInternationalNumberToKhmer(Utils.CurrentCambodiaTime().Value.Day.ToString("00")) + " ខែ " + Utils.GetKhmerMonthName(Utils.CurrentCambodiaTime().Value) + " ឆ្នាំ " + Utils.ConvertInternationalNumberToKhmer(Utils.CurrentCambodiaTime().Value.Year.ToString());
                sheet.Cells[i, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells[i, 7].Style.Font.Name           = "Khmer OS Siemreap";
                i++;
                sheet.Cells[i, 7, i, 12].Merge = true;
                sheet.Cells[i, 7].Value        = "ហត្ថលេខា";
                sheet.Cells[i, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells[i, 7].Style.Font.Name           = "Khmer OS Siemreap";
                package.SaveAs(new FileInfo(Path.Combine(Path.Combine(temPath, "Purchase-" + month + ".xlsx"))));
            }
            using (var package = new ExcelPackage(new FileInfo(Path.Combine(templatPath, "Sale.xlsx"))))
            {
                var sheet = package.Workbook.Worksheets[0];
                sheet.Name = "Sale " + month;
                sheet.Cells[2, 1].Value = "ខែ " + Utils.ConvertInternationalNumberToKhmer(month.Substring(4)) + "  ឆ្នាំ  " + Utils.ConvertInternationalNumberToKhmer(month.Substring(0, 4));
                sheet.Cells[3, 1].Value = "ឈ្មោះសហគ្រាស៖ " + organisaction.LegalLocalName;
                sheet.Cells[4, 1].Value = organisaction.Contact.Address;
                sheet.Cells[4, 8].Value = "លេខអត្តសញ្ញាណកម្មៈ " + organisaction.TaxNumber;

                var     invoiceItems        = reportService.GetInvoiceItems(tax.Invoices.Select(u => u.Id).ToList());
                decimal totalInBaseCurrency = 0;
                decimal totalInTaxCurrency  = 0;
                decimal totalTax            = 0;
                int     i = 10;
                foreach (var invoice in tax.Invoices)
                {
                    var itemsInExpense = invoiceItems.Where(u => u.CustomerTransaction == invoice.Id);
                    sheet.Cells[i, 1].Value = invoice.Date;
                    sheet.Cells[i, 2].Value = invoice.Number;
                    sheet.Cells[i, 3].Value = string.IsNullOrEmpty(invoice.Customer.LocalLegalName) && string.IsNullOrEmpty(invoice.Customer.LegalName)
                        ? invoice.Customer.DisplayName :
                                              (string.IsNullOrEmpty(invoice.Customer.LocalLegalName) ? invoice.Customer.LegalName : invoice.Customer.LocalLegalName);
                    sheet.Cells[i, 4].Value = invoice.Customer.TaxNumber;
                    sheet.Cells[i, 5].Value = itemsInExpense.First().Description;
                    sheet.Cells[i, 6].Value = "-";
                    if (invoice.TaxCurrencyExchangeRate == 1)
                    {
                        sheet.Cells[i, 7].Value = "-";
                    }
                    else
                    {
                        sheet.Cells[i, 7].Value = invoice.TaxCurrencyExchangeRate;
                    }
                    if (invoice.TaxCurrencyExchangeRate == 1)
                    {
                        sheet.Cells[i, 8].Value = "-";
                    }
                    else
                    {
                        sheet.Cells[i, 8].Value = invoice.Currency.Symbole + " " + Math.Round(invoice.Total, 0);
                    }
                    sheet.Cells[i, 9].Value = Math.Round(invoice.Total * invoice.TaxCurrencyExchangeRate);

                    Dictionary <int, int> dicRate = new Dictionary <int, int>();
                    foreach (var t in itemsInExpense)
                    {
                        foreach (var r in t.Tax.Components)
                        {
                            if (!dicRate.ContainsKey((int)r.Rate))
                            {
                                dicRate.Add((int)r.Rate, (int)r.Rate);
                            }
                        }
                    }
                    string rateText = "";
                    foreach (var r in dicRate)
                    {
                        if (rateText != "")
                        {
                            rateText += ",";
                        }
                        rateText += r.Key + "%";
                    }

                    sheet.Cells[i, 10].Value = rateText;
                    sheet.Cells[i, 11].Value = Math.Round((invoice.TotalIncludeTax - invoice.Total) * invoice.TaxCurrencyExchangeRate, 0);
                    sheet.Cells[i, 12].Value = Math.Round(invoice.TotalIncludeTax * invoice.TaxCurrencyExchangeRate, 0);
                    totalInBaseCurrency     += invoice.Total * invoice.BaseCurrencyExchangeRate;
                    totalInTaxCurrency      += invoice.Total * invoice.TaxCurrencyExchangeRate;
                    totalTax += (invoice.TotalIncludeTax - invoice.Total) * invoice.TaxCurrencyExchangeRate;
                    for (int j = 1; j <= 12; j++)
                    {
                        sheet.Cells[i, j].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                    }
                    i++;
                }
                sheet.Cells[i, 1, i, 7].Merge = true;
                sheet.Cells[i, 1].Value       = "Total:";
                sheet.Cells[i, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Right;
                sheet.Cells[i, 8].Value  = tax.Currency.Symbole + " " + Math.Round(totalInBaseCurrency, 2);
                sheet.Cells[i, 9].Value  = Math.Round(totalInTaxCurrency, 0);
                sheet.Cells[i, 10].Value = "-";
                sheet.Cells[i, 11].Value = Math.Round(totalTax, 0);
                sheet.Cells[i, 12].Value = Math.Round(totalInTaxCurrency + totalTax, 0);
                for (int j = 1; j <= 12; j++)
                {
                    sheet.Cells[i, j].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                    sheet.Cells[i, j].Style.Font.Bold = true;
                }
                i += 2;
                sheet.Cells[i, 7, i, 12].Merge = true;
                sheet.Cells[i, 7].Value        = "ធ្វើនៅ ភ្នំពេញ ថ្ងៃទី " + Utils.ConvertInternationalNumberToKhmer(Utils.CurrentCambodiaTime().Value.Day.ToString("00")) + " ខែ " + Utils.GetKhmerMonthName(Utils.CurrentCambodiaTime().Value) + " ឆ្នាំ " + Utils.ConvertInternationalNumberToKhmer(Utils.CurrentCambodiaTime().Value.Year.ToString());
                sheet.Cells[i, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells[i, 7].Style.Font.Name           = "Khmer OS Siemreap";
                i++;
                sheet.Cells[i, 7, i, 12].Merge = true;
                sheet.Cells[i, 7].Value        = "ហត្ថលេខា";
                sheet.Cells[i, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells[i, 7].Style.Font.Name           = "Khmer OS Siemreap";
                package.SaveAs(new FileInfo(Path.Combine(Path.Combine(temPath, "Sale-" + month + ".xlsx"))));
            }
            using (var package = new ExcelPackage(new FileInfo(Path.Combine(templatPath, "Summary.xlsx"))))
            {
                var sheet = package.Workbook.Worksheets[0];
                sheet.Cells[2, 1].Value = organisaction.LegalLocalName;
                sheet.Cells[3, 1].Value = "ខែ " + Utils.ConvertInternationalNumberToKhmer(month.Substring(4)) + "  ឆ្នាំ  " + Utils.ConvertInternationalNumberToKhmer(month.Substring(0, 4));
                sheet.Cells[5, 2].Value = tax.Currency.Symbole + " " + Math.Round(tax.TotalInvoiceTaxInBaseCurrency, 2);
                sheet.Cells[6, 2].Value = tax.Currency.Symbole + " " + Math.Round(tax.TotalExpenseTaxInBaseCurrency, 2);
                sheet.Cells[7, 2].Value = tax.Currency.Symbole + " " + Math.Round(tax.TotalEmployeeTaxInBaseCurrency, 2);
                sheet.Cells[8, 2].Value = tax.Currency.Symbole + " " + Math.Round(tax.TotalPayToTax, 0);
                sheet.Cells[9, 2].Value = Math.Round(tax.TotalPayToTaxInKHR, 2) + tax.TaxCurrency.Symbole;
                var invoiceSheet = package.Workbook.Worksheets[1];
                invoiceSheet.Cells[2, 1].Value = "ខែ " + Utils.ConvertInternationalNumberToKhmer(month.Substring(4)) + "  ឆ្នាំ  " + Utils.ConvertInternationalNumberToKhmer(month.Substring(0, 4));
                invoiceSheet.Cells[3, 1].Value = organisaction.LegalLocalName;
                int i = 6;
                foreach (var invoice in tax.Invoices)
                {
                    invoiceSheet.Cells[i, 1].Value = invoice.Date;
                    invoiceSheet.Cells[i, 2].Value = invoice.Number;
                    invoiceSheet.Cells[i, 3].Value = tax.Currency.Symbole + " " + Math.Round(invoice.TotalIncludeTax * invoice.BaseCurrencyExchangeRate, 2);
                    invoiceSheet.Cells[i, 4].Value = tax.Currency.Symbole + " " + Math.Round((invoice.TotalIncludeTax - invoice.Total) * invoice.BaseCurrencyExchangeRate, 2);
                    if (invoice.TaxCurrencyExchangeRate == 1)
                    {
                        invoiceSheet.Cells[i, 5].Value = "-";
                    }
                    else
                    {
                        invoiceSheet.Cells[i, 5].Value = invoice.TaxCurrencyExchangeRate;
                    }
                    invoiceSheet.Cells[i, 6].Value = Math.Round((invoice.TotalIncludeTax - invoice.Total) * invoice.TaxCurrencyExchangeRate, 0);
                    for (int j = 1; j <= 6; j++)
                    {
                        invoiceSheet.Cells[i, j].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                    }
                    i++;
                }
                invoiceSheet.Cells[i, 1, i, 2].Merge = true;
                invoiceSheet.Cells[i, 1].Value       = "Total:";
                invoiceSheet.Cells[i, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Right;
                invoiceSheet.Cells[i, 3].Value = tax.Currency.Symbole + " " + Math.Round(tax.Invoices.Sum(u => u.TotalIncludeTax * u.BaseCurrencyExchangeRate), 2);
                invoiceSheet.Cells[i, 4].Value = tax.Currency.Symbole + " " + Math.Round(tax.Invoices.Sum(u => (u.TotalIncludeTax - u.Total) * u.BaseCurrencyExchangeRate), 2);
                invoiceSheet.Cells[i, 5].Value = "-";
                invoiceSheet.Cells[i, 6].Value = Math.Round(tax.Invoices.Sum(u => (u.TotalIncludeTax - u.Total) * u.TaxCurrencyExchangeRate), 2) + " " + tax.TaxCurrency.Symbole;
                for (int j = 1; j <= 6; j++)
                {
                    invoiceSheet.Cells[i, j].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                    invoiceSheet.Cells[i, j].Style.Font.Bold = true;
                }
                var exepnseSheet = package.Workbook.Worksheets[2];
                exepnseSheet.Cells[2, 1].Value = "ខែ " + Utils.ConvertInternationalNumberToKhmer(month.Substring(4)) + "  ឆ្នាំ  " + Utils.ConvertInternationalNumberToKhmer(month.Substring(0, 4));
                exepnseSheet.Cells[3, 1].Value = organisaction.LegalLocalName;
                i = 6;
                foreach (var expense in tax.Expenses)
                {
                    exepnseSheet.Cells[i, 1].Value = expense.Date;
                    exepnseSheet.Cells[i, 2].Value = expense.OrderNumber;
                    exepnseSheet.Cells[i, 3].Value = tax.Currency.Symbole + " " + Math.Round(expense.TotalIncludeTax * expense.BaseCurrencyExchangeRate, 2);
                    exepnseSheet.Cells[i, 4].Value = tax.Currency.Symbole + " " + Math.Round((expense.TotalIncludeTax - expense.Total) * expense.BaseCurrencyExchangeRate, 2);
                    if (expense.TaxCurrencyExchangeRate == 1)
                    {
                        exepnseSheet.Cells[i, 5].Value = "-";
                    }
                    else
                    {
                        exepnseSheet.Cells[i, 5].Value = expense.TaxCurrencyExchangeRate;
                    }
                    exepnseSheet.Cells[i, 6].Value = Math.Round((expense.TotalIncludeTax - expense.Total) * expense.TaxCurrencyExchangeRate, 0);
                    for (int j = 1; j <= 6; j++)
                    {
                        exepnseSheet.Cells[i, j].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                    }
                    i++;
                }
                exepnseSheet.Cells[i, 1, i, 2].Merge = true;
                exepnseSheet.Cells[i, 1].Value       = "Total:";
                exepnseSheet.Cells[i, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Right;
                exepnseSheet.Cells[i, 3].Value = tax.Currency.Symbole + " " + Math.Round(tax.Expenses.Sum(u => u.TotalIncludeTax * u.BaseCurrencyExchangeRate), 2);
                exepnseSheet.Cells[i, 4].Value = tax.Currency.Symbole + " " + Math.Round(tax.Expenses.Sum(u => (u.TotalIncludeTax - u.Total) * u.BaseCurrencyExchangeRate), 2);
                exepnseSheet.Cells[i, 5].Value = "-";
                exepnseSheet.Cells[i, 6].Value = Math.Round(tax.Expenses.Sum(u => (u.TotalIncludeTax - u.Total) * u.TaxCurrencyExchangeRate), 2) + " " + tax.TaxCurrency.Symbole;
                for (int j = 1; j <= 6; j++)
                {
                    exepnseSheet.Cells[i, j].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                    exepnseSheet.Cells[i, j].Style.Font.Bold = true;
                }
                var salarySheet = package.Workbook.Worksheets[3];
                salarySheet.Cells[2, 1].Value = "ខែ " + Utils.ConvertInternationalNumberToKhmer(month.Substring(4)) + "  ឆ្នាំ  " + Utils.ConvertInternationalNumberToKhmer(month.Substring(0, 4));
                salarySheet.Cells[3, 1].Value = organisaction.LegalLocalName;
                i = 6;
                foreach (var emp in tax.Payroll.Payrolls)
                {
                    salarySheet.Cells[i, 1].Value = emp.Employee.DisplayName;
                    salarySheet.Cells[i, 2].Value = tax.Currency.Symbole + " " + Math.Round(emp.Salary, 2);
                    if (emp.OtherBenefit == null)
                    {
                        salarySheet.Cells[i, 3].Value = "-";
                    }
                    else
                    {
                        salarySheet.Cells[i, 3].Value = tax.Currency.Symbole + " " + Math.Round(emp.OtherBenefit.Value, 2);
                    }
                    var totalTax = emp.DeductSalary;
                    if (emp.OtherBenefitTaxDeduct != null)
                    {
                        totalTax += emp.OtherBenefitTaxDeduct.Value;
                    }
                    salarySheet.Cells[i, 4].Value = tax.Currency.Symbole + " " + Math.Round(totalTax, 2);
                    if (tax.Payroll.ExchangeRate == 1)
                    {
                        salarySheet.Cells[i, 5].Value = "-";
                    }
                    else
                    {
                        salarySheet.Cells[i, 5].Value = tax.Payroll.ExchangeRate;
                    }
                    salarySheet.Cells[i, 6].Value = Math.Round(totalTax * tax.Payroll.ExchangeRate, 0) + " " + tax.TaxCurrency.Symbole;
                    for (int j = 1; j <= 6; j++)
                    {
                        salarySheet.Cells[i, j].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                    }
                    i++;
                }
                salarySheet.Cells[i, 1].Value = "Total:";
                salarySheet.Cells[i, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Right;
                salarySheet.Cells[i, 2].Value = tax.Currency.Symbole + " " + Math.Round(tax.Payroll.Payrolls.Sum(u => u.Salary), 2);
                salarySheet.Cells[i, 3].Value = tax.Currency.Symbole + " " + Math.Round(tax.Payroll.Payrolls.Where(u => u.OtherBenefit != null).Sum(u => u.OtherBenefit.Value), 2);
                var totalPayTax = tax.Payroll.Payrolls.Sum(u => u.DeductSalary + (u.OtherBenefitTaxDeduct == null ? 0 : u.OtherBenefitTaxDeduct.Value));
                salarySheet.Cells[i, 4].Value = tax.Currency.Symbole + " " + Math.Round(totalPayTax, 2);
                salarySheet.Cells[i, 5].Value = "-";
                salarySheet.Cells[i, 6].Value = Math.Round(totalPayTax * tax.Payroll.ExchangeRate, 0) + " " + tax.TaxCurrency.Symbole;
                for (int j = 1; j <= 6; j++)
                {
                    salarySheet.Cells[i, j].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                    salarySheet.Cells[i, j].Style.Font.Bold = true;
                }
                package.SaveAs(new FileInfo(Path.Combine(Path.Combine(temPath, "Summary-" + month + ".xlsx"))));
            }
            var expenseFileFolder = Path.Combine(temPath, "Purchase");

            Directory.CreateDirectory(expenseFileFolder);
            var expenseAttachments = reportService.GetExpenseOfficalDocuments(tax.Expenses.Select(u => u.Id).ToList());

            foreach (var expenseAttachment in expenseAttachments)
            {
                var fileName = expenseAttachment.RefNo;
                if (expenseAttachments.Any(u => u != expenseAttachment && u.RefNo == expenseAttachment.RefNo))
                {
                    fileName += Guid.NewGuid().ToString();
                }
                fileName += "." + expenseAttachment.FileName.Split('.')[expenseAttachment.FileName.Split('.').Length - 1];
                using System.Net.WebClient wc = new System.Net.WebClient();
                wc.DownloadFile(expenseAttachment.FileUrl, Path.Combine(expenseFileFolder, fileName));
            }
            var invoiceFolder = Path.Combine(temPath, "Sale");

            Directory.CreateDirectory(invoiceFolder);
            expenseAttachments = reportService.GetInvoiceOfficalDocuments(tax.Invoices.Select(u => u.Id).ToList());

            foreach (var expenseAttachment in expenseAttachments)
            {
                var fileName = expenseAttachment.RefNo;
                if (expenseAttachments.Any(u => u != expenseAttachment && u.RefNo == expenseAttachment.RefNo))
                {
                    fileName += Guid.NewGuid().ToString();
                }
                fileName += "." + expenseAttachment.FileName.Split('.')[expenseAttachment.FileName.Split('.').Length - 1];
                using System.Net.WebClient wc = new System.Net.WebClient();
                wc.DownloadFile(expenseAttachment.FileUrl, Path.Combine(invoiceFolder, fileName));
            }
            var    zipFileName = month + "-" + folderName + ".zip";
            string zipPath     = Path.Combine(webHostEnvironment.WebRootPath, "Temp", zipFileName);

            ZipFile.CreateFromDirectory(temPath, zipPath);
            Directory.Delete(temPath, true);
            return(Ok(new { result = url + "/Temp/" + zipFileName }));
        }
Exemple #36
0
        private void getImagesThreadMethod()
        {
            Framework.Data.Geocache gc = null;
            lock (_gcList)
            {
                if (_gcList.Count > 0)
                {
                    gc = _gcList[0];
                    _gcList.RemoveAt(0);
                }
            }
            using (System.Net.WebClient wc = new System.Net.WebClient())
            {
                string fnp         = System.IO.Path.Combine(PluginSettings.Instance.ActiveDataPath, IMG_SUBFOLDER);
                bool   grabOnlyNew = _grabOnlyNew;
                while (gc != null)
                {
                    //todo: get images
                    try
                    {
                        StringBuilder sb = new StringBuilder();
                        lock (_lockDBObject)
                        {
                            if (gc.ShortDescriptionInHtml && gc.ShortDescription != null)
                            {
                                sb.Append(gc.ShortDescription);
                            }
                            if (gc.LongDescriptionInHtml && gc.LongDescription != null)
                            {
                                sb.Append(gc.LongDescription);
                            }
                        }
                        if (sb.Length > 0)
                        {
                            List <string> linkList = new List <string>();

                            Regex           r  = new Regex(@"</?\w+\s+[^>]*>", RegexOptions.Multiline);
                            MatchCollection mc = r.Matches(sb.ToString());
                            foreach (Match m in mc)
                            {
                                string s = m.Value.Substring(1).Replace('\r', ' ').Replace('\n', ' ').Trim();
                                if (s.StartsWith("img ", StringComparison.OrdinalIgnoreCase))
                                {
                                    int pos = s.IndexOf(" src", StringComparison.OrdinalIgnoreCase);
                                    pos = s.IndexOfAny(new char[] { '\'', '"' }, pos);
                                    int pos2 = s.IndexOfAny(new char[] { '\'', '"' }, pos + 1);
                                    linkList.Add(s.Substring(pos + 1, pos2 - pos - 1));
                                }
                            }

                            List <Framework.Data.GeocacheImage> imgList = DataAccess.GetGeocacheImages(Core.GeocacheImages, gc.Code);
                            if (imgList != null)
                            {
                                foreach (Framework.Data.GeocacheImage img in imgList)
                                {
                                    if (!linkList.Contains(img.Url))
                                    {
                                        linkList.Add(img.Url);
                                    }
                                }
                            }

                            foreach (string link in linkList)
                            {
                                string fn         = string.Format("{0}.jpg", Guid.NewGuid().ToString("N"));
                                bool   skipInsert = false;
                                //if it fails, just ignore this image
                                try
                                {
                                    //check if link already is in database
                                    //if so, use this filename
                                    lock (_lockDBObject)
                                    {
                                        object o = _dbcon.ExecuteScalar(string.Format("select local_file from images where gccode='{0}' and org_url='{1}'", gc.Code.Replace("'", "''"), link.Replace("'", "''")));
                                        if (o != null && o.GetType() != typeof(DBNull))
                                        {
                                            fn         = (string)o;
                                            skipInsert = true;
                                        }
                                    }
                                    if (grabOnlyNew && skipInsert)
                                    {
                                        if (System.IO.File.Exists(System.IO.Path.Combine(fnp, fn)))
                                        {
                                            continue;
                                        }
                                    }
                                    using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                                    {
                                        wc.DownloadFile(link, tmp.Path);
                                        using (System.Drawing.Image img = System.Drawing.Image.FromFile(tmp.Path))
                                        {
                                            img.Save(System.IO.Path.Combine(fnp, fn), System.Drawing.Imaging.ImageFormat.Jpeg);
                                            if (!skipInsert)
                                            {
                                                lock (_lockDBObject)
                                                {
                                                    _dbcon.ExecuteNonQuery(string.Format("insert into images (gccode, org_url, local_file) values ('{0}', '{1}', '{2}')", gc.Code.Replace("'", "''"), link.Replace("'", "''"), fn));
                                                }
                                            }
                                        }
                                    }
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                    catch
                    {
                    }

                    gc = null;
                    lock (_gcList)
                    {
                        if (_gcList.Count > 0)
                        {
                            gc = _gcList[0];
                            _gcList.RemoveAt(0);
                        }
                    }
                }
            }
        }
Exemple #37
0
        private void checkForUpdate(String localVersion)
        {
            try {
                if (Program.InDeveloperMode && File.Exists(tzdbFile))
                {
                    return;
                }

                log.Debug("Checking for new timezone database...");
                String nodatimeURL      = "http://nodatime.org/tzdb/latest.txt";
                String html             = "";
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.Headers.Add("user-agent", Settings.Instance.Proxy.BrowserUserAgent);
                try {
                    html = wc.DownloadString(nodatimeURL);
                } catch (System.Exception ex) {
                    log.Error("Failed to get latest NodaTime db version.");
                    OGCSexception.Analyse(ex);
                    return;
                }

                if (string.IsNullOrEmpty(html))
                {
                    log.Warn("Empty response from " + nodatimeURL);
                }
                else
                {
                    html = html.TrimEnd('\r', '\n');
                    if (html.EndsWith(localVersion + ".nzd"))
                    {
                        log.Debug("Already have latest TZDB version.");
                    }
                    else
                    {
                        Regex           rgx     = new Regex(@"https*:.*/tzdb(.*)\.nzd$", RegexOptions.IgnoreCase);
                        MatchCollection matches = rgx.Matches(html);
                        if (matches.Count > 0)
                        {
                            String remoteVersion = matches[0].Result("$1");
                            if (string.Compare(localVersion, remoteVersion, System.StringComparison.InvariantCultureIgnoreCase) < 0)
                            {
                                log.Debug("There is a new version " + remoteVersion);
                                try {
                                    wc.DownloadFile(html, tzdbFile);
                                    log.Debug("New TZDB version downloaded - disposing of reference to old db data.");
                                    instance = null;
                                } catch (System.Exception ex) {
                                    log.Error("Failed to download new TZDB database from " + html);
                                    OGCSexception.Analyse(ex);
                                }
                            }
                        }
                        else
                        {
                            log.Warn("Regex to extract latest version is no longer working!");
                        }
                    }
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse("Could not check for timezone data update.", ex);
            }
        }
Exemple #38
0
 void demoButton_Click(object sender, EventArgs e)
 {
     try
     {
         if (Commons.IsNullOrEmpty(dxErrorProvider1, this.mailGroupControl.Controls))
         {
             return;
         }
         else
         {
             dxErrorProvider1.ClearErrors();
         }
         if (!Mail.IsAddressValid(this.mailTextEdit.Text))
         {
             dxErrorProvider1.SetError(this.mailTextEdit, L.MailGecersiz);
             return;
         }
         string mesaj = BAYMYO.UI.FileIO.ReadText(Commons.AppFilePath + "DL.dat")
                        .Replace("{COMPANY}", firmaAdiTextEdit.Text.Trim())
                        .Replace("{PHONE}", telefonTextEdit.Text)
                        .Replace("{MAIL}", mailTextEdit.Text)
                        .Replace("{VK}", validateKeyText.Text)
                        .Replace("{PV}", productVersionText.Text);
         Commons.Loading("License downloading .. .");
         Application.DoEvents();
         using (System.Net.WebClient cln = new System.Net.WebClient())
         {
             System.IO.Stream s          = cln.OpenRead(string.Format("http://service.baymyo.com/license.ashx?key={0}&v={1}", validateKeyText.Text, productVersionText.Text));
             bool             baymyoMail = Mail.SendBaymyo(this.mailTextEdit.Text, this.firmaAdiTextEdit.Text, "Demo License! Easy Supply Application.", mesaj + "<br/><br/> * Aynı mail SonayNet'de gitti!");
             bool             sonayMail  = Mail.SendSonay(this.mailTextEdit.Text, this.firmaAdiTextEdit.Text, "Demo License! Easy Supply Application.", mesaj + "<br/><br/> * Aynı mail baymyo yazılma'da gitti!");
             if ((baymyoMail || sonayMail) & s != null)
             {
                 this.telefonTextEdit.Text  = string.Empty;
                 this.firmaAdiTextEdit.Text = string.Empty;
                 this.mailTextEdit.Text     = string.Empty;
                 if (!System.IO.File.Exists(Commons.LicenseKeyFile))
                 {
                     BAYMYO.UI.FileIO.CreateDirectory(Commons.FolderPath);
                     cln.DownloadFile(string.Format("http://service.baymyo.com/keys/{0}-{1}.zip", validateKeyText.Text, productVersionText.Text.Replace(".", "-")), Commons.LicenseKeyFile);
                     Commons.IsLicenseLoad = true;
                     if (Commons.ValidateApplication())
                     {
                         this.DialogResult = DialogResult.OK;
                     }
                     else
                     {
                         MessageBox.Show(L.LisansGecersiz, "License Warning");
                     }
                 }
                 else
                 {
                     MessageBox.Show("Şuan sisteminizde bir adet lisans dosyası bulunmaktadır.", "Info");
                 }
             }
             else
             {
                 MessageBox.Show("Lisans dosyası indirilemiyor lütfen internet bağlantınızı yada proxy ayarlarınızı kontrol ediniz.", "Warning");
             }
         }
     }
     catch (Exception)
     {
         MessageBox.Show(Commons.GetErrorCode("FTL", 4) + " DEMO LICENSE ERROR!", "Warning");
     }
     finally
     {
         Commons.Loaded();
     }
 }
Exemple #39
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList(0, boundary);

            int zoom = -1;

            DA.GetData(1, ref zoom);

            string filePath = "";

            DA.GetData(2, ref filePath);
            if (!filePath.EndsWith(@"\"))
            {
                filePath = filePath + @"\";
            }

            string prefix = "";

            DA.GetData(3, ref prefix);
            if (prefix == "")
            {
                prefix = slippySource;
            }

            string URL = slippyURL;
            //DA.GetData<string>(4, ref URL);

            string userAgent = "";

            DA.GetData(4, ref userAgent);

            bool run = false;

            DA.GetData <bool>("Run", ref run);

            GH_Structure <GH_String>    mapList  = new GH_Structure <GH_String>();
            GH_Structure <GH_Rectangle> imgFrame = new GH_Structure <GH_Rectangle>();
            GH_Structure <GH_String>    tCount   = new GH_Structure <GH_String>();


            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path                = new GH_Path(i);
                int     tileTotalCount      = 0;
                int     tileDownloadedCount = 0;


                ///Get image frame for given boundary and  make sure it's valid
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = filePath + prefix + "_" + i + ".jpg";

                ///location of final image file
                mapList.Append(new GH_String(imgPath), path);

                ///create cache folder for images
                string        cacheLoc       = filePath + @"HeronCache\";
                List <string> cachefilePaths = new List <string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                ///tile bounding box array
                List <Point3d> boxPtList = new List <Point3d>();

                ///get the tile coordinates for all tiles within boundary
                var ranges = Convert.GetTileRange(boundaryBox, zoom);
                List <List <int> > tileList = new List <List <int> >();
                var x_range = ranges.XRange;
                var y_range = ranges.YRange;

                if (x_range.Length > 100 || y_range.Length > 100)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                    return;
                }

                ///cycle through tiles to get bounding box
                for (int y = (int)y_range.Min; y <= y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                    {
                        ///add bounding box of tile to list
                        boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList());
                        cachefilePaths.Add(cacheLoc + slippySource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg");
                        tileTotalCount = tileTotalCount + 1;
                    }
                }

                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                ///bounding box of tile boundaries
                BoundingBox bbox = new BoundingBox(boxPtList);

                var rect = BBoxToRect(bbox);
                imgFrame.Append(new GH_Rectangle(rect), path);

                AddPreviewItem(imgPath, boundary[i], rect);

                ///tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                                         + x_range[0].ToString()
                                         + y_range[0].ToString()
                                         + x_range[1].ToString()
                                         + y_range[1].ToString();

                ///check if the existing final image already covers the boundary.
                ///if so, no need to download more or reassemble the cached tiles.
                if ((TileCacheMeta == tileRangeString) && Convert.CheckCacheImagesExist(cachefilePaths))
                {
                    if (File.Exists(imgPath))
                    {
                        using (Bitmap imageT = new Bitmap(imgPath))
                        {
                            ///getting commments currently only working for JPG
                            ///TODO: get this to work for any image type or
                            ///find another way to check if the cached image covers the boundary.
                            string imgComment = imageT.GetCommentsFromJPG();

                            imageT.Dispose();

                            ///check to see if tilerange in comments matches current tilerange
                            if (imgComment == (slippySource.Replace(" ", "") + tileRangeString))
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing image.");
                                continue;
                            }
                        }
                    }
                }



                ///Query Slippy URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap
                ///API to query


                ///Do the work of assembling image
                ///setup final image container bitmap
                int    fImageW    = ((int)x_range.Length + 1) * 256;
                int    fImageH    = ((int)y_range.Length + 1) * 256;
                Bitmap finalImage = new Bitmap(fImageW, fImageH);


                int imgPosW = 0;
                int imgPosH = 0;

                if (run == true)
                {
                    using (Graphics g = Graphics.FromImage(finalImage))
                    {
                        g.Clear(Color.Black);
                        for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                        {
                            for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                            {
                                //create tileCache name
                                string tileCache    = slippySource.Replace(" ", "") + zoom + x + y + ".jpg";
                                string tileCacheLoc = cacheLoc + tileCache;

                                //check cache folder to see if tile image exists locally
                                if (File.Exists(tileCacheLoc))
                                {
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                    ///add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256);
                                    tmpImage.Dispose();
                                }

                                else
                                {
                                    tileList.Add(new List <int> {
                                        zoom, y, x
                                    });
                                    string urlAuth = Convert.GetZoomURL(x, y, zoom, slippyURL);

                                    System.Net.WebClient client = new System.Net.WebClient();

                                    ///insert header if required
                                    client.Headers.Add("user-agent", userAgent);

                                    client.DownloadFile(urlAuth, tileCacheLoc);
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                    client.Dispose();

                                    //add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256);
                                    tmpImage.Dispose();
                                    tileDownloadedCount = tileDownloadedCount + 1;
                                }

                                //increment x insert position, goes left to right
                                imgPosW++;
                            }
                            //increment y insert position, goes top to bottom
                            imgPosH++;
                            imgPosW = 0;
                        }
                        //garbage collection
                        g.Dispose();

                        //add tile range meta data to image comments
                        finalImage.AddCommentsToJPG(slippySource.Replace(" ", "") + tileRangeString);

                        //save the image
                        finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }

                //garbage collection
                finalImage.Dispose();


                //add to tile count total
                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;
            }


            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            DA.SetDataList(3, "copyright Slippy");
        }
Exemple #40
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>(0, boundary);

            int zoom = -1;

            DA.GetData <int>(1, ref zoom);

            string filePath = "";

            DA.GetData <string>(2, ref filePath);
            if (!filePath.EndsWith(@"\"))
            {
                filePath = filePath + @"\";
            }

            string prefix = "";

            DA.GetData <string>(3, ref prefix);
            if (prefix == "")
            {
                prefix = mbSource;
            }

            string URL = mbURL;
            //DA.GetData<string>(4, ref URL);


            string mbToken = "";

            DA.GetData <string>(4, ref mbToken);
            if (mbToken == "")
            {
                string hmbToken = System.Environment.GetEnvironmentVariable("HERONMAPBOXTOKEN");
                if (hmbToken != null)
                {
                    mbToken = hmbToken;
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using Mapbox token stored in Environment Variable HERONMAPBOXTOKEN.");
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Mapbox token is specified.  Please get a valid token from mapbox.com");
                    return;
                }
            }

            bool run = false;

            DA.GetData <bool>("Run", ref run);

            GH_Structure <GH_String> mapList  = new GH_Structure <GH_String>();
            GH_Structure <GH_Curve>  imgFrame = new GH_Structure <GH_Curve>();
            GH_Structure <GH_String> tCount   = new GH_Structure <GH_String>();
            GH_Structure <GH_Mesh>   tMesh    = new GH_Structure <GH_Mesh>();

            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path                = new GH_Path(i);
                int     tileTotalCount      = 0;
                int     tileDownloadedCount = 0;

                ///Get image frame for given boundary
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = filePath + prefix + "_" + i + ".png";

                //location of final image file
                mapList.Append(new GH_String(imgPath), path);

                //create cache folder for images
                string        cacheLoc       = filePath + @"HeronCache\";
                List <string> cachefilePaths = new List <string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                //tile bounding box array
                List <Point3d> boxPtList = new List <Point3d>();


                //get the tile coordinates for all tiles within boundary
                var ranges = Convert.GetTileRange(boundaryBox, zoom);
                List <List <int> > tileList = new List <List <int> >();
                var x_range = ranges.XRange;
                var y_range = ranges.YRange;

                if (x_range.Length > 100 || y_range.Length > 100)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                    return;
                }

                //cycle through tiles to get bounding box
                for (int y = (int)y_range.Min; y <= y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                    {
                        //add bounding box of tile to list
                        boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList());
                        cachefilePaths.Add(cacheLoc + mbSource.Replace(" ", "") + zoom + x + y + ".png");
                        tileTotalCount = tileTotalCount + 1;
                    }
                }

                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //bounding box of tile boundaries
                BoundingBox bboxPts = new BoundingBox(boxPtList);

                //convert bounding box to polyline
                List <Point3d> imageCorners = bboxPts.GetCorners().ToList();
                imageCorners.Add(imageCorners[0]);
                imgFrame.Append(new GH_Curve(new Rhino.Geometry.Polyline(imageCorners).ToNurbsCurve()), path);

                //tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                                         + x_range[0].ToString()
                                         + y_range[0].ToString()
                                         + x_range[1].ToString()
                                         + y_range[1].ToString();

                //check if the existing final image already covers the boundary.
                //if so, no need to download more or reassemble the cached tiles.
                ///temporarily disable until how to tag images with meta data is figured out

                /*
                 * if (TileCacheMeta == tileRangeString && Convert.CheckCacheImagesExist(cachefilePaths))
                 * {
                 *  if (File.Exists(imgPath))
                 *  {
                 *      using (Bitmap imageT = new Bitmap(imgPath))
                 *      {
                 *          //System.Drawing.Imaging.PropertyItem prop = imageT.GetPropertyItem(40092);
                 *          //string imgComment = Encoding.Unicode.GetString(prop.Value);
                 *          string imgComment = imageT.GetCommentsFromImage();
                 *          //AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, imgComment);
                 *          imageT.Dispose();
                 *          //check to see if tilerange in comments matches current tilerange
                 *          if (imgComment == (mbSource.Replace(" ", "") + tileRangeString))
                 *          {
                 *              AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing topo image.");
                 *
                 *              Mesh eMesh = TopoMeshFromImage(imgPath, boundaryBox, zoom);
                 *              tMesh.Append(new GH_Mesh(eMesh), path);
                 *              continue;
                 *          }
                 *
                 *      }
                 *
                 *  }
                 *
                 * }
                 */


                ///Query Mapbox URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap

                ///API to query
                ///string mbURL = "https://api.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}@2x.pngraw?access_token=" + mbToken;
                string mbURLauth = mbURL + mbToken;


                ///Do the work of assembling image
                ///setup final image container bitmap
                int    fImageW    = ((int)x_range.Length + 1) * 512;
                int    fImageH    = ((int)y_range.Length + 1) * 512;
                Bitmap finalImage = new Bitmap(fImageW, fImageH, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                int imgPosW = 0;
                int imgPosH = 0;

                if (run == true)
                {
                    using (Graphics g = Graphics.FromImage(finalImage))
                    {
                        g.Clear(Color.Black);
                        for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                        {
                            for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                            {
                                //create tileCache name
                                string tileCache    = mbSource.Replace(" ", "") + zoom + x + y + ".png";
                                string tileCahceLoc = cacheLoc + tileCache;

                                //check cache folder to see if tile image exists locally
                                if (File.Exists(tileCahceLoc))
                                {
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCahceLoc));
                                    //add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                    tmpImage.Dispose();
                                }

                                else
                                {
                                    tileList.Add(new List <int> {
                                        zoom, y, x
                                    });
                                    string urlAuth = Convert.GetZoomURL(x, y, zoom, mbURLauth);
                                    System.Net.WebClient client = new System.Net.WebClient();
                                    client.DownloadFile(urlAuth, tileCahceLoc);
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCahceLoc));
                                    client.Dispose();

                                    //add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                    tmpImage.Dispose();
                                    tileDownloadedCount = tileDownloadedCount + 1;
                                }

                                //increment x insert position, goes left to right
                                imgPosW++;
                            }
                            //increment y insert position, goes top to bottom
                            imgPosH++;
                            imgPosW = 0;
                        }
                        //garbage collection
                        g.Dispose();

                        //add tile range meta data to image comments
                        finalImage.AddCommentsToPNG(mbSource.Replace(" ", "") + tileRangeString);

                        //save out assembled image
                        finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Png);
                    }
                }

                //garbage collection
                finalImage.Dispose();

                //add to tile count total
                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);


                Mesh nMesh = TopoMeshFromImage(imgPath, boundaryBox, zoom);

                //mesh.Flip(true, true, true);
                tMesh.Append(new GH_Mesh(nMesh), path);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;
            }

            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            DA.SetDataTree(3, tMesh);
            DA.SetDataList(4, "copyright Mapbox");
        }
Exemple #41
0
        /// <summary>
        /// 下载6分钟内的弹幕,返回弹幕列表
        /// </summary>
        /// <param name="avid">稿件avID</param>
        /// <param name="cid">视频CID</param>
        /// <param name="segmentIndex">分包,每6分钟一包</param>
        /// <returns></returns>
        public static List <BiliDanmaku> GetDanmakuProto(long avid, long cid, int segmentIndex)
        {
            string url = $"https://api.bilibili.com/x/v2/dm/web/seg.so?type=1&oid={cid}&pid={avid}&segment_index={segmentIndex}";
            //string referer = "https://www.bilibili.com";

            string directory = Path.Combine(Storage.StorageManager.GetDanmaku(), $"{cid}");
            string filePath  = Path.Combine(directory, $"{segmentIndex}.proto");

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            try
            {
                System.Net.WebClient mywebclient = new System.Net.WebClient();
                mywebclient.DownloadFile(url, filePath);
            }
            catch (Exception e)
            {
                Utils.Debugging.Console.PrintLine("GetDanmakuProto()发生异常: {0}", e);
                //Logging.LogManager.Error(e);
            }

            var danmakuList = new List <BiliDanmaku>();

            try
            {
                using (var input = File.OpenRead(filePath))
                {
                    DmSegMobileReply danmakus = DmSegMobileReply.Parser.ParseFrom(input);
                    if (danmakus == null || danmakus.Elems == null)
                    {
                        return(danmakuList);
                    }

                    foreach (var dm in danmakus.Elems)
                    {
                        var danmaku = new BiliDanmaku
                        {
                            Id       = dm.Id,
                            Progress = dm.Progress,
                            Mode     = dm.Mode,
                            Fontsize = dm.Fontsize,
                            Color    = dm.Color,
                            MidHash  = dm.MidHash,
                            Content  = dm.Content,
                            Ctime    = dm.Ctime,
                            Weight   = dm.Weight,
                            //Action = dm.Action,
                            Pool = dm.Pool
                        };
                        danmakuList.Add(danmaku);
                    }
                }
            }
            catch (Exception e)
            {
                Utils.Debugging.Console.PrintLine("GetDanmakuProto()发生异常: {0}", e);
                //Logging.LogManager.Error(e);
                return(null);
            }

            return(danmakuList);
        }
Exemple #42
0
        public void check_update()
        {
            string checkforupdates = PCS.IniReadValue("main", "checkforupdates");
            string lastupdatecheck = PCS.IniReadValue("main", "lastupdatecheck");

            DateTime now = DateTime.Now;
            DateTime dt;

            if (DateTime.TryParseExact(lastupdatecheck, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
            {
            }
            else
            {
                dt = DateTime.Now;
                PCS.IniWriteValue("main", "lastupdatecheck", now.ToString("dd/MM/yyyy"));
            }
            //DateTime dt = DateTime.ParseExact(lastupdatecheck, "dd/MM/yyyy", CultureInfo.InvariantCulture);


            if (checkforupdates == "true" && (now - dt).TotalDays > 30)
            {
                if (PCS.CheckForInternetConnection() == true)
                {
                    using (System.Net.WebClient myWebClient = new System.Net.WebClient())
                    {
                        myWebClient.DownloadFile("http://www.pcstarters.net/pcsm/update/downloadsettings.ini", "settings\\downloadsettingsnew.ini");
                    }
                }

                string latestversion = PCS.IniReadValue("main", "version");


                if (Version != latestversion && PCS.CheckForInternetConnection() == true)
                {
                    PCS.IniWriteValue("main", "lastupdatecheck", now.ToString("dd/MM/yyyy"));

                    DialogResult dialogupdate = MessageBox.Show("Update Available! \n\nDo you want to download Performance Maintainer " + latestversion + " ?", "Performance Maintainer Update", MessageBoxButtons.YesNo);

                    if (dialogupdate == DialogResult.Yes)
                    {
                        string updatefile = PCS.IniReadValue("Main", "filename");
                        string updatelink = PCS.IniReadValue("Main", "link");

                        PCS.IniWriteValue("main", "filename", updatefile);
                        PCS.IniWriteValue("main", "link", updatelink);

                        Download     newupdate = new Download("main");
                        DialogResult dlg       = newupdate.ShowDialog(this);

                        if (dlg == DialogResult.OK && File.Exists(updatefile))
                        {
                            Process pcsmnew = new Process();
                            pcsmnew.StartInfo.FileName  = "pcsmnew.exe";
                            pcsmnew.StartInfo.Arguments = "";
                            pcsmnew.Start();
                            this.Close();
                        }
                    }
                }
            }
        }
Exemple #43
0
        /// <summary>
        /// Update function that will compare the current program assembly version against a web document containing
        /// the most updated version number. If the
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void check_update_button_Click(object sender, EventArgs e)
        {
            var currentVersion = typeof(Options).Assembly.GetName().Version.ToString();

            System.Net.WebClient wc = new System.Net.WebClient();
            wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
            string webVersion = wc.DownloadString(@"https://raw.githubusercontent.com/taylorflatt/windows-shutdown-timer/master/VERSION").TrimEnd('\n');

            Array webV = webVersion.Split('.');
            Array curV = currentVersion.Split('.');

            // Note: The user's version number should never be higher than the release version. So I don't even consider that case.
            for (int i = 0; i < 4; i++)
            {
                if (Convert.ToInt32(webV.GetValue(i)) > Convert.ToInt32(curV.GetValue(i)))
                {
                    DialogResult result = MessageBox.Show("The current version is: " + currentVersion + " and the newest version is " + webVersion + ". Would you " +
                                                          "like to download the newest version?", "New Version Found!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                    if (result == DialogResult.Yes)
                    {
                        string exeName            = typeof(Options).Assembly.GetName().ToString();
                        string newFilePath        = AppDomain.CurrentDomain.BaseDirectory + "WindowsShutdownTimer_v" + webVersion + ".exe"; // This should be distinct from old by version number.
                        string updatedAppLocation = "https://github.com/taylorflatt/windows-shutdown-timer/raw/master/WindowsShutdownTimer.exe";

                        try
                        {
                            wc.DownloadFile(new Uri(updatedAppLocation), newFilePath);

                            DialogResult close = MessageBox.Show("You have successfully updated to version " + webVersion + "! The new version was downloaded to the same directory as this " +
                                                                 "program. Would you like to close this program now?", "Update Completed!", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

                            if (close == DialogResult.Yes)
                            {
                                Application.Exit();
                            }
                            else
                            {
                                return;
                            }
                        }

                        catch
                        {
                            DialogResult error = MessageBox.Show("There was an error attempting to grab the latest update. Would you like to " +
                                                                 "retry or cancel?", "Error Downloading Update!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);

                            if (error == DialogResult.Retry)
                            {
                                check_update_button_Click(null, null);
                            }
                            else
                            {
                                return;
                            }
                        }
                    }

                    else
                    {
                        return;
                    }
                }
            }

            MessageBox.Show("The current version is: " + currentVersion + " and it is up to date!", "No New Update!", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Exemple #44
0
        internal static bool CheckVersion()
        {
            bool ret = false;

            try
            {
                //the webclient
                System.Net.WebClient myWebClient = new System.Net.WebClient();
                System.IO.Stream     updatestream;
                try
                {
                    // Download the update info file to the memory,
                    updatestream = myWebClient.OpenRead(REMOTE_URI + UPDATE_FILE);
                }
                catch (Exception ex)
                {
                    LogHelper.Write("Download update.xml", REMOTE_URI + UPDATE_FILE, ex, LogSeverity.Error);
                    return(ret);
                }

                // read and close the stream
                using (System.IO.StreamReader streamReader = new System.IO.StreamReader(updatestream, System.Text.Encoding.GetEncoding("GB2312")))
                {
                    string updateInfo = streamReader.ReadToEnd();
                    // if something was read
                    if (!string.IsNullOrEmpty(updateInfo))
                    {
                        LogHelper.Write("Johnny.Kaixin.WinUI.AutoUpdate.CheckVersion.updateInfo:", updateInfo, LogSeverity.Info);
                        string newVersion = JsonHelper.GetMid(updateInfo, "<Version Num = \"", "\"/>");
                        if (String.IsNullOrEmpty(newVersion))
                        {
                            return(ret);
                        }

                        if (CompareVersions(Assembly.GetExecutingAssembly().GetName().Version.ToString(), newVersion))
                        {
                            if (MessageBox.Show("检测到有新版本:" + newVersion + "\r\n是否退出进行升级?", MainConstants.MESSAGEBOX_CAPTION, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                            {
                                // assembly the parameter to be passed to the auto
                                // update program

                                // Download the auto update program to the application
                                // path, so you always have the last version runing
                                myWebClient.DownloadFile(REMOTE_URI + "AutoUpdate.exe", Application.StartupPath + "\\AutoUpdate.exe");
                                // Call the auto update program with all the parameters
                                System.Diagnostics.Process.Start(Application.StartupPath + "\\AutoUpdate.exe", System.Web.HttpUtility.UrlEncode(updateInfo));
                                // return true - auto update in progress
                                ret = true;
                            }
                            else
                            {
                                ret = false;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // if there is an error return true,
                // what means that the application
                // should be closed
                ret = true;
                // something went wrong...
                Program.ShowMessageBox("AutoUpdate", ex);
            }
            return(ret);
        }
        public SortableHelpElement(XmlNode source)
        {
            this.priority = source.Attributes.GetNamedItem("sort")?.InnerText;
            this.Title    = source.Attributes.GetNamedItem("title")?.InnerText;
            this.ToolTip  = source.Attributes.GetNamedItem("tooltip")?.InnerText;
            this.URL      = source.Attributes.GetNamedItem("url")?.InnerText;

            //Modal help items
            this.ModalTitle   = source.Attributes.GetNamedItem("modaltitle")?.InnerText;
            this.ModalIcon    = source.Attributes.GetNamedItem("modalicon")?.InnerText;
            this.ModalText    = source.InnerText;
            this.ResourceName = source.Attributes.GetNamedItem("resource")?.InnerText;
            this.ResourceMD5  = source.Attributes.GetNamedItem("md5")?.InnerText;

            string resourceSizeStr = source.Attributes.GetNamedItem("size")?.InnerText;

            if (resourceSizeStr != null)
            {
                this.ResourceSize = int.Parse(resourceSizeStr);
            }

            //Download resource if any
            if (ResourceName != null)
            {
                //Validate locally
                var localFile = Path.Combine(Utilities.GetLocalHelpResourcesDirectory(), ResourceName);
                if (!File.Exists(localFile))
                {
                    //Download
                    foreach (var staticendpoint in OnlineContent.StaticFilesBaseEndpoints)
                    {
                        var fullURL = staticendpoint + "dynamichelp/resources/" + ResourceName;

                        try
                        {
                            using var wc = new System.Net.WebClient();

                            Log.Information("Downloading dynamic help image asset: " + fullURL);
                            wc.DownloadFile(fullURL, localFile);

                            var md5OfDownloadedFile = Utilities.CalculateMD5(localFile);
                            if (md5OfDownloadedFile != ResourceMD5)
                            {
                                Log.Error($"Downloaded asset has wrong hash. Expected: {ResourceMD5}, got: {md5OfDownloadedFile}");
                                File.Delete(localFile);
                            }
                            else
                            {
                                Log.Information("Downloaded resource passed md5 check");
                            }
                        }
                        catch (Exception e)
                        {
                            Log.Error("Error downloading dynamic help asset from endpoint " + fullURL);
                        }
                    }
                }
            }

            foreach (XmlNode v in source.ChildNodes)
            {
                if (v.NodeType == XmlNodeType.Element)
                {
                    Children.Add(new SortableHelpElement(v));
                }
            }
        }
Exemple #46
0
        public string download_and_install(string DriverPath)
        {
            string extract_to = DriverPath;
            object path;

            //get value of chrome from registry
            path = Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null);


            if (path != null)
            {
                //read exact version of chrome browser from registry value
                string chrome_browser_vers;
                chrome_browser_vers = FileVersionInfo.GetVersionInfo(path.ToString()).FileVersion;

                //get major version of chrome browser
                int    pos           = chrome_browser_vers.LastIndexOf('.') + 1;
                string major_browser = chrome_browser_vers.Substring(0, pos - 1);

                //read version of chrome driver associated with major browser version
                System.Net.WebClient wc       = new System.Net.WebClient();
                string associated_driver_vers = wc.DownloadString("https://chromedriver.storage.googleapis.com/LATEST_RELEASE_" + major_browser);

                //check if associated browser version is already installed
                bool download = true;
                if (System.IO.File.Exists(extract_to + "\\chromedriver.exe"))
                {
                    System.IO.File.Delete(extract_to + "\\chromedriver.exe");

                    //downloaded chromedriver has no version info. In the future, save file with version # and compare version of currently installed driver
                    //string current_driver_vers = DriverVersion(extract_to + "\\chromedriver.exe");
                    //if (current_driver_vers == associated_driver_vers)
                    //{
                    //  download = false;
                    //}
                }

                if (download == true)
                {
                    string fname   = associated_driver_vers + "/chromedriver_win32.zip";
                    var    jsonstr = wc.DownloadString("https://www.googleapis.com/storage/v1/b/chromedriver/o");

                    //get mediaLink from JSON object
                    JObject json        = JObject.Parse(jsonstr);
                    var     media_list  = (from p in json["items"] select(string) p["mediaLink"]).ToList();
                    var     names_list  = (from p in json["items"] select(string) p["name"]).ToList();
                    int     media_index = names_list.FindIndex(a => a == fname);
                    string  mediaLink   = media_list[media_index];

                    //download associated driver from respective media link
                    string remoteUri   = mediaLink;
                    string zipfileName = extract_to + "\\chromedriver_win32.zip";

                    // Create a new WebClient instance.
                    using (System.Net.WebClient myWebClient = new System.Net.WebClient())
                    {
                        string myStringWebResource = remoteUri;
                        // Download the Web resource and save it into the current filesystem folder.
                        myWebClient.DownloadFile(myStringWebResource, zipfileName);
                    }



                    ZipFile.ExtractToDirectory(zipfileName, extract_to);
                    System.IO.File.Delete(zipfileName);
                }


                return(extract_to);
            }
            else
            {
                throw new System.Exception("Chrome is not installed on this machine.");
            }
        }
        public ActionResult DownLoadPosters(int id)
        {
            try
            {
                ViewData["CustomerName"] = CustomerName();
                ViewData["WeixinUser"]   = WeiXinUser();
                var customerId = CustomerId().ToString();
                LogManager.GetLogger().Info("customerId:" + customerId);

                var productLine = ProductLine.FindById(id);

                ViewData["ProductLine"] = productLine;

                var imgUrl1 = (!string.IsNullOrEmpty(productLine.WeChatAdUrl)
                    ? (ConstValue.SysConfig.BossImgUrl + productLine.WeChatAdUrl.Split(',')[0])
                    : "");
                if (!string.IsNullOrEmpty(imgUrl1))
                {
                    System.Net.WebClient myWebClient = new System.Net.WebClient();
                    //将头像保存到服务器
                    var virPath  = "/Uploads/temp/";
                    var fileName = Guid.NewGuid().ToString("N") + ".png";
                    myWebClient.DownloadFile(imgUrl1, System.Web.HttpContext.Current.Request.PhysicalApplicationPath + virPath + fileName);
                    ViewData["ImgUrl1"] = virPath + fileName;
                }
                else
                {
                    ViewData["ImgUrl1"] = "";
                }

                var url = ConstValue.SysConfig.ImgUrl + "/Home/Product/Index?lineId=" + id + "&uId=" + CustomerId();
                LogManager.GetLogger().Info("DownLoadPosters-Url:" + url);

                #region 生成二维码

                var content = url;
                var size    =
                    Convert.ToInt32(string.IsNullOrEmpty(Request.QueryString["size"])
                        ? "200"
                        : Request.QueryString["size"]);
                var border =
                    Convert.ToInt32(string.IsNullOrEmpty(Request.QueryString["border"])
                        ? "10"
                        : Request.QueryString["border"]);

                var image = QRCode.CreateQRCode(content,
                                                QRCodeEncoder.ENCODE_MODE.BYTE,
                                                QRCodeEncoder.ERROR_CORRECTION.M,
                                                0,
                                                5,
                                                size,
                                                border);
                //将图片输出到页面
                var ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                var imgUrl  = "";
                var strPath = Server.MapPath("~/Uploads");
                //保存图片到目录
                if (Directory.Exists(strPath))
                {
                    //文件名称
                    var guid = Guid.NewGuid().ToString().Replace("-", "") + ".png";
                    image.Save(strPath + "/" + guid, System.Drawing.Imaging.ImageFormat.Png);

                    imgUrl = "/Uploads/" + guid;
                }
                else
                {
                    //当前目录不存在,则创建
                    Directory.CreateDirectory(strPath);
                }
                ms.Close();
                ms = null;
                image.Dispose();
                image = null;

                ViewData["ImgUrl"] = imgUrl;

                #endregion
            }
            catch (Exception ex)
            {
                LogManager.GetLogger().Error(ex);
            }

            return(View());
        }
Exemple #48
0
        private static CompilerResults CompileDll()
        {
            Console.WriteLine("Generating new DLL");
            var csprojPath = @"..\BattleSharpController\";

            if (!File.Exists(csprojPath + "BattleSharpController.csproj"))
            {
                Console.WriteLine("Getting latest version info from Github");
                System.Net.WebClient wc = new System.Net.WebClient();
                string hash             = wc.DownloadString("https://github.com/shalzuth/BattleSharp");
                string hashSearch       = "\"commit-tease-sha\" href=\"/shalzuth/BattleSharp/commit/";
                hash = hash.Substring(hash.IndexOf(hashSearch) + hashSearch.Length, 7);
                string hashFile = @".\BattleSharp-master\hash.txt";
                csprojPath = @".\BattleSharp-master\BattleSharpController";
                if (File.Exists(hashFile))
                {
                    if (hash != File.ReadAllText(hashFile))
                    {
                        Console.WriteLine("Later version exists, removing existing version");
                        Directory.Delete(@".\BattleSharp-master", true);
                    }
                }
                if (!File.Exists(hashFile))
                {
                    Console.WriteLine("Downloading latest version");
                    wc.DownloadFile("https://github.com/shalzuth/BattleSharp/archive/master.zip", "BattleSharpSource.zip");
                    using (var archive = ZipFile.OpenRead("BattleSharpSource.zip"))
                    {
                        archive.ExtractToDirectory(@".\");
                    }
                    File.WriteAllText(hashFile, hash);
                }
            }
            var randString = "aa" + Guid.NewGuid().ToString().Substring(0, 8);

            var codeProvider       = new CSharpCodeProvider();
            var compilerParameters = new CompilerParameters
            {
                GenerateExecutable = false,
#if DEBUG
                IncludeDebugInformation = true,
#endif
                GenerateInMemory = false,
                OutputAssembly   = randString + ".dll"
            };

            compilerParameters.ReferencedAssemblies.Add("mscorlib.dll");
            compilerParameters.ReferencedAssemblies.Add(gamePath + "System.dll");
            compilerParameters.ReferencedAssemblies.Add(gamePath + "System.Core.dll"); // not sure which to use... prefer Linq...
            compilerParameters.ReferencedAssemblies.Add("System.Drawing.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            compilerParameters.ReferencedAssemblies.Add(gamePath + "UnityEngine.dll");
            compilerParameters.ReferencedAssemblies.Add(gamePath + "UnityEngine.UI.dll");
            compilerParameters.ReferencedAssemblies.Add(gamePath + "UnityContent.dll");
            compilerParameters.ReferencedAssemblies.Add(gamePath + "MergedShared.dll");
            compilerParameters.ReferencedAssemblies.Add(gamePath + "MergedUnity.dll");

            var sourceFiles = Directory.GetFiles(csprojPath, "*.cs", SearchOption.AllDirectories);
            var sources     = new List <String>();

            foreach (var sourceFile in sourceFiles)
            {
                var source = File.ReadAllText(sourceFile);
                source = source.Replace("BattleSharpControllerGenericNamespace", randString);
                sources.Add(source);
            }
            Console.WriteLine("Compiling DLL");
            var result = codeProvider.CompileAssemblyFromSource(compilerParameters, sources.ToArray());

            return(result);
        }
Exemple #49
0
        /// <summary>
        /// Update WebUI with version from given url
        /// </summary>
        /// <param name="url">direct link to version you want to install</param>
        /// <returns></returns>
        internal object WebUIUpdate(string url, string channel, string version)
        {
            //list all files from root /webui/ and all directories
            string[] files       = Directory.GetFiles("webui");
            string[] directories = Directory.GetDirectories("webui");

            try
            {
                //download latest version
                var client = new System.Net.WebClient();
                client.Headers.Add("User-Agent", "shokoserver");
                client.DownloadFile(url, "webui\\latest.zip");

                //create 'old' dictionary
                if (!Directory.Exists("webui\\old"))
                {
                    System.IO.Directory.CreateDirectory("webui\\old");
                }
                try
                {
                    //move all directories and files to 'old' folder as fallback recovery
                    foreach (string dir in directories)
                    {
                        if (Directory.Exists(dir) && dir != "webui\\old")
                        {
                            string n_dir = dir.Replace("webui", "webui\\old");
                            Directory.Move(dir, n_dir);
                        }
                    }
                    foreach (string file in files)
                    {
                        if (File.Exists(file))
                        {
                            string n_file = file.Replace("webui", "webui\\old");
                            File.Move(file, n_file);
                        }
                    }

                    try
                    {
                        //extract latest webui
                        System.IO.Compression.ZipFile.ExtractToDirectory("webui\\latest.zip", "webui");

                        //clean because we already have working updated webui
                        Directory.Delete("webui\\old", true);
                        File.Delete("webui\\latest.zip");

                        //save version type>version that was installed successful
                        if (File.Exists("webui\\index.ver"))
                        {
                            File.Delete("webui\\index.ver");
                        }
                        File.AppendAllText("webui\\index.ver", channel + ">" + version);

                        return(APIStatus.statusOK());
                    }
                    catch
                    {
                        //when extracting latest.zip failes
                        return(new APIMessage(405, "MethodNotAllowed"));
                    }
                }
                catch
                {
                    //when moving files to 'old' folder failed
                    return(new APIMessage(423, "Locked"));
                }
            }
            catch
            {
                //when download failed
                return(new APIMessage(499, "download failed"));
            }
        }
Exemple #50
0
        /// <summary>
        /// 支付宝结算
        /// </summary>
        public override void ProcessMessage()
        {
            var listpbxx = DBVisitor.ExecuteTable(SqlLoad.GetFormat(SQ.HIS00002, InObject.WIDOUTTRADENO));

            LogUnit.Write(listpbxx.Rows.Count.ToString());
            if (listpbxx.Rows.Count > 0)
            {
                throw new Exception("商户订单号不能重复!");
            }

            #region //手机网页支付
            if (InObject.JIESUANLX == "1")
            {
                //支付宝网关地址
                string GATEWAY_NEW = "http://wappaygw.alipay.com/service/rest.htm?";
                ////////////////////////////////////////////调用授权接口alipay.wap.trade.create.direct获取授权码token////////////////////////////////////////////

                //返回格式
                string format = "xml";
                //必填,不需要修改

                //返回格式
                string v = "2.0";
                //必填,不需要修改

                if (string.IsNullOrEmpty(InObject.QINGQIUDH))
                {
                    throw new Exception("请求单号不能为空!");
                }
                //请求号
                string req_id = InObject.QINGQIUDH; //DateTime.Now.ToString("yyyyMMddHHmmss");
                //必填,须保证每次请求都是唯一

                //req_data详细信息
                if (string.IsNullOrEmpty(InObject.NOTIFYURL))
                {
                    throw new Exception("服务器异步通知页面路径不能为空!");
                }
                //服务器异步通知页面路径
                string notify_url = InObject.NOTIFYURL;//"http://商户网关地址/WS_WAP_PAYWAP-CSHARP-UTF-8/notify_url.aspx";
                //需http://格式的完整路径,不允许加?id=123这类自定义参数

                if (string.IsNullOrEmpty(InObject.CALLBACKURL))
                {
                    throw new Exception("页面跳转同步通知页面路径不能为空!");
                }
                //页面跳转同步通知页面路径
                string call_back_url = InObject.CALLBACKURL;//"http://127.0.0.1:64704/WS_WAP_PAYWAP-CSHARP-UTF-8/call_back_url.aspx";
                //需http://格式的完整路径,不允许加?id=123这类自定义参数

                if (string.IsNullOrEmpty(InObject.MERCHANTURL))
                {
                    throw new Exception("操作中断返回地址不能为空!");
                }
                //操作中断返回地址
                string merchant_url = InObject.MERCHANTURL;// "http://127.0.0.1:64704/WS_WAP_PAYWAP-CSHARP-UTF-8/xxxxx.aspx";
                //用户付款中途退出返回商户的地址。需http://格式的完整路径,不允许加?id=123这类自定义参数

                if (string.IsNullOrEmpty(InObject.WIDOUTTRADENO))
                {
                    throw new Exception("商户订单号不能为空!");
                }
                //商户订单号
                string out_trade_no = InObject.WIDOUTTRADENO;// WIDout_trade_no.Text.Trim();
                //商户网站订单系统中唯一订单号,必填

                if (string.IsNullOrEmpty(InObject.WIDSUBJECT))
                {
                    throw new Exception("订单名称不能为空!");
                }
                //订单名称
                string subject = InObject.WIDSUBJECT;//WIDsubject.Text.Trim();
                //必填

                if (string.IsNullOrEmpty(InObject.WIDTOTALFEE))
                {
                    throw new Exception("付款金额不能为空!");
                }
                //付款金额
                string total_fee = InObject.WIDTOTALFEE; //WIDtotal_fee.Text.Trim();
                //必填

                //请求业务参数详细
                string req_dataToken = "<direct_trade_create_req><notify_url>" + notify_url +
                                       "</notify_url><call_back_url>" + call_back_url +
                                       "</call_back_url><seller_account_name>" + Common.Alipay.Config.Seller_email +
                                       "</seller_account_name><out_trade_no>" + out_trade_no +
                                       "</out_trade_no><subject>" + subject +
                                       "</subject><total_fee>" + total_fee +
                                       "</total_fee><merchant_url>" + merchant_url +
                                       "</merchant_url></direct_trade_create_req>";
                //必填

                //把请求参数打包成数组
                Dictionary <string, string> sParaTempToken = new Dictionary <string, string>();
                sParaTempToken.Add("partner", Config.Partner);
                sParaTempToken.Add("_input_charset", Config.Input_charset.ToLower());
                sParaTempToken.Add("sec_id", Config.Sign_type.ToUpper());
                sParaTempToken.Add("service", "alipay.wap.trade.create.direct");
                sParaTempToken.Add("format", format);
                sParaTempToken.Add("v", v);
                sParaTempToken.Add("req_id", req_id);
                sParaTempToken.Add("req_data", req_dataToken);

                //建立请求
                string sHtmlTextToken = Submit.BuildRequest(GATEWAY_NEW, sParaTempToken);
                //URLDECODE返回的信息
                Encoding code = Encoding.GetEncoding(Config.Input_charset);
                sHtmlTextToken = System.Web.HttpUtility.UrlDecode(sHtmlTextToken, code);

                //解析远程模拟提交后返回的信息
                Dictionary <string, string> dicHtmlTextToken = Submit.ParseResponse(sHtmlTextToken);

                //获取token
                string request_token = dicHtmlTextToken["request_token"];


                ////////////////////////////////////////////根据授权码token调用交易接口alipay.wap.auth.authAndExecute////////////////////////////////////////////

                //业务详细
                string req_data = "<auth_and_execute_req><request_token>" + request_token + "</request_token></auth_and_execute_req>";
                //必填

                DBVisitor.ExecuteNonQuery(SqlLoad.GetFormat(SQ.HIS00001,
                                                            InObject.QINGQIUDH,     //请求单号
                                                            '1',                    //结算类型 1手机网页支付 2二维码扫描支付 3商户代扣
                                                            InObject.NOTIFYURL,     //服务器异步通知页面路径
                                                            InObject.CALLBACKURL,   //页面跳转同步通知页面路径
                                                            InObject.MERCHANTURL,   //操作中断返回地址)
                                                            InObject.WIDOUTTRADENO, //商户订单号
                                                            InObject.WIDSUBJECT,    //订单名称
                                                            InObject.WIDTOTALFEE,   //订单金额
                                                            InObject.WIDBODY,       //订单描述
                                                            InObject.OUTTIME,       //超时时间取值范围
                                                            "",                     //买家支付宝用户号
                                                            "",                     //买家支付宝帐号
                                                            "",                     //授权号
                                                            "",                     //协议号
                                                            "0",                    //结算状态 0未结算 1结算成功 2结算失败
                                                            request_token));

                //把请求参数打包成数组
                Dictionary <string, string> sParaTemp = new Dictionary <string, string>();
                sParaTemp.Add("partner", Config.Partner);
                sParaTemp.Add("_input_charset", Config.Input_charset.ToLower());
                sParaTemp.Add("sec_id", Config.Sign_type.ToUpper());
                sParaTemp.Add("service", "alipay.wap.auth.authAndExecute");
                sParaTemp.Add("format", format);
                sParaTemp.Add("v", v);
                sParaTemp.Add("req_data", req_data);

                //建立请求
                string sHtmlText = Submit.BuildRequest(GATEWAY_NEW, sParaTemp, "get", "确认");
                OutObject            = new ZHIFUBAOJS_OUT();
                OutObject.JIESUANURL = sHtmlText;
            }
            #endregion
            #region 二维码支付
            else if (InObject.JIESUANLX == "2")
            {
                if (string.IsNullOrEmpty(InObject.BASEINFO.FENYUANDM))
                {
                    throw new Exception("医院代码不能为空!");
                }
                if (string.IsNullOrEmpty(InObject.BASEINFO.CAOZUOYDM))
                {
                    throw new Exception("操作员代码不能为空!");
                }
                if (string.IsNullOrEmpty(InObject.BASEINFO.CAOZUOYXM))
                {
                    throw new Exception("操作员姓名不能为空!");
                }
                if (string.IsNullOrEmpty(InObject.JIUZHENKH))
                {
                    throw new Exception("就诊卡号不能为空!");
                }
                DataTable dt = DBVisitor.ExecuteTable(SqlLoad.GetFormat(SQ.HIS00006, InObject.BASEINFO.FENYUANDM));
                if (dt.Rows.Count <= 0)
                {
                    throw new Exception("查询不到医院代码为【" + InObject.BASEINFO.FENYUANDM + "】的医院信息");
                }
                var ddxx = DBVisitor.ExecuteTable(SqlLoad.GetFormat(SQ.HIS00002, InObject.WIDOUTTRADENO));
                if (ddxx.Rows.Count > 0)
                {
                    throw new Exception("已存在相同订单号的结算信息!");
                }
                if (string.IsNullOrEmpty(InObject.NOTIFYURL))
                {
                    throw new Exception("异步请求地址不能为空!");
                }
                //服务器异步通知页面路径
                string notify_url = ConfigurationManager.AppSettings["FWPTURL"] + "NotifyUrl2.aspx";//InObject.NOTIFYURL;
                //需http://格式的完整路径,不能加?id=123这类自定义参数
                //商户订单号
                string out_trade_no = InObject.WIDOUTTRADENO;// WIDout_trade_no.Text.Trim();
                //商户网站订单系统中唯一订单号,必填

                //订单名称
                string subject = InObject.WIDSUBJECT;// WIDsubject.Text.Trim();
                //必填

                //订单业务类型
                string product_code = "QR_CODE_OFFLINE";// WIDproduct_code.Text.Trim();
                //目前只支持QR_CODE_OFFLINE(二维码支付),必填

                //付款金额
                string total_fee = InObject.WIDTOTALFEE;// WIDtotal_fee.Text.Trim();
                //必填

                //卖家支付宝帐户
                string seller_email = dt.Rows[0]["SELLEREMAIL"].ToString(); //WIDseller_email.Text.Trim();
                //必填

                //订单描述
                string body = InObject.WIDBODY;

                //把请求参数打包成数组
                SortedDictionary <string, string> sParaTemp = new SortedDictionary <string, string>();
                sParaTemp.Add("partner", Config.Partner);
                sParaTemp.Add("_input_charset", Config.Input_charset.ToLower());
                sParaTemp.Add("service", "alipay.acquire.precreate");
                sParaTemp.Add("notify_url", notify_url);
                sParaTemp.Add("out_trade_no", out_trade_no);
                sParaTemp.Add("subject", subject);
                sParaTemp.Add("product_code", product_code);
                sParaTemp.Add("total_fee", total_fee);
                sParaTemp.Add("seller_email", seller_email);
                sParaTemp.Add("body", body);
                sParaTemp.Add("it_b_pay", InObject.OUTTIME);
                sParaTemp.Add("key", "rfk3sw6dlq28k2tijjj54le6lfhw73s4");//取余杭卫生局的key
                //将请求数据 插入数据库
                DBVisitor.ExecuteNonQuery(SqlLoad.GetFormat(SQ.HIS00001,
                                                            InObject.WIDOUTTRADENO,               //商户订单号
                                                            '2',                                  //结算类型 1手机网页支付 2二维码扫描支付 3商户代扣
                                                            InObject.NOTIFYURL,                   //服务器异步通知页面路径
                                                            "",                                   //页面跳转同步通知页面路径
                                                            "",                                   //操作中断返回地址)
                                                            InObject.WIDSUBJECT,                  //订单名称
                                                            InObject.WIDTOTALFEE,                 //订单金额
                                                            InObject.WIDBODY,                     //订单描述
                                                            InObject.OUTTIME,                     //超时时间取值范围
                                                            InObject.BUYERID,                     //买家支付宝用户号
                                                            InObject.BUYEREMAIL,                  //买家支付宝帐号
                                                            InObject.AUTHNO,                      //授权号
                                                            InObject.AGREENNO,                    //协议号
                                                            "0",                                  //结算状态 0未结算 1结算成功 2结算失败
                                                            "",
                                                            InObject.BASEINFO.FENYUANDM,          //分院代码
                                                            dt.Rows[0]["SELLEREMAIL"].ToString(), //收款帐号
                                                            InObject.BASEINFO.CAOZUOYXM,
                                                            InObject.BASEINFO.CAOZUOYDM,
                                                            "",                //身份证号
                                                            InObject.JIUZHENKH //就诊卡号
                                                            ));

                //建立请求
                string sHtmlText = Submit.BuildRequest(sParaTemp);
                //记录日志
                LogUnit.Write("JIESUANLX == 2###" + sHtmlText, "ZHIFUBAOJS");
                OutObject = new ZHIFUBAOJS_OUT();
                XmlDocument xmlDoc = new XmlDocument();
                try
                {
                    string PicUrl = "";
                    xmlDoc.LoadXml(sHtmlText);
                    XmlNodeList nodeList = xmlDoc.SelectSingleNode("alipay").ChildNodes;
                    foreach (XmlNode xn in nodeList)
                    {
                        //判断是否异常,如果返回异常 则抛出
                        //if (xn.Name == "is_success" && xn.InnerText == "F")
                        //{
                        //    throw new Exception("支付宝请求生成二维码失败!");
                        //}
                        if (xn.Name == "error")
                        {
                            throw new Exception(xn.InnerText);
                        }
                        if (xn.Name == "response")
                        {
                            XmlElement  xe      = (XmlElement)xn;
                            XmlNodeList subList = xe.ChildNodes;
                            foreach (XmlNode xmlNode in subList)
                            {
                                if (xmlNode.Name == "alipay")
                                {
                                    XmlElement  xemx      = (XmlElement)xmlNode;
                                    XmlNodeList submxList = xemx.ChildNodes;

                                    foreach (XmlNode mxnode in submxList)
                                    {
                                        if (mxnode.Name == "detail_error_code")
                                        {
                                            OutObject.ERRORCODE = mxnode.InnerText;
                                        }
                                        if (mxnode.Name == "detail_error_des")
                                        {
                                            OutObject.ERRORDES = mxnode.InnerText;
                                        }
                                        if (mxnode.Name == "big_pic_url")
                                        {
                                            //   OutObject.PICURL = mxnode.InnerText;
                                            PicUrl = mxnode.InnerText;
                                        }
                                        if (mxnode.Name == "out_trade_no")
                                        {
                                            OutObject.WIDOUTTRADENO = mxnode.InnerText;
                                        }
                                        if (mxnode.Name == "qr_code")
                                        {
                                            OutObject.QRCODE = mxnode.InnerText;
                                        }
                                    }
                                    try
                                    {//将二维码图片下载到服务平台本地
                                        var path = HostingEnvironment.ApplicationPhysicalPath + "ZFBImg\\";
                                        DeletePic(path);
                                        System.Net.WebClient webClient = new System.Net.WebClient();
                                        webClient.DownloadFile(PicUrl, path + OutObject.WIDOUTTRADENO + ".jpg");
                                        OutObject.PICLOCAL = OutObject.WIDOUTTRADENO + ".jpg";
                                    }
                                    catch
                                    {
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception exp)
                {
                    throw new Exception(exp.Message.ToString());
                }
            }
            #endregion
            #region 签约账户支付 商户代扣
            else if (InObject.JIESUANLX == "3")
            {
                if (string.IsNullOrEmpty(InObject.BASEINFO.FENYUANDM))
                {
                    throw new Exception("医院代码不能为空!");
                }
                if (string.IsNullOrEmpty(InObject.BASEINFO.CAOZUOYDM))
                {
                    throw new Exception("操作员代码不能为空!");
                }
                if (string.IsNullOrEmpty(InObject.BASEINFO.CAOZUOYXM))
                {
                    throw new Exception("操作员姓名不能为空!");
                }
                if (string.IsNullOrEmpty(InObject.JIUZHENKH))
                {
                    throw new Exception("就诊卡号不能为空!");
                }
                DataTable dt = DBVisitor.ExecuteTable(SqlLoad.GetFormat(SQ.HIS00006, InObject.BASEINFO.FENYUANDM));
                if (dt.Rows.Count <= 0)
                {
                    throw new Exception("查询不到医院代码为【" + InObject.BASEINFO.FENYUANDM + "】的医院信息");
                }

                var ddxx = DBVisitor.ExecuteTable(SqlLoad.GetFormat(SQ.HIS00002, InObject.WIDOUTTRADENO));
                if (ddxx.Rows.Count > 0)
                {
                    throw new Exception("已存在相同订单号的结算信息!");
                }

                SortedDictionary <string, string> sParaTemp = new SortedDictionary <string, string>();
                sParaTemp.Add("partner", Config.Partner);
                sParaTemp.Add("_input_charset", Config.Input_charset.ToLower());
                sParaTemp.Add("service", "alipay.acquire.createandpay");
                sParaTemp.Add("notify_url", InObject.NOTIFYURL);
                sParaTemp.Add("seller_email", dt.Rows[0]["SELLEREMAIL"].ToString()); //Config.Seller_email);
                //sParaTemp.Add("seller_id", "2088121042783039");
                sParaTemp.Add("out_trade_no", InObject.WIDOUTTRADENO);               //InObject.WIDOUTTRADENO
                sParaTemp.Add("subject", InObject.WIDSUBJECT);
                sParaTemp.Add("product_code", "GENERAL_WITHHOLDING");
                sParaTemp.Add("total_fee", InObject.WIDTOTALFEE);
                sParaTemp.Add("agreement_info", "{\"agreement_no\":\"" + InObject.AGREENNO + "\"}"); //协议号 必传 签约后传回
                sParaTemp.Add("key", "rfk3sw6dlq28k2tijjj54le6lfhw73s4");                            //取余杭卫生局的key
                // sParaTemp.Add("royalty_type", "ROYALTY");
                // sParaTemp.Add("buyer_id", InObject.BUYERID);
                // sParaTemp.Add("buyer_email", InObject.BUYEREMAIL);
                // sParaTemp.Add("body", InObject.WIDBODY);
                //sParaTemp.Add("it_b_pay", InObject.OUTTIME);
                //sParaTemp.Add("dynamic_id_type", "bar_code");//动态ID类型
                //sParaTemp.Add("dynamic_id", "kff3hjwqzxrbvrrkd0");//动态ID
                //  sParaTemp.Add("auth_no", InObject.AUTHNO);

                string    sfzh = "";
                DataTable qyxx = DBVisitor.ExecuteTable(SqlLoad.GetFormat(SQ.HIS00021, InObject.AGREENNO));
                if (qyxx.Rows.Count >= 0)
                {
                    sfzh = qyxx.Rows[0]["SHENFENZH"].ToString();
                }
                //将请求数据 插入数据库
                DBVisitor.ExecuteNonQuery(SqlLoad.GetFormat(SQ.HIS00001,
                                                            InObject.WIDOUTTRADENO,               //商户订单号
                                                            '3',                                  //结算类型 1手机网页支付 2二维码扫描支付 3商户代扣
                                                            "",                                   //服务器异步通知页面路径
                                                            "",                                   //页面跳转同步通知页面路径
                                                            "",                                   //操作中断返回地址)
                                                            InObject.WIDSUBJECT,                  //订单名称
                                                            InObject.WIDTOTALFEE,                 //订单金额
                                                            InObject.WIDBODY,                     //订单描述
                                                            InObject.OUTTIME,                     //超时时间取值范围
                                                            InObject.BUYERID,                     //买家支付宝用户号
                                                            InObject.BUYEREMAIL,                  //买家支付宝帐号
                                                            InObject.AUTHNO,                      //授权号
                                                            InObject.AGREENNO,                    //协议号
                                                            "0",                                  //结算状态 0未结算 1结算成功 2结算失败
                                                            "",
                                                            InObject.BASEINFO.FENYUANDM,          //分院代码
                                                            dt.Rows[0]["SELLEREMAIL"].ToString(), //收款帐号
                                                            InObject.BASEINFO.CAOZUOYXM,
                                                            InObject.BASEINFO.CAOZUOYDM,
                                                            sfzh,
                                                            InObject.JIUZHENKH
                                                            ));

                LogUnit.Write("开始请求支付宝!");
                //建立请求
                string sHtmlText = Submit.BuildRequest(sParaTemp);
                //记录日志
                LogUnit.Write("JIESUANLX == 3###" + sHtmlText, "ZHIFUBAOJS");
                OutObject = new ZHIFUBAOJS_OUT();
                XmlDocument xmlDoc = new XmlDocument();
                try
                {
                    xmlDoc.LoadXml(sHtmlText);
                    XmlNodeList nodeList = xmlDoc.SelectSingleNode("alipay").ChildNodes;
                    foreach (XmlNode xn in nodeList)
                    {
                        if (xn.Name == "error")
                        {
                            DBVisitor.ExecuteNonQuery(string.Format("update JR_ZHIFUBAOJSXX set FAILERR='{0}',JIESUANZT='-1' where IOUTTRADENO='{1}' ", xn.InnerText, InObject.WIDOUTTRADENO));
                            throw new Exception(xn.InnerText);
                        }
                        if (xn.Name == "response")
                        {
                            XmlElement  xe      = (XmlElement)xn;
                            XmlNodeList subList = xe.ChildNodes;
                            foreach (XmlNode xmlNode in subList)
                            {
                                if (xmlNode.Name == "alipay")
                                {
                                    XmlElement  xemx      = (XmlElement)xmlNode;
                                    XmlNodeList submxList = xemx.ChildNodes;

                                    foreach (XmlNode mxnode in submxList)
                                    {
                                        if (mxnode.Name == "detail_error_code")
                                        {
                                            OutObject.ERRORCODE = mxnode.InnerText;
                                        }
                                        if (mxnode.Name == "detail_error_des")
                                        {
                                            OutObject.ERRORDES = mxnode.InnerText;
                                            throw new Exception(mxnode.InnerText);
                                        }
                                        if (mxnode.Name == "result_code")
                                        {
                                            OutObject.RESULTCODE = mxnode.InnerText;
                                        }
                                        if (mxnode.Name == "trade_no")
                                        {
                                            OutObject.TRADENO = mxnode.InnerText;
                                        }
                                        if (mxnode.Name == "out_trade_no")
                                        {
                                            OutObject.WIDOUTTRADENO = mxnode.InnerText;
                                        }
                                        if (mxnode.Name == "buyer_user_id")
                                        {
                                            OutObject.BUYERID = mxnode.InnerText;
                                        }
                                        if (mxnode.Name == "buyer_logon_id")
                                        {
                                            OutObject.BUYEREMAIL = mxnode.InnerText;
                                        }
                                        if (mxnode.Name == "total_fee")
                                        {
                                            OutObject.TOTALFREE = mxnode.InnerText;
                                        }
                                        if (mxnode.Name == "gmt_payment")
                                        {
                                            OutObject.PAYMENTTIME = mxnode.InnerText;
                                        }
                                        if (mxnode.Name == "extend_info")
                                        {
                                            OutObject.EXTENDINFO = mxnode.InnerText;
                                        }
                                        if (mxnode.Name == "fund_bill_list")
                                        {
                                            OutObject.FUNDBILLLIST = mxnode.InnerText;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (OutObject.RESULTCODE.ToUpper() == "ORDER_SUCCESS_PAY_SUCCESS")
                    {
                        DBVisitor.ExecuteNonQuery(string.Format("update JR_ZHIFUBAOJSXX set TRADENO='{0}',JIESUANZT='1',JIESUANSJ= sysdate,IBUYERID='{1}',IBUYEREMAIL='{2}'  where IOUTTRADENO='{3}' ", OutObject.TRADENO, OutObject.BUYERID, OutObject.BUYEREMAIL, InObject.WIDOUTTRADENO));
                    }
                    else
                    {
                        DBVisitor.ExecuteNonQuery(string.Format("update JR_ZHIFUBAOJSXX set FAILERR='{0}',JIESUANZT='-1',IBUYERID='{1}',IBUYEREMAIL='{2}'  where IOUTTRADENO='{3}' ", OutObject.ERRORDES, OutObject.BUYERID, OutObject.BUYEREMAIL, InObject.WIDOUTTRADENO));
                    }
                }
                catch (Exception ep)
                {
                    LogUnit.Write(ep.Message);
                    throw new Exception(ep.Message);
                }
            }
            #endregion
            else
            {
                throw new Exception("支付类型不正确!");
            }
        }
Exemple #51
0
        public override void RunCommand(object sender)
        {
            // get  type of file either from a physical file or from a URL
            var vFileType = v_FileType.ConvertToUserVariable(sender);
            //get variable path or URL to source file
            var vSourceFilePathOrigin = v_FilePathOrigin.ConvertToUserVariable(sender);
            // get source type of file either from a physical file or from a URL
            var vSourceFileType = v_FileSourceType.ConvertToUserVariable(sender);
            // get file path to destination files
            var vFilePathDestination = v_PathDestination.ConvertToUserVariable(sender);
            // get file path to destination files
            var v_VariableName = v_applyToVariableName.ConvertToUserVariable(sender);

            if (vSourceFileType == "File URL")
            {
                //create temp directory
                var tempDir  = Core.IO.Folders.GetFolder(Folders.FolderType.TempFolder);
                var tempFile = System.IO.Path.Combine(tempDir, $"{ Guid.NewGuid()}." + vFileType);

                //check if directory does not exist then create directory
                if (!System.IO.Directory.Exists(tempDir))
                {
                    System.IO.Directory.CreateDirectory(tempDir);
                }

                // Create webClient to download the file for extraction
                var webclient = new System.Net.WebClient();
                var uri       = new Uri(vSourceFilePathOrigin);
                webclient.DownloadFile(uri, tempFile);

                // check if file is downloaded successfully
                if (System.IO.File.Exists(tempFile))
                {
                    vSourceFilePathOrigin = tempFile;
                }

                // Free not needed resources
                uri = null;
                if (webclient != null)
                {
                    webclient.Dispose();
                    webclient = null;
                }
            }

            // Check if file exists before proceeding
            if (!System.IO.File.Exists(vSourceFilePathOrigin))
            {
                throw new System.IO.FileNotFoundException("Could not find file: " + vSourceFilePathOrigin);
            }

            // Get 7Z app
            var zPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "Resources", "7z.exe");

            // If the directory doesn't exist, create it.
            if (!Directory.Exists(vFilePathDestination))
            {
                Directory.CreateDirectory(vFilePathDestination);
            }

            var result = "";

            System.Diagnostics.Process process = new System.Diagnostics.Process();

            try
            {
                var temp = Guid.NewGuid();
                //Extract in temp to get list files and directories and delete
                ProcessStartInfo pro = new ProcessStartInfo();
                pro.WindowStyle            = ProcessWindowStyle.Hidden;
                pro.UseShellExecute        = false;
                pro.FileName               = zPath;
                pro.RedirectStandardOutput = true;
                pro.Arguments              = "x " + vSourceFilePathOrigin + " -o" + vFilePathDestination + "/" + temp + " -aoa";
                process.StartInfo          = pro;
                process.Start();
                process.WaitForExit();
                string[] dirPaths  = Directory.GetDirectories(vFilePathDestination + "/" + temp, "*", SearchOption.TopDirectoryOnly);
                string[] filePaths = Directory.GetFiles(vFilePathDestination + "/" + temp, "*", SearchOption.TopDirectoryOnly);

                foreach (var item in dirPaths)
                {
                    result = result + item + Environment.NewLine;
                }
                foreach (var item in filePaths)
                {
                    result = result + item + Environment.NewLine;
                }
                result = result.Replace("/" + temp, "");
                Directory.Delete(vFilePathDestination + "/" + temp, true);

                //Extract
                pro.Arguments     = "x " + vSourceFilePathOrigin + " -o" + vFilePathDestination + " -aoa";
                process.StartInfo = pro;
                process.Start();
                process.WaitForExit();


                result.StoreInUserVariable(sender, v_applyToVariableName);
            }
            catch (System.Exception Ex)
            {
                process.Kill();
                v_applyToVariableName = Ex.Message;
            }
        }
        public async Task DownloadImagesAsync(List <Core.Data.Geocache> gcList, bool updateExisting)
        {
            await Task.Run(async() =>
            {
                bool cancel = false;
                ConcurrentQueue <Core.Data.Geocache> cq = new ConcurrentQueue <Core.Data.Geocache>();
                foreach (var gc in gcList)
                {
                    cq.Enqueue(gc);
                }

                using (Utils.ProgressBlock prog = new ProgressBlock("DownloadingImages", "DownloadingImages", gcList.Count, 0, true))
                {
                    Action actionUpdateProgress = () =>
                    {
                        DateTime updateAt = DateTime.MinValue;
                        int cnt           = cq.Count;
                        while (cnt > 0)
                        {
                            if (DateTime.Now >= updateAt)
                            {
                                if (!prog.Update("DownloadingImages", gcList.Count, gcList.Count - cnt))
                                {
                                    cancel = true;
                                    break;
                                }
                                updateAt = DateTime.Now.AddSeconds(1);
                            }
                            System.Threading.Thread.Sleep(200);
                            cnt = cq.Count;
                        }
                        ;
                    };

                    Action actionDownload = () =>
                    {
                        Core.Data.Geocache gc;
                        using (System.Net.WebClient wc = new System.Net.WebClient())
                        {
                            while (!cancel && cq.TryDequeue(out gc))
                            {
                                string fnp       = System.IO.Path.Combine(_imageFolder, IMG_SUBFOLDER);
                                bool grabOnlyNew = !updateExisting;
                                try
                                {
                                    List <string> linkList;
                                    lock (_lockObject)
                                    {
                                        linkList = DataAccess.GetImagesOfGeocache(gc.Database, gc.Code);
                                    }

                                    foreach (string link in linkList)
                                    {
                                        string fn       = string.Format("{0}.jpg", Guid.NewGuid().ToString("N"));
                                        bool skipInsert = false;
                                        //if it fails, just ignore this image
                                        try
                                        {
                                            //check if link already is in database
                                            //if so, use this filename
                                            lock (_lockObject)
                                            {
                                                object o = _dbcon.ExecuteScalar(string.Format("select local_file from images where gccode='{0}' and org_url='{1}'", gc.Code.Replace("'", "''"), link.Replace("'", "''")));
                                                if (o != null && o.GetType() != typeof(DBNull))
                                                {
                                                    fn         = (string)o;
                                                    skipInsert = true;
                                                }
                                            }
                                            if (grabOnlyNew && skipInsert)
                                            {
                                                if (System.IO.File.Exists(System.IO.Path.Combine(fnp, fn)))
                                                {
                                                    continue;
                                                }
                                            }
                                            using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                                            {
                                                wc.DownloadFile(link, tmp.Path);
                                                if (new FileInfo(tmp.Path).Length < 10 * 1024 * 1024)
                                                {
                                                    using (System.Drawing.Image img = System.Drawing.Image.FromFile(tmp.Path))
                                                    {
                                                        img.Save(System.IO.Path.Combine(fnp, fn), System.Drawing.Imaging.ImageFormat.Jpeg);
                                                        if (!skipInsert)
                                                        {
                                                            lock (_lockObject)
                                                            {
                                                                _dbcon.ExecuteNonQuery(string.Format("insert into images (gccode, org_url, local_file) values ('{0}', '{1}', '{2}')", gc.Code.Replace("'", "''"), link.Replace("'", "''"), fn));
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        catch //(Exception e)
                                        {
                                            //Core.ApplicationData.Instance.Logger.AddLog(this, e);
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    Core.ApplicationData.Instance.Logger.AddLog(this, e);
                                    //skip and go to next one
                                }
                            }
                        };
                    };

                    List <Task> tasks = new List <Task>();
                    tasks.Add(Task.Factory.StartNew(actionUpdateProgress));
                    for (int i = 0; i < 4 && i < gcList.Count; i++)
                    {
                        tasks.Add(Task.Factory.StartNew(actionDownload));
                    }
                    await Task.WhenAll(tasks.ToArray());
                }
            });
        }
Exemple #53
0
        public static bool CreateWordDocParagraph(string qname, string[][] qdata, IVsThreadedWaitDialog2 dlg)
        {
            //InitializeVariables();
            System.Net.WebClient webclient = new System.Net.WebClient();
            webclient.Credentials = System.Net.CredentialCache.DefaultCredentials;

            var           application = new MSWord.Application();
            var           document    = new MSWord.Document();
            object        missing     = System.Reflection.Missing.Value;
            int           pagewidth   = 800;
            bool          bcanceled;
            int           progress = 1;
            StringBuilder strbld   = new StringBuilder();

            MSWord.WdBuiltinStyle[] hstyles = new MSWord.WdBuiltinStyle[8];
            hstyles[0] = MSWord.WdBuiltinStyle.wdStyleHeading1;
            hstyles[1] = MSWord.WdBuiltinStyle.wdStyleHeading2;
            hstyles[2] = MSWord.WdBuiltinStyle.wdStyleHeading3;
            hstyles[3] = MSWord.WdBuiltinStyle.wdStyleHeading4;
            hstyles[4] = MSWord.WdBuiltinStyle.wdStyleHeading5;
            hstyles[5] = MSWord.WdBuiltinStyle.wdStyleHeading6;
            hstyles[6] = MSWord.WdBuiltinStyle.wdStyleHeading7;
            hstyles[7] = MSWord.WdBuiltinStyle.wdStyleHeading8;

            application.Visible       = true;
            application.WindowState   = MSWord.WdWindowState.wdWindowStateMinimize;
            application.DisplayAlerts = MSWord.WdAlertLevel.wdAlertsNone;
            document = application.Documents.Add();
            //document.PageSetup.Orientation = MSWord.WdOrientation.wdOrientLandscape;
            document.PageSetup.LeftMargin   = 20;
            document.PageSetup.RightMargin  = 20;
            document.PageSetup.TopMargin    = 20;
            document.PageSetup.BottomMargin = 20;
            document.PageSetup.PageWidth    = pagewidth + 40;

            MSWord.Paragraph prg = document.Paragraphs.Add();
            prg.Range.Text = "Query results for " + qname + " [" + DateTime.Now + "]";
            prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTitle);
            //prg.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            prg.SpaceAfter  = 100;
            prg.SpaceBefore = 100;
            prg.Range.InsertParagraphAfter();

            prg            = document.Paragraphs.Add();
            prg.Range.Text = "Table of Contents";
            prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTocHeading);
            prg.Range.InsertParagraphAfter();

            prg            = document.Paragraphs.Add();
            prg.Range.Text = "TOC";
            prg.Range.InsertParagraphAfter();
            prg.Range.InsertBreak(MSWord.WdBreakType.wdPageBreak);

            prg = document.Paragraphs.Add();
            MSWord.Table qtable = document.Tables.Add(prg.Range, qdata.Length, 1);
            prg.Range.InsertParagraphAfter();

            prg            = document.Paragraphs.Add();
            prg.Range.Text = "Appendix";
            prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTitle);
            prg.Range.InsertParagraphAfter();

            object styleTypeTable = MSWord.WdStyleType.wdStyleTypeTable;

            MSWord.Style styl = document.Styles.Add("New Table Style", ref styleTypeTable);
            styl.ParagraphFormat.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceSingle;
            styl.ParagraphFormat.SpaceAfter      = 0;
            styl.ParagraphFormat.SpaceBefore     = 0;
            styl.Table.TopPadding    = 0;
            styl.Table.BottomPadding = 0;
            styl.Table.LeftPadding   = 0;
            styl.Table.RightPadding  = 0;
            //styl.Table.Borders.Enable = 1;
            qtable.Range.set_Style(styl);

            MSWord.Cell cell = qtable.Cell(1, 1);

            int headerwidth = 85;
            int levelwidth  = 100;

            object rows, cols;

            for (int i = 0; i < qdata.Length; i++)
            {
                int level = int.Parse(qdata[i][1]);
                if (level > 0)
                {
                    rows = 1;
                    cols = 2;
                    cell.Split(ref rows, ref cols);
                    cell.Range.Cells.SetWidth(level * levelwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                    cell = cell.Next;
                }

                rows = 1 + (string.IsNullOrWhiteSpace(qdata[i][0]) ? 0 : 1) + (string.IsNullOrWhiteSpace(qdata[i][6]) ? 0 : 1);
                cols = 2;
                cell.Split(ref rows, ref cols);
                cell.Merge(cell.Next);

                string title = String.Format("{0} {1} ({2})",
                                             qdata[i][2],
                                             (qdata[i][5].Length > 128 ? qdata[i][5].Remove(128) : qdata[i][5]).Replace("\n", "").Replace("\r", "").Replace("\t", ""),
                                             qdata[i][4]);

                cell.Range.Text      = title;
                cell.Range.Font.Bold = 1;
                cell.Range.set_Style(hstyles[level < 8 ? level:7]);
                cell = cell.Next;

                dlg.UpdateProgress("Exporting Work Item query to Microsoft Word document", "Adding to Word document " + qdata[i][3] + " #" + qdata[i][4], "status", progress++, 100, false, out bcanceled);
                if (progress == 100)
                {
                    progress = 0;
                }
                if (bcanceled)
                {
                    application.Visible = true;
                    Marshal.ReleaseComObject(document);
                    Marshal.ReleaseComObject(application);

                    return(true);
                }

                /*cell.Range.Text = "Title";
                 * cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                 * cell.Range.Font.Bold = 1;
                 * cell = cell.Next;
                 *
                 * cell.Range.Text = qdata[i][4];
                 * cell = cell.Next;*/

                /*cell.Range.Text = "Description";
                 * cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                 * cell.Range.Font.Bold = 1;
                 * cell = cell.Next;*/

                if (!string.IsNullOrWhiteSpace(qdata[i][6]))
                {
                    cell.Merge(cell.Next);
                    cell.Range.Text = qdata[i][6];
                    cell            = cell.Next;
                }

                if (!string.IsNullOrWhiteSpace(qdata[i][0]))
                {
                    cell.Range.Text = "Attachments";
                    cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth);
                    cell.Range.Font.Bold = 1;
                    cell = cell.Next;

                    var query = qdata[i][0]
                                .Split(';')
                                .Where(x => !string.IsNullOrWhiteSpace(x))
                                .Select(x =>
                    {
                        string[] ch = x.Split('~');
                        return(new { name = ch[0], value = ch[1] });
                    }).ToArray();
                    cell.Split(query.Length, 1);

                    foreach (var kvp in query)
                    {
                        string localpath = Path.GetTempFileName() + "." + kvp.name;
                        //try { File.Delete(localpath); }
                        //catch { }

                        try
                        {
                            webclient.DownloadFile(kvp.value, localpath);
                        }
                        catch (Exception ex)
                        {
                            localpath = "";
                            Utilities.OutputCommandString(ex.ToString());
                        }

                        prg            = document.Paragraphs.Add();
                        prg.Range.Text = kvp.name;
                        prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleHeading3);

                        cell.Range.Text = kvp.name;
                        document.Hyperlinks.Add(cell.Range, missing, prg.Range);

                        prg.Range.InsertParagraphAfter();
                        document.InlineShapes.AddHorizontalLineStandard(prg.Range);
                        prg = document.Paragraphs.Add();

                        if (!string.IsNullOrEmpty(localpath))
                        {
                            try
                            {
                                Image img = Image.FromFile(localpath);
                                img.Dispose();
                                document.InlineShapes.AddPicture(localpath, false, true, prg.Range);
                            }
                            catch
                            {
                                if (Path.GetExtension(kvp.name).Equals(".sql", StringComparison.InvariantCultureIgnoreCase) ||
                                    Path.GetExtension(kvp.name).Equals(".txt", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    prg.Range.InsertFile(localpath);//, prg.Range, false, true, false);
                                }
                                else
                                {
                                    MSWord.InlineShape shape = document.InlineShapes.AddOLEObject(missing, localpath, false, false, missing, missing, missing, prg.Range);
                                    if (shape.OLEFormat.ClassType.ToString() != "Package")
                                    {
                                        shape.Width = document.PageSetup.PageWidth - 40;
                                    }
                                }
                            }
                        }
                        cell = cell.Next;
                    }
                    if (query.Length == 0)
                    {
                        cell = cell.Next;
                    }
                }
            }

            object styleTypePara = MSWord.WdStyleType.wdStyleTypeParagraph;

            MSWord.Style styl2 = document.Styles.Add("New Paragraph Style", ref styleTypePara);
            //styl2.ParagraphFormat.set_Style(MSWord.WdBuiltinStyle.wdStyleNormal);
            styl2.ParagraphFormat.LeftIndent      = 100;
            styl2.ParagraphFormat.RightIndent     = 100;
            styl2.ParagraphFormat.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceSingle;
            styl2.ParagraphFormat.SpaceAfter      = 0;
            styl2.ParagraphFormat.SpaceBefore     = 0;

            MSWord.Paragraph       tocpara = document.Paragraphs[3];
            MSWord.TableOfContents tblct   = document.TablesOfContents.Add(tocpara.Range, missing, 1, 1);
            tblct.Update();
            //tblct.Range.set_Style(styl2);

            //application.Visible = true;

            Marshal.ReleaseComObject(document);
            Marshal.ReleaseComObject(application);

            return(false);
        }
Exemple #54
0
        /// <summary>
        /// Paints the PictureBox
        /// </summary>
        /// <param name="g">The Graphics object to draw</param>
        /// <remarks>Causes the PictureBox to be painted to the screen.</remarks>
        public override void Paint(Graphics g)
        {
            // Raffaele Russo - 12/12/2011 - Start
            Rectangle paintArea = this.Section.Document.DesignMode ? theRegion : new Rectangle(Bounds.X - rBounds.X, Bounds.Y - rBounds.Y, Bounds.Width, Bounds.Height);

            // Rectangle paintArea = new Rectangle(theRegion.X - rBounds.X, theRegion.Y - rBounds.Y, theRegion.Width, theRegion.Height);
            // Rectangle paintArea = this.Section.Document.DesignMode ? theRegion : Bounds;
            // Raffaele Russo - 12/12/2011 - End

            // Raffaele Russo - 07/03/2012 - Start
            if (mImage == null)
            {
                string url = this.ResolveParameterValues(mFilename);

                int    lio = url.LastIndexOf('/');
                string soloFilename;
                if (lio > 0)
                {
                    soloFilename = System.IO.Path.GetFileName(url.Substring(lio + 1));
                }
                else
                {
                    soloFilename = System.IO.Path.GetFileName(url);
                }

                System.Net.WebClient client = new System.Net.WebClient();

                try
                {
                    string filename = section.Document.DocRoot + Path.DirectorySeparatorChar.ToString() + soloFilename;
                    if (!System.IO.File.Exists(filename))
                    {
                        client.DownloadFile(url, filename);
                    }

                    mImage = new Bitmap(filename);
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    client.Dispose();
                }
            }
            // Raffaele Russo - 07/03/2012 - End

            if (mImage != null)
            {
                if (mDoStretch)
                {
                    if (paintTransparent)
                    {
                        g.DrawImage(mImage, paintArea, 0, 0, mImage.Width, mImage.Height, GraphicsUnit.Pixel, transparencyAttributes);
                    }
                    else
                    {
                        g.DrawImage(mImage, paintArea, 0, 0, mImage.Width, mImage.Height, GraphicsUnit.Pixel);
                    }
                }
                else
                {
                    if (paintTransparent)
                    {
                        g.DrawImage(mImage, paintArea, 0, 0, paintArea.Width, paintArea.Height, GraphicsUnit.Pixel, transparencyAttributes);
                    }
                    else
                    {
                        g.DrawImage(mImage, paintArea, 0, 0, paintArea.Width, paintArea.Height, GraphicsUnit.Pixel);
                    }
                }

                if (mBorderWidth > 0)
                {
                    g.DrawRectangle(new Pen(mBorderColor, mBorderWidth), paintArea);
                }
            }
            else
            {
                if (section.Document.DesignMode)
                {
                    g.FillRectangle(new System.Drawing.Drawing2D.HatchBrush(System.Drawing.Drawing2D.HatchStyle.Percent05, Color.Gray, Color.Transparent), paintArea);

                    StringFormat sf = new StringFormat();
                    sf.Alignment     = StringAlignment.Center;
                    sf.LineAlignment = StringAlignment.Center;
                    g.DrawString("Set your picture through ImageFile property.", new Font("Tahoma", 8 * g.PageScale), Brushes.Black, theRegion, sf);
                }
            }
        }
Exemple #55
0
        void addonInstUpd(object o, LinkLabelLinkClickedEventArgs e)
        {
            //Set Up Progress Bar
            statusProgress.Minimum = 0;
            statusProgress.Maximum = addonsDataGrid.Rows.Count;
            statusProgress.Value   = 0;

            //Loop through selected rows
            foreach (DataGridViewRow row in addonsDataGrid.Rows)
            {
                if ((bool)row.Cells["addonsSelected"].Value == true)
                {
                    //If We Are Updating, Remove It First
                    if ((bool)row.Cells["addonsInstalled"].Value == true)
                    {
                        addonDeleteSingle(row.Index);
                    }

                    //Set Up
                    System.IO.Directory.CreateDirectory("Addons");
                    string file = "Addons/" + row.Cells["addonsFile"].Value.ToString();

                    if (!System.IO.File.Exists(file))
                    {
                        //Download
                        statusText.Text = "Downloading " + row.Cells["addonsFile"].Value.ToString();
                        System.Net.WebClient client = new System.Net.WebClient();
                        client.DownloadFile("http://www.lotrointerface.com/downloads/download" + row.Cells["addonsID"].Value.ToString(), file);

                        //Move Progress Bar (but make sure it still ends at 100%)
                        statusProgress.Maximum = statusProgress.Maximum + 1;
                        statusProgress.Increment(1);
                        Application.DoEvents();
                    }

                    //Move Progress Bar (but make sure it still ends at 100%)
                    statusProgress.Maximum = statusProgress.Maximum + 1;
                    statusProgress.Increment(1);
                    statusText.Text = "Extracting " + row.Cells["addonsFile"].Value.ToString();
                    Application.DoEvents();

                    //Extract
                    SevenZipExtractor zip = new SevenZipExtractor(file);
                    zip.PreserveDirectoryStructure = true;
                    zip.ExtractArchive(".");

                    //Save File List
                    string[] files = new string[zip.ArchiveFileNames.Count];
                    zip.ArchiveFileNames.CopyTo(files, 0);
                    System.IO.File.WriteAllLines("Addons/" + row.Cells["addonsID"].Value.ToString() + ".conf", files);

                    //Set Installed + Version
                    row.Cells["addonsInstVer"].Value   = row.Cells["addonsVersion"].Value;
                    row.Cells["addonsInstalled"].Value = true;
                    row.Cells["addonsSelected"].Value  = false;
                }

                statusProgress.Increment(1);
            }

            //Refresh Available Skin Elements
            skinFillTable();

            statusText.Text = "Addons were installed/updated successfully!";
        }
        public ActionResultVM UpdateUserPhoto(string type, string source)
        {
            var vm = new ActionResultVM();

            var uinfo = new Func.UserAuthAid(HttpContext).Get();

            try
            {
                var rootdir  = GlobalTo.WebRootPath + "/" + (GlobalTo.GetValue("StaticResource:RootDir").TrimStart('/').TrimEnd('/') + "/");
                var path     = GlobalTo.GetValue("StaticResource:AvatarPath").TrimEnd('/').TrimStart('/') + '/';
                var fullpath = rootdir + path;

                if (!Directory.Exists(fullpath))
                {
                    Directory.CreateDirectory(fullpath);
                }

                if (string.IsNullOrWhiteSpace(uinfo.UserPhoto))
                {
                    uinfo.UserPhoto = Core.UniqueTo.LongId() + ".jpg";
                }
                var upname = uinfo.UserPhoto.Split('?')[0];
                var npnew  = upname + "?" + DateTime.Now.ToTimestamp();

                switch (type)
                {
                case "file":
                {
                    source = source.Substring(source.LastIndexOf(",") + 1);
                    byte[] bytes = Convert.FromBase64String(source);
                    using var ms  = new MemoryStream(bytes);
                    using var bmp = new System.Drawing.Bitmap(ms);
                    var hp = fullpath + upname.Replace(".", "_lg.");
                    bmp.Save(hp, ImageFormat.Jpeg);
                    Fast.ImageTo.MinImg(hp, fullpath, upname, 40, 40, "wh");

                    using (var db = new ContextBase())
                    {
                        var usermo = db.UserInfo.Find(uinfo.UserId);
                        usermo.UserPhoto = npnew;
                        db.UserInfo.Update(usermo);
                        int num = db.SaveChanges();
                        if (num > 0)
                        {
                            using var ac = new AccountController();
                            ac.SetAuth(HttpContext, usermo);
                        }
                    }

                    vm.Set(ARTag.success);
                }
                break;

                case "link":
                {
                    using var wc = new System.Net.WebClient();
                    var hp = fullpath + upname.Replace(".", "_lg.");
                    wc.DownloadFile(source, hp);
                    Fast.ImageTo.MinImg(hp, fullpath, upname, 40, 40, "wh");

                    using (var db = new ContextBase())
                    {
                        var usermo = db.UserInfo.Find(uinfo.UserId);
                        usermo.UserPhoto = npnew;
                        db.UserInfo.Update(usermo);
                        int num = db.SaveChanges();
                        if (num > 0)
                        {
                            using var ac = new AccountController();
                            ac.SetAuth(HttpContext, usermo);
                        }
                    }

                    vm.Set(ARTag.success);
                }
                break;
                }
            }
            catch (Exception ex)
            {
                vm.Set(ex);
            }

            return(vm);
        }
        public static void GameListCheck()
        {
            byte[] hashlocal;
            byte[] hashremote;

            try
            {
                System.Net.WebClient gamefile = new System.Net.WebClient();
                gamefile.DownloadFile("https://raw.githubusercontent.com/andymanic/PresentMonLauncher/master/PresentMonLauncher/games.json", Path.Combine(Application.StartupPath) + "\\remotegames.json");
            }
            catch
            {
                if (MessageBox.Show("We tried to check the 'Games' file online but couldn't reach it, would you like to try checking again?", "Games file check", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
                {
                    try
                    {
                        System.Net.WebClient gamefile = new System.Net.WebClient();
                        gamefile.DownloadFile("https://raw.githubusercontent.com/andymanic/PresentMonLauncher/master/PresentMonLauncher/games.json", Path.Combine(Application.StartupPath) + "\\remotegames.json");
                    }
                    catch
                    {
                        if (MessageBox.Show("We tried to check the 'Games' file online but couldn't reach it, would you like to try checking again?", "Games file check", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
                        {
                            System.Net.WebClient gamefile = new System.Net.WebClient();
                            gamefile.DownloadFile("https://raw.githubusercontent.com/andymanic/PresentMonLauncher/master/PresentMonLauncher/games.json", Path.Combine(Application.StartupPath) + "\\remotegames.json");
                        }
                        else
                        {
                            MessageBox.Show("This isn't working, perhaps try again later.");
                            return;
                        }
                        return;
                    }
                }
                return;
            }
            if (!File.Exists(Path.Combine(Application.StartupPath) + "\\games.json"))
            {
                try
                {
                    System.IO.File.Move(Path.Combine(Application.StartupPath, "remotegames.json"), Path.Combine(Application.StartupPath, "games.json"));
                    return;
                }
                catch (Exception e)
                {
                    MessageBox.Show("We had a bit of a problem. Here's the error: " + e);
                }
            }

            using (var md5 = MD5.Create())
            {
                using (var stream = File.OpenRead(Path.Combine(Application.StartupPath) + "\\games.json"))
                {
                    hashlocal = md5.ComputeHash(stream);
                }
                using (var stream2 = File.OpenRead(Path.Combine(Application.StartupPath) + "\\remotegames.json"))
                {
                    hashremote = md5.ComputeHash(stream2);
                }
            }
            if (hashlocal.SequenceEqual(hashremote))
            {
                System.IO.File.Delete(Path.Combine(Application.StartupPath, "remotegames.json"));
            }
            else
            {
                System.IO.File.Delete(Path.Combine(Application.StartupPath, "games.json"));
                System.IO.File.Move(Path.Combine(Application.StartupPath, "remotegames.json"), Path.Combine(Application.StartupPath, "games.json"));
            }
        }
Exemple #58
0
        public DataTable getData(string symbol)
        {
            DataTable stockdata = new DataTable();


            //Download csv file for last 5 years, up to last month and save it
            System.Net.WebClient csvDownloader = new System.Net.WebClient();
            string stockUrl = "http://ichart.finance.yahoo.com/table.csv?s=" +
                              symbol +
                              "&a=" +
                              beginningDate.ToString("MM") +
                              "&b=" +
                              beginningDate.ToString("dd") +
                              "&c=" +
                              beginningDate.ToString("yyyy") +
                              "&d=" +
                              today.ToString("MM") +
                              "&e=" +
                              today.ToString("dd") +
                              "&f=" +
                              today.ToString("yyyy") +
                              "&g=d&ignore=.csv";

            //Download 5 years worth of EOD data
            try
            {
                csvDownloader.DownloadFile(stockUrl, "./" + symbol + ".csv");
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception Caught.", e);
            }

            //DataTable stockData = new DataTable("prices");
            stockdata.Columns.Add("date");
            stockdata.Columns.Add("open");
            stockdata.Columns.Add("high");
            stockdata.Columns.Add("low");
            stockdata.Columns.Add("close");
            stockdata.Columns.Add("volume");
            stockdata.Columns.Add("adjVolume");

            stockdata.Rows.Clear();
            using (StreamReader csvReader = new StreamReader("./" + symbol + ".csv"))
            {
                string   line;
                string[] vals;
                while ((line = csvReader.ReadLine()) != null)
                {
                    vals = line.Split(',');
                    stockdata.Rows.Add(vals);
                }
            }


            stockdata.Rows[0].Delete();

            //stockdata.DefaultView.Sort = "date" + " " + "ASC";
            //stockdata = stockdata.DefaultView.ToTable();


            //Open database connection
            string        connectionStringLaptop = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\crommie\Dropbox\stock_analyzer\StockAnalyzer_windows\StockAnalyzer\prices.mdf;Integrated Security=True";
            string        connectionString       = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\aaron\documents\visual studio 2012\Projects\StockAnalyzer\StockAnalyzer\prices.mdf;Integrated Security=True";
            SqlConnection db2Connection          = new SqlConnection(connectionStringLaptop);

            db2Connection.Open();

            using (SqlCommand cmd = db2Connection.CreateCommand())
            {
                cmd.CommandText =
                    @"
                       IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '" + symbol + @"')
                        BEGIN
                        DROP TABLE " + symbol + @";
                       IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '" + symbol + @"')
                        CREATE TABLE " + symbol + @" (
                          ID     integer PRIMARY KEY NOT NULL IDENTITY,
                          datetime     varchar(20), 
                          openVal     varchar(10),
                          closeVal     varchar(10),
                          highVal     varchar(10),
                          lowVal     varchar(10),
                          volume     varchar(20)
                            ); END";
                MessageBox.Show(cmd.CommandText);
                cmd.ExecuteNonQuery();
                //try { cmd.ExecuteNonQuery(); }
                //catch (SqlException) { MessageBox.Show("SQL Exception creating table for company info"); }
            }

            //Delete contents of table - may want to rethink this step??
            SqlCommand delCmd = new SqlCommand(@"DELETE FROM " + symbol + ";", db2Connection);

            delCmd.ExecuteNonQuery();

            using (SqlBulkCopy copy = new SqlBulkCopy(connectionStringLaptop))
            {
                copy.ColumnMappings.Add("date", "datetime");
                copy.ColumnMappings.Add("open", "openVal");
                copy.ColumnMappings.Add("close", "closeVal");
                copy.ColumnMappings.Add("high", "highVal");
                copy.ColumnMappings.Add("low", "lowVal");
                copy.ColumnMappings.Add("volume", "volume");

                copy.DestinationTableName = symbol;
                copy.WriteToServer(stockdata);
            }



            //Download Company information

            companyInfo.Columns.Add("symbol");
            companyInfo.Columns.Add("openVal");
            companyInfo.Columns.Add("ask");
            companyInfo.Columns.Add("bid");
            companyInfo.Columns.Add("avgDailyVol");
            companyInfo.Columns.Add("change");
            companyInfo.Columns.Add("eps");
            companyInfo.Columns.Add("epsEst");
            companyInfo.Columns.Add("dailyLow");
            companyInfo.Columns.Add("dailyHigh");
            companyInfo.Columns.Add("fiftytwoWeekLow");
            companyInfo.Columns.Add("fiftytwoWeekHigh");
            companyInfo.Columns.Add("mktCap");
            companyInfo.Columns.Add("ps");
            companyInfo.Columns.Add("pb");
            companyInfo.Columns.Add("pe");
            companyInfo.Columns.Add("targetOneYear");
            companyInfo.Columns.Add("exchange");
            companyInfo.Columns.Add("price");
            companyInfo.Columns.Add("tradeTime");
            companyInfo.Columns.Add("tradeDate");
            companyInfo.Columns.Add("prevClose");
            companyInfo.Columns.Add("div");
            companyInfo.Columns.Add("divYield");
            companyInfo.Columns.Add("name");

            //Download csv file with company info and save it
            System.Net.WebClient csvInfoDownloader = new System.Net.WebClient();
            string companyUrl = @"http://finance.yahoo.com/d/quotes.csv?s=" +
                                symbol +
                                @"&f=sob2b3a2c6ee8ghjkj1p5p6rt8xk1t1d1pdy";

            try
            {
                csvInfoDownloader.DownloadFile(companyUrl, "./" + symbol + "Info" + ".csv");
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception Caught.", e);
            }


            companyInfo.Rows.Clear();

            using (StreamReader csvCompanyReader = new StreamReader("./" + symbol + "Info" + ".csv"))
            {
                string   line;
                string[] vals;
                while ((line = csvCompanyReader.ReadLine()) != null)
                {
                    vals = line.Split(',');
                    try
                    {
                        companyInfo.Rows.Add(vals);
                    }
                    catch (ArgumentException)
                    {
                    }
                }
            }

            //Download company name and save it
            System.Net.WebClient csvNameDownloader = new System.Net.WebClient();
            string nameUrl = @"http://finance.yahoo.com/d/quotes.csv?s=" +
                             symbol +
                             @"&f=n";

            try
            {
                csvNameDownloader.DownloadFile(nameUrl, "./" + symbol + "Name" + ".csv");
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception Caught.", e);
            }

            using (StreamReader csvNameReader = new StreamReader("./" + symbol + "Name" + ".csv"))
            {
                string line;
                while ((line = csvNameReader.ReadLine()) != null)
                {
                    companyInfo.Rows[0]["name"] = line.Split('"', '"')[1];
                }
            }

            //Rename Symbol in Table to not have quotes
            companyInfo.Rows[0]["symbol"] = companyInfo.Rows[0]["symbol"].ToString().Split('"', '"')[1];

            using (SqlCommand cmd2 = db2Connection.CreateCommand())
            {
                cmd2.CommandText =
                    @" 
                       IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'companyData')
                        BEGIN
                        CREATE TABLE companyData (
                          ID     integer PRIMARY KEY NOT NULL IDENTITY,
                          symbol     varchar(10),
                          openVal     varchar(20),
                          ask     varchar(20),
                          bid     varchar(20),
                          avgDailyVol     varchar(20),
                          change     varchar(20),
                          eps     varchar(20),
                          epsEst     varchar(20),
                          dailyLow     varchar(20),
                          dailyHigh     varchar(20),
                          fiftytwoWeekLow     varchar(20),
                          fiftytwoWeekHigh     varchar(20),
                          mktCap     varchar(20),
                          ps     varchar(20),
                          pb     varchar(20),
                          pe     varchar(20),
                          targetOneYear     varchar(20),
                          exchange     varchar(20),
                          price     varchar(30),
                          tradeTime     varchar(20),
                          tradeDate     varchar(20),
                          prevClose     varchar(20), 
                          div     varchar(20),
                          divYield     varchar(20),
                          name     varchar(30),
                          ); END";

                cmd2.ExecuteNonQuery();
            }


            //Delete contents of table - may want to rethink this step??
            MessageBox.Show("About to delete company data");
            SqlCommand delCompanyCmd = new SqlCommand(@"DELETE FROM companyData where symbol = '" + symbol + "';", db2Connection);

            delCompanyCmd.ExecuteNonQuery();
            MessageBox.Show("Just deleted company data");
            using (SqlBulkCopy copyCompany = new SqlBulkCopy(connectionStringLaptop))
            {
                copyCompany.ColumnMappings.Add("symbol", "symbol");
                copyCompany.ColumnMappings.Add("openVal", "openVal");
                copyCompany.ColumnMappings.Add("ask", "ask");
                copyCompany.ColumnMappings.Add("bid", "bid");
                copyCompany.ColumnMappings.Add("avgDailyVol", "avgDailyVol");
                copyCompany.ColumnMappings.Add("change", "change");
                copyCompany.ColumnMappings.Add("eps", "eps");
                copyCompany.ColumnMappings.Add("epsEst", "epsEst");
                copyCompany.ColumnMappings.Add("dailyLow", "dailyLow");
                copyCompany.ColumnMappings.Add("dailyHigh", "dailyHigh");
                copyCompany.ColumnMappings.Add("fiftytwoWeekLow", "fiftytwoWeekLow");
                copyCompany.ColumnMappings.Add("fiftytwoWeekHigh", "fiftytwoWeekHigh");
                copyCompany.ColumnMappings.Add("mktCap", "mktCap");
                copyCompany.ColumnMappings.Add("ps", "ps");
                copyCompany.ColumnMappings.Add("pb", "pb");
                copyCompany.ColumnMappings.Add("pe", "pe");
                copyCompany.ColumnMappings.Add("targetOneYear", "targetOneYear");
                copyCompany.ColumnMappings.Add("exchange", "exchange");
                copyCompany.ColumnMappings.Add("price", "price");
                copyCompany.ColumnMappings.Add("tradeTime", "tradeTime");
                copyCompany.ColumnMappings.Add("tradeDate", "tradeDate");
                copyCompany.ColumnMappings.Add("prevClose", "prevClose");
                copyCompany.ColumnMappings.Add("div", "div");
                copyCompany.ColumnMappings.Add("divYield", "divYield");
                copyCompany.ColumnMappings.Add("name", "name");

                copyCompany.DestinationTableName = "companyData";
                copyCompany.WriteToServer(companyInfo);
            }

            db2Connection.Close();
            return(companyInfo);
        }
Exemple #59
0
        public static void GenerateIconImage(SoundPlayerInfo bgm, bool force)
        {
            string folder   = "playericon";
            string fileName = folder + @"\" + bgm.Id + ".png";

            System.Drawing.Bitmap bitmap;

            try
            {
                if (bgm.Name == "System Sounds")
                {
                    if (_iconContents.TryGetValue(@"mixer\windows.png", out bitmap) == false)
                    {
                        string tempFileName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\mixer\windows.png";
                        if (System.IO.File.Exists(tempFileName))
                        {
                            bitmap = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile(tempFileName);
                            _iconContents[@"mixer\windows.png"] = bitmap;
                        }
                    }
                }
                else
                {
                    System.Drawing.Icon icon = null;
                    int x = 0;
                    if (bgm.IconPath != "")
                    {
                        x = x + 1;
                    }
                    string path = bgm.IconPath != "" ? bgm.IconPath : bgm.UrlOrCommandLine;
                    if ((bgm.IconPath == "") && (bgm.UrlOrCommandLine.StartsWith("http://")))
                    {
                        path = @"http://getfavicon.appspot.com/" + path;
                    }
                    if ((bgm.IconPath == "") && (bgm.UrlOrCommandLine.StartsWith("https://")))
                    {
                        path = @"https://getfavicon.appspot.com/" + path;
                    }

                    if (_iconContents.TryGetValue(path, out bitmap) == false)
                    {
                        if ((path.ToLower().StartsWith("http://")) || (path.ToLower().StartsWith("https://")))
                        {
                            string tempFile = System.IO.Path.GetTempFileName();
                            var    client   = new System.Net.WebClient();
                            client.DownloadFile(path, tempFile);
                            icon = System.Drawing.Icon.ExtractAssociatedIcon(tempFile);
                            System.IO.File.Delete(tempFile);
                        }
                        else
                        {
                            if (System.IO.File.Exists(path))
                            {
                                icon = GetIconOldSchool(path);
                            }
                            //icon = System.Drawing.Icon.ExtractAssociatedIcon(path);
                        }
                        if (icon != null)
                        {
                            bitmap = icon.ToBitmap();
                        }
                        _iconContents[path] = bitmap;
//                        bitmap.Save("C://foo.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                    }
                }
                if ((force) || ((bitmap != null) && (WebServer.RetrieveFile(fileName) == null)))
                {
                    byte[] result;
                    using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                    {
                        bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                        result = stream.ToArray();
                    }
                    WebServer.StoreFile(fileName, result);
                }

//                if (bitmap == null)
//                    bgm.Enabled = false;
            }
            catch (Exception ex)
            {
                MuteFm.SmartVolManagerPackage.SoundEventLogger.LogMsg("Error generating icon file for bgmusic " + bgm.GetName());
                MuteFm.SmartVolManagerPackage.SoundEventLogger.LogException(ex);
//                bgm.Enabled = false;
            }
        }
        static void Main(string[] args)
        {
            //if (!TDSM.API.Command.WorldTime.Test())
            //{
            //    Console.WriteLine("Time test failed");
            //    Console.ReadKey(true);
            //}

            //if (!TDSM.API.Permissions.PermissionsManager.IsSet)
            //{
            //    var file = System.IO.Path.Combine(TDSM.API.Globals.DataPath, "permissions.xml");
            //    //if (System.IO.File.Exists(file)) System.IO.File.Delete(file);
            //    if (System.IO.File.Exists(file))
            //    {
            //        var handler = new TDSM.API.Permissions.XmlSupplier(file);
            //        if (handler.Load())
            //            TDSM.API.Permissions.PermissionsManager.SetHandler(handler);
            //    }
            //}

            Console.ForegroundColor         = ConsoleColor.Yellow;
            Console.WriteLine(Console.Title = String.Format("TDSM patcher build {0}", Build));
            Console.ForegroundColor         = ConsoleColor.White;
            var isMono = Type.GetType("Mono.Runtime") != null;

#if SERVER
            var inFile   = "TerrariaServer.exe";
            var fileName = "tdsm";
            //            var outFileMS = fileName + ".microsoft.exe";
            //            var outFileMN = fileName + ".mono.exe";
            var output    = fileName + ".exe";
            var patchFile = "TDSM.API.dll";

            if (!File.Exists(inFile))
            {
                var bin = Path.Combine(Environment.CurrentDirectory, "bin", "x86", "Debug", inFile);
                if (File.Exists(bin))
                {
                    inFile = bin;
                }
            }
            if (!File.Exists(patchFile))
            {
                var bin = Path.Combine(Environment.CurrentDirectory, "bin", "x86", "Debug", patchFile);
                if (File.Exists(bin))
                {
                    patchFile = bin;
                }
            }

            var resourceLib = "Vestris.ResourceLib.dll";
            if (!System.IO.File.Exists(resourceLib))
            {
                var bin = System.IO.Path.Combine(Environment.CurrentDirectory, "bin", "x86", "Debug", resourceLib);
                if (System.IO.File.Exists(bin))
                {
                    System.IO.File.Copy(bin, resourceLib);
                }
            }

#if DEV
            //            if (File.Exists(outFileMS)) File.Delete(outFileMS);
            //            if (File.Exists(outFileMN)) File.Delete(outFileMN);
            if (File.Exists(output))
            {
                File.Delete(output);
            }

            var root = new DirectoryInfo(Environment.CurrentDirectory);
            while (root.GetDirectories().Where(x => x.Name == "tdsm-patcher").Count() == 0)
            {
                if (root.Parent == null)
                {
                    Console.WriteLine("Failed to find root TDSM project directory");
                    break;
                }
                root = root.Parent;
            }

            Copy(root, "Binaries", Path.Combine(Environment.CurrentDirectory), "TDSM.API");
            Copy(root, "tdsm-api", Environment.CurrentDirectory);
            Copy(root, "tdsm-core", Path.Combine(Environment.CurrentDirectory, "Plugins"));
            //Copy (root, "Restrict", Path.Combine (Environment.CurrentDirectory, "Plugins"), "RestrictPlugin");
            Copy(root, "External", Path.Combine(Environment.CurrentDirectory, "Libraries"), "KopiLua", false);
            Copy(root, "External", Path.Combine(Environment.CurrentDirectory, "Libraries"), "NLua", false);
            Copy(root, "External", Path.Combine(Environment.CurrentDirectory, "Libraries"), "ICSharpCode.SharpZipLib", false);
            Copy(root, "External", Path.Combine(Environment.CurrentDirectory, "Libraries"), "Mono.Nat", false);
            Copy(root, "tdsm-core", Path.Combine(Environment.CurrentDirectory, "Libraries"), "Newtonsoft.Json", true);
            Copy(root, "tdsm-mysql-connector", Path.Combine(Environment.CurrentDirectory, "Plugins"), "tdsm-mysql-connector", true);
//            Copy(root, "tdsm-sqlite-connector", Path.Combine(Environment.CurrentDirectory, "Plugins"), "tdsm-sqlite-connector", true);
#endif
#elif CLIENT
            var inFile    = "Terraria.exe";
            var fileName  = "tcsm";
            var outFileMS = fileName + ".microsoft.exe";
            var outFileMN = fileName + ".mono.exe";
            var patchFile = "MonoGame.Framework.dll";
#endif
            if (!File.Exists(inFile))
            {
                //Download the supported vanilla software from our GitHub repo
                Console.WriteLine("The original Re-Logic TerrariaServer.exe is missing, download?");
                if (Console.ReadKey(true).Key == ConsoleKey.Y)
                {
                    //TODO add throbber
                    const String Url = "https://github.com/DeathCradle/Terraria-s-Dedicated-Server-Mod/raw/master/Official/TerrariaServer.exe";
                    using (var wc = new System.Net.WebClient())
                    {
                        var started = DateTime.Now;
                        try
                        {
                            wc.DownloadFile(Url, inFile);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                            Console.WriteLine("Press any key to exit...");
                            Console.ReadKey(true);
                            return;
                        }
                        var duration = DateTime.Now - started;
                        Console.WriteLine("Download completed in {0:c}", duration);
                    }
                }
                else
                {
                    return;
                }
            }

            var patcher = new Injector(inFile, patchFile);

            var noVersionCheck = args != null && args.Where(x => x.ToLower() == "-nover").Count() > 0;
            if (noVersionCheck != true)
            {
                var vers = patcher.GetAssemblyVersion();
                if (vers != APIWrapper.TerrariaVersion)
                {
                    Console.WriteLine("This patcher only supports Terraria {0}, but we have detected something else {1}.", APIWrapper.TerrariaVersion, vers);
                    Console.Write("There's a high chance this will fail, continue? (y/n)");
                    if (Console.ReadKey(true).Key != ConsoleKey.Y)
                    {
                        return;
                    }
                    Console.WriteLine();
                }
            }
#if SERVER
            Console.Write("Opening up classes for API usage...");
            patcher.MakeTypesPublic(true);
            Console.Write("Ok\nHooking command line...");
            patcher.PatchCommandLine();
            Console.Write("Ok\nHooking players...");
            patcher.PatchPlayer();
            Console.Write("Ok\nRemoving console handlers...");
            patcher.RemoveConsoleHandler();
            Console.Write("Ok\nRemoving mono incompatible code...");
            patcher.SwapProcessPriority();
            ////patcher.HookConsoleTitle();
            Console.Write("Ok\nSkipping sysmenus functions...");
            patcher.SkipMenu();
            //Console.Write("Ok\nFixing code entry...");
            //patcher.FixEntryPoint();
            Console.Write("Ok\nPatching save paths...");
            patcher.FixSavePath();
            Console.Write("Ok\nHooking receive buffer...");
            patcher.HookMessageBuffer();
            //Console.Write("Ok\nAdding the slot manager...");
            //patcher.PatchServer();
            Console.Write("Ok\nPatching XNA...");
            patcher.PatchXNA(true);
            Console.Write("Ok\nHooking start...");
            patcher.HookProgramStart();
            Console.Write("Ok\nHooking initialise...");
            patcher.HookInitialise();
            patcher.HookNetplayInitialise();
            Console.Write("Ok\nHooking into world events...");
            patcher.HookWorldEvents();
            Console.Write("Ok\nHooking statusText...");
            patcher.HookStatusText();
            //Console.Write("Ok\nHooking NetMessage...");
            //patcher.HookNetMessage();
            ////Console.Write("Ok\nRemoving client code...");
            ////patcher.RemoveClientCode();
            Console.Write("Ok\nHooking Server events...");
            patcher.HookUpdateServer();
            patcher.HookDedServEnd();
            Console.Write("Ok\nHooking NPC Spawning...");
            patcher.HookNPCSpawning();
            Console.Write("Ok\nHooking config...");
            patcher.HookConfig();
            ////Console.Write("Ok\nRouting socket implementations...");
            ////patcher.HookSockets();
            Console.Write("Ok\nFixing statusText...");
            patcher.FixStatusTexts();
            Console.Write("Ok\nHooking invasions...");
            patcher.HookInvasions();
            Console.Write("Ok\nEnabling rain...");
            patcher.EnableRaining();
            //Console.Write("Ok\nHooking eclipse...");
            //patcher.HookEclipse();
            //Console.Write("Ok\nHooking blood moon...");
            //patcher.HookBloodMoon();

            Console.Write("Ok\nFixing world removal...");
            patcher.PathFileIO();
            Console.Write("Ok\nRouting network message validity...");
            patcher.HookValidPacketState();

            //We only need one TDSM.exe if this works...
            Console.Write("Ok\nRemoving port forwarding functionality...");
            patcher.FixNetplay();
            //            patcher.DetectMissingXNA();

            Console.Write("Ok\n");
            patcher.InjectHooks();

//            patcher.SwapToVanillaTile(); //Holy shit batman! it works

            //            Console.Write("Ok\nPutting Terraria on a diet...");
            //            patcher.ChangeTileToStruct();
            //Console.Write("Ok\nHooking DEBUG...");
            //patcher.HookWorldFile_DEBUG();

            Console.Write("Ok\n");

            //TODO repace Terraria's Console.SetTitles
#elif CLIENT
            Console.Write("Opening up classes for API usage...");
            patcher.MakeTypesPublic(false);
            Console.Write("Ok\nPatching XNA...");
            patcher.PatchXNA(false);
            Console.Write("Ok\n");
#endif

#if Release
            try
            {
#endif
            //            APIWrapper.Initialise();
            //            byte[] data;
            //            using (var ms = new MemoryStream())
            //            {
            //                patcher.Terraria.Write(ms);
            //                ms.Seek(0, SeekOrigin.Begin);
            //                data = ms.ToArray();
            //            }
            //            data = APIWrapper.InvokeEvent(data, true);
            ////            TDSM.API.Globals.Touch();
            ////
            ////            TDSM.API.PluginManager.SetHookSource(typeof(HookPoints));
            ////            TDSM.API.PluginManager.Initialize(TDSM.API.Globals.PluginPath, TDSM.API.Globals.LibrariesPath);
            ////            TDSM.API.PluginManager.LoadPlugins();
            ////
            ////            var ctx = new TDSM.API.Plugin.HookContext
            ////            {
            ////                Sender = TDSM.API.Plugin.HookContext.ConsoleSender
            ////            };
            ////
            ////            var hookArgs = new HookArgs.PatchServer
            ////            {
            ////                Default = patcher,
            ////#if SERVER
            ////                IsClient = false,
            ////                IsServer = true
            ////#elif CLIENT
            ////                IsClient = true,
            ////                IsServer = false
            ////#endif
            ////            };
            ////            HookPoints.PatchServer.Invoke(ref ctx, ref hookArgs);
            //            //var apiBuild = APIWrapper.Build;
            //            APIWrapper.Finish();
#if Release
        }
        catch (Exception e)
        {
            Console.WriteLine("An exception ocurred during PluginManager.LoadPlugins: {0}", e);
        }
#endif

            Console.ForegroundColor = ConsoleColor.DarkGreen;
            //            //if (isMono || (args != null && args.Where(x => x.ToLower() == "-removeupnp").Count() > 0))
            //            //{
            //            //    Console.Write("Ok\nRemoving port forwarding functionality...");
            //            //    patcher.FixNetplay();
            //            //}
            //            Console.Write("Ok\nSaving to {0}...", outFileMN);
            //            patcher.Save(outFileMN, Build, TDSMGuid, fileName);
            Console.Write("Saving to {0}...", output);
            patcher.Save(output, Build, TDSMGuid, fileName);


            //var t = patcher.Terraria.Netplay.Fields.Single(x => x.Name == "serverSock");


            patcher.Dispose();
            //            Console.WriteLine("Ok");

            Console.ForegroundColor = ConsoleColor.White;
            if (!isMono)
            {
                Console.Write("Ok\nUpdating icons...");
                var res = new Vestris.ResourceLib.IconDirectoryResource(new Vestris.ResourceLib.IconFile("tdsm.ico"));
                foreach (var fl in new string[] { output }) //outFileMS, outFileMN })
                {
                    try
                    {
                        System.Threading.Thread.Sleep(1000);
                        res.SaveTo(fl);
                    }
                    catch
                    {
                        Console.Write("Failed to write icon for: " + fl);
                    }
                }

                Console.Write("Ok\nUpdating headers...");
                foreach (var fl in new string[] { output }) //outFileMS, outFileMN })
                {
                    try
                    {
                        using (var ri = new Vestris.ResourceLib.ResourceInfo())
                        {
                            System.Threading.Thread.Sleep(1000);
                            ri.Load(fl);

                            var ver = (Vestris.ResourceLib.VersionResource)ri[Vestris.ResourceLib.Kernel32.ResourceTypes.RT_VERSION].First();

                            var inf = (Vestris.ResourceLib.StringFileInfo)ver["StringFileInfo"];
                            inf["OriginalFilename"] = fileName + ".exe" + '\0';
                            inf["InternalName"]     = fileName + ".exe" + '\0';
                            inf["ProductName"]      = fileName + '\0';
                            inf["FileDescription"]  = fileName + '\0';

                            ri.Unload();
                            ver.SaveTo(fl);
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Failed to write header for: " + fl);
                    }
                }
            }

            #if DEBUG
            Console.Write("Ok\nUpdating Binaries folder...");
            UpdateBinaries();
            Console.Write("Ok\nGenerating server.config...");
            GenerateConfig();
#endif

#if Release || true
            var noRun = args != null && args.Where(x => x.ToLower() == "-norun").Count() > 0;
            if (!noRun)
            {
                //var current = isMono ? outFileMN : outFileMS;
                //                if (File.Exists("tdsm.exe")) File.Delete("tdsm.exe");
                //                if (isMono)
                //                {
                //                    File.Copy(outFileMN, "tdsm.exe");
                //                }
                //                else
                //                {
                //                    File.Copy(outFileMS, "tdsm.exe");
                //                }
                //                var current = "tdsm.exe";
                Console.WriteLine("Ok");
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine("You may now run {0} as you would normally.", output);
                Console.WriteLine("Press [y] to run {0}, any other key will exit . . .", output);
                if (Console.ReadKey(true).Key == ConsoleKey.Y)
                {
                    if (!isMono)
                    {
                        if (File.Exists("server.config"))
                        {
                            System.Diagnostics.Process.Start(output, "-config server.config");
                        }
                        else
                        {
                            System.Diagnostics.Process.Start(output);
                        }
                    }
                    else
                    {
                        Console.Clear();

                        using (var ms = new MemoryStream())
                        {
                            using (var fs = File.OpenRead(output))
                            {
                                var buff = new byte[256];
                                while (fs.Position < fs.Length)
                                {
                                    var task = fs.Read(buff, 0, buff.Length);
                                    ms.Write(buff, 0, task);
                                }
                            }

                            ms.Seek(0L, SeekOrigin.Begin);
                            var asm = System.Reflection.Assembly.Load(ms.ToArray());
                            try
                            {
                                if (File.Exists("server.config"))
                                {
                                    asm.EntryPoint.Invoke(null, new object[]
                                    {
                                        new string[] { "-config", "server.config", "-noupnp" }
                                    });
                                }
                                else
                                {
                                    asm.EntryPoint.Invoke(null, null);
                                }
                            }
                            catch (Exception e)
                            {
                            }
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("Ok\n");
            }
#endif
        }