Esempio n. 1
0
 private async Task DownloadFile(byte[] message)
 {
     var dto = MessagePackSerializer.Deserialize <FileDto>(message);
     await FileDownloadService.ReceiveFile(dto.Buffer,
                                           dto.FileName,
                                           dto.MessageId,
                                           dto.EndOfFile,
                                           dto.StartOfFile);
 }
 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
 {
     if (e.CommandName == "delRecord")
     {
         int fd_Id = Convert.ToInt32(e.CommandArgument);
         FileDownloadService.Delete_FileDownload(fd_Id);
         binddata(Convert.ToInt32(((DataTable)ViewState["dtType"]).Rows[0]["FT_ID"]));
     }
 }
Esempio n. 3
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         CommonFunction.isLoginCheck();
         txtTime.Text = DateTime.Now.ToShortDateString();
         int ftid = Convert.ToInt32(Request.QueryString["ftid"]);
         ViewState["dtType"] = FileDownloadService.Get_FileTypeInfo(ftid);
     }
 }
Esempio n. 4
0
        public void TestDownload()
        {
            var localStorage   = new LocalPodcastService("podcasts.json");
            var feedParser     = new FeedParserService();
            var fileManager    = new FileDownloadService();
            var podcastService = new PodcastService(feedParser, localStorage, fileManager);

            var podcastFromService = podcastService.GetPodcastAsync("http://monstercat.com/podcast/feed.xml").Result;

            podcastService.DownloadEpisodeAsync(podcastFromService.Episodes.OrderByDescending(e => e.Published).ToList()[0]).Wait();
        }
        public void ShouldCauseException()
        {
            string targetFolder = "tmp";

            using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
            ILogger <FileDownloadService> logger  = loggerFactory.CreateLogger <FileDownloadService>();
            FileDownloadService           service = new FileDownloadService(logger, null);
            FileDownload fd = Task.Run(async() => await service.GetFileFromUrl(new System.Uri("https://localhost/fake.txt"), "tmp", true).ConfigureAwait(true)).Result;

            Assert.ThrowsAsync <AggregateException>(() => Task.Run(async() => await service.GetFileFromUrl(new System.Uri("https://localhost/fake.txt"), targetFolder, true).ConfigureAwait(true)));
            Directory.Delete(Path.Combine(Directory.GetCurrentDirectory(), targetFolder));
        }
Esempio n. 6
0
        public ActionResult Index()
        {
            if (Session["LoginId"] == null)
            {
                if (CommonUtil.LoginId != string.Empty)
                {
                    Session["LoginId"] = CommonUtil.LoginId;
                    CommonUtil.LoginId = string.Empty;
                }
                else
                {
                    return(RedirectToAction("Account", "Account/LogOn", new { url = Request.Url }));
                }
            }

            object loginId  = Session["LoginId"];
            string username = loginId as string;

            try
            {
                FileDownloadService fds = new FileDownloadService();
                string dbServerip       = ConfigUtil.AppSetting("remoteIP");

                List <Models.MonitorServer> mslist = fds.GetRemoteMSList(dbServerip) ?? new List <Models.MonitorServer>();

                if ("soumu".Equals(username))
                {
                    mslist = mslist.FindAll(x => x.MonitorServerName.Equals("soumu"));
                }
                else if ("mac".Equals(username))
                {
                    mslist = mslist.FindAll(x => !x.MonitorServerName.Equals("soumu"));
                }

                ViewData["msList"] = mslist;
            }
            catch (Exception ex)
            {
                ViewData["msList"] = new List <Models.MonitorServer>();
                logger.Error(ex.Message);
            }

            if (loginId != null)
            {
                if ("admin".Equals(username))
                {
                    return(View());
                }
            }

            return(View("NmIndex"));
        }
Esempio n. 7
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //文件下载
            rptDownLoad.DataSource = FileDownloadService.Get_TopFileDownloadView(1, 6);
            rptDownLoad.DataBind();

            //政策法规
            rptRuleList.DataSource = NewsInfoService.Get_TopNewsInfoViewList("政策法规", 6);
            rptRuleList.DataBind();

            //工作动态
            rptWorkexpress.DataSource = NewsInfoService.Get_TopNewsInfoViewList(1, 6);
            rptWorkexpress.DataBind();

            //高速新闻
            rptGsNews.DataSource = NewsInfoService.Get_TopNewsInfoViewList(2, 6);
            rptGsNews.DataBind();

            //公告公示
            rptSiteNotice.DataSource = NewsInfoService.Get_TopNewsInfoViewList(63, 5);
            rptSiteNotice.DataBind();

            //头2-4条政务信息
            rptTop2_4NewsList.DataSource = NewsInfoService.Get_Top2To5NewsInfoViewList(62);
            rptTop2_4NewsList.DataBind();

            //头1条政务信息
            rptTop1_NewsList.DataSource = NewsInfoService.Get_Top1NewsInfoView(62);
            rptTop1_NewsList.DataBind();

            //高速风采
            rptGsFengCai.DataSource = NewsInfoService.Get_TopAnyPicNews(4, 0);
            rptGsFengCai.DataBind();

            //实时路况
            DataTable dtCurrentRoadCondition = NewsInfoService.Get_TopNewsInfoViewList(80, 0);
            rptCurrentRoadConditon.DataSource = dtCurrentRoadCondition;
            rptCurrentRoadConditon.DataBind();
            lblLJZHZX.Text = "您通行高速公路前可拨打高速交警路况查询电话:0371-68208110查询最新路况。<br><br>";

            //路政单位信息列表
            DataTable dtLZ = DBHelper.GetDataSet("select RD_ID,RD_Name from R_RoadDepart");
            rptLZ.DataSource = dtLZ;
            rptLZ.DataBind();
        }
    }
Esempio n. 8
0
    void binddata()
    {
        DataTable dt = FileDownloadService.Get_TopFileDownloadView(1, 0);

        AspNetPager1.RecordCount = dt.Rows.Count;
        if (dt.Rows.Count >= 0)
        {
            PagedDataSource ps = new PagedDataSource();
            DataView        dv = new DataView(dt);
            ps.DataSource          = dv;
            ps.AllowPaging         = true;
            ps.CurrentPageIndex    = AspNetPager1.CurrentPageIndex - 1;
            ps.PageSize            = AspNetPager1.PageSize;
            rptDownload.DataSource = ps;
            rptDownload.DataBind();
        }
    }
Esempio n. 9
0
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        if (!FileUpload1.HasFile)
        {
            CommonFunction.Alert(Literal1, "请选择要上传的文件");
            return;
        }
        string fileName = CommonFunction.Get_DynamicString() + FileUpload1.FileName;
        string filePath = Server.MapPath("~/DownLoad/" + fileName);
        int    fileSzie = Convert.ToInt32(FileUpload1.PostedFile.ContentLength / 1024);

        FileUpload1.PostedFile.SaveAs(filePath);
        FileDownload download = new FileDownload();

        download.FD_Title      = txtTitle.Text;
        download.FD_FTID       = Convert.ToInt32(((DataTable)ViewState["dtType"]).Rows[0]["FT_ID"]);
        download.FD_Path       = fileName;
        download.FD_Size       = fileSzie + "KB";
        download.FD_CreateDate = txtTime.Text;
        FileDownloadService.Insert_FileDownload(download);
        CommonFunction.AlertAndRedirect(Literal1, "上传成功", "FileDownloadMgr.aspx?ftid=" + Convert.ToInt32(((DataTable)ViewState["dtType"]).Rows[0]["FT_ID"]));
    }
        public void ShouldGetFile()
        {
            string response     = "A simple file";
            string md5Hash      = "ur2T7CGMUXLkYT+IgN4Xy8r33EktY9JrTOm0FZwhh1A="; // This hash has to change if you change the response above
            string targetFolder = "tmp";

            using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
            ILogger <FileDownloadService> logger = loggerFactory.CreateLogger <FileDownloadService>();
            var handlerMock = new Mock <HttpMessageHandler>();

            handlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(response),
            })
            .Verifiable();
            Mock <IHttpClientService> mockHttpClientService = new Mock <IHttpClientService>();

            mockHttpClientService.Setup(s => s.CreateDefaultHttpClient()).Returns(() => new HttpClient(handlerMock.Object));
            FileDownloadService service = new FileDownloadService(logger, mockHttpClientService.Object);
            FileDownload        fd      = Task.Run(async() => await service.GetFileFromUrl(new System.Uri("https://localhost/fake.txt"), targetFolder, true).ConfigureAwait(true)).Result;
            string filename             = Path.Combine(fd.LocalFilePath, fd.Name);

            // Clean up physical artifacts
            File.Delete(filename);
            Directory.Delete(Path.Combine(Directory.GetCurrentDirectory(), targetFolder));

            Assert.True(fd.Hash == md5Hash);
        }
Esempio n. 11
0
        public ActionResult Download()
        {
            try
            {
                //get the path post
                string str = Request.Form["checkFilePath"];
                if (string.IsNullOrWhiteSpace(str))
                {
                    Response.End();
                    return(null);
                }

                string zipfilePath = "";//path
                string zipfileName = "";


                /**
                 * check  session
                 *
                 * if exists then compress the the files to a zip file
                 * else resuming download the zip file
                 *
                 * xiecongwen 20150112
                 *
                 */

                object zipPathHt = Session["zipPathHt"];
                if (zipPathHt != null)
                {
                    Hashtable ht = zipPathHt as Hashtable;
                    if (ht.ContainsKey(str))
                    {
                        zipfilePath = ht[str] as string;
                        goto Download;
                    }
                }
                else
                {
                    Session["zipPathHt"] = new Hashtable();
                }


                #region compress to zip file
                string[] files = str.Split(',');

                files = GetString(files);

                //get the backup server info (xcw 20141202
                FileDownloadService fds = new FileDownloadService();
                budbackup.Models.ServerShareInfo ssi = fds.GetSSI();

                //guarantee the access connection
                Common.PinvokeWindowsNetworking.connectToRemote(ssi.UNCBase, ssi.Username, ssi.Passwd);

                //get the uncpath and insert into list
                //download files from ftp that set——2014-06-04 wjd add
                List <string> fileFTP = new List <string>();
                foreach (string f in files)
                {
                    string uncPath = ssi.UNCBase + f.Substring(f.IndexOf("\\"));    //添加IP,在所建立的网络位置上下载

                    fileFTP.Add(uncPath);
                }

                #region compress and write it to client
                if (fileFTP.Count() > 0)
                {
                    files = fileFTP.ToArray();
                    #region temp Path
                    string tmpPath = ConfigurationManager.AppSettings["TmpPath"];
                    try
                    {
                        if (!Directory.Exists(tmpPath))
                        {
                            Directory.CreateDirectory(tmpPath);
                        }
                        else    //删除超过一周的文件
                        {
                            foreach (string file in Directory.GetFiles(tmpPath))
                            {
                                if ((DateTime.Now - System.IO.File.GetCreationTime(file)).Days >= 7)
                                {
                                    System.IO.File.Delete(file);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.Message);
                    }
                    string ZipedFileName = tmpPath + "\\" + DateTime.Now.ToFileTime().ToString() + Common.RandomCode.GetCode(1) + ".zip";
                    #endregion

                    ZipIonicHelper.ZipAdvanced(files, ZipedFileName, ssi.UNCBase);
                    zipfilePath = ZipedFileName;    //path
                    zipfileName = Path.GetFileName(ZipedFileName);

                    (Session["zipPathHt"] as Hashtable).Add(str, zipfilePath);
                }
                else
                {
                    zipfilePath = files[0];    //path
                    zipfileName = Path.GetFileName(files[0]);
                }
                #endregion
                #endregion


Download:       //resuming download
                {
                    zipfileName = Path.GetFileName(zipfilePath);
                    if (System.IO.File.Exists(zipfilePath))
                    {
                        Response.Clear();
                        int BUFFERSize = 1024 * 1024 * 2;
                        // Buffer to read 10K bytes in chunk:
                        byte[] buffer = new Byte[BUFFERSize];
                        // Length of the file:
                        int length;

                        // Total bytes to read:
                        long dataToRead;

                        FileStream iStream = new System.IO.FileStream(zipfilePath, System.IO.FileMode.Open,
                                                                      System.IO.FileAccess.Read, System.IO.FileShare.Read);
                        // Total bytes to read:
                        dataToRead = iStream.Length;
                        long p = 0;
                        if (Request.Headers["Range"] != null)
                        {
                            Response.StatusCode = 206;
                            p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
                        }

                        Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString());

                        Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString());
                        Response.ContentType = "application/octet-stream";
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(Request.ContentEncoding.GetBytes(zipfileName)));
                        //use this to tell client that file is sending
                        String     TOKEN    = "downloadToken";
                        HttpCookie dtCookie = new HttpCookie(TOKEN);
                        dtCookie.Value = Request.Form[TOKEN];
                        Response.Cookies.Add(dtCookie);

                        iStream.Position = p;
                        dataToRead       = dataToRead - p;
                        // Read the bytes.
                        while (dataToRead > 0)
                        {
                            // Verify that the client is connected.
                            if (Response.IsClientConnected)
                            {
                                // Read the data in buffer.
                                length = iStream.Read(buffer, 0, BUFFERSize);

                                // Write the data to the current output stream.
                                Response.OutputStream.Write(buffer, 0, length);

                                // Flush the data to the HTML output.
                                Response.Flush();

                                buffer     = new Byte[BUFFERSize];
                                dataToRead = dataToRead - length;
                            }
                            else
                            {
                                //prevent infinite loop if user disconnects
                                dataToRead = -1;
                            }
                        }

                        iStream.Close();
                        Response.End();
                        return(null);
                    }
                    else
                    {
                        //Session["fileexists"] = "no";
                        return(RedirectToAction("Index", "FileDownload"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString() + ex.Message);
            }

            return(RedirectToAction("Index", "FileDownload"));
        }
Esempio n. 12
0
        /// <summary>
        /// 最新的 查询文件
        /// </summary>
        /// <param name="monitorFileName"></param>
        /// <param name="monitorServerID"></param>
        /// <param name="dirname"></param>
        /// <param name="pindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public ActionResult Search_new(string monitorFileName, string monitorServerID, int pindex)
        {
            string result = string.Empty;

            //判断用户是否登陆
            if (Session["LoginId"] == null)
            {
                result = "-99";
            }
            else
            {
                #region 根据条件查询 并 拼凑html (xiecongwen 20141203
                object loginId  = Session["LoginId"];
                string username = loginId as string;
                //save
                try
                {
                    //get the pagesize
                    int pagesize = 20;
                    //max entry count that should be search
                    int maxSize = 200;

                    #region 根据条件查询
                    //get the result match the condition
                    FileDownloadService fds = new FileDownloadService();
                    budbackup.Models.DownloadSearchResult ds = null;
                    //check session
                    object dsr = Session["DownloadSearchResult"];
                    if (dsr != null)
                    {
                        budbackup.Models.DownloadSearchResult dstemp = dsr as budbackup.Models.DownloadSearchResult;
                        if (dstemp.SearchPattern.Equals(monitorFileName) && dstemp.MonitorServerID.Equals(monitorServerID))
                        {
                            ds = dstemp;
                        }
                    }

                    //get from db
                    if (ds == null)
                    {
                        ds = fds.GetMatchList(monitorFileName, monitorServerID, maxSize, username);
                        //save into session
                        if (ds != null && ds.Count > 0)
                        {
                            ds.SearchPattern   = monitorFileName;
                            ds.MonitorServerID = monitorServerID;
                            Session["DownloadSearchResult"] = ds;
                        }
                    }
                    #endregion

                    #region 拼凑html语句
                    jsonData jd = new jsonData();

                    StringBuilder tableTR = new StringBuilder();
                    if (ds != null && ds.Count > 0)
                    {
                        string fileTRFormat = "<tr>" +
                                              "           <td class=\"cel1\" style=\"text-align:center;line-height:28px;\"><input type=\"checkbox\" value='{0}' class=\"filePath\" name=\"monitorFileLocalPath[]\" title=\"{4}\"/></td>" +
                                              "           <td class=\"cel2\">{1}</td>" +
                                              "           <td class=\"cel2\">{2}</td>" +
                                              "           <td class=\"cel3\">{3}</td>" +
                                              //"           <td class=\"cel4\">{4}</td>" +
                                              "       </tr>";
                        #region resolve get the page

                        int min = (pindex - 1) * pagesize;
                        int max = pindex * pagesize - 1;

                        int folderListCount = ds.FolderInfoList.Count;
                        //folder フォルダー
                        while (folderListCount > min)
                        {
                            if (min > max)
                            {
                                break;
                            }

                            budbackup.Models.DFolderInfo dfi = ds.FolderInfoList[min];
                            //dfi.MacPath.Replace(@"\", @"\\") escape
                            tableTR.Append(string.Format(fileTRFormat, dfi.WinPath.Replace(@"\", @"\\"), "フォルダー", dfi.Name, dfi.MacPath.Replace(@"\", @"\\"), min));

                            min++;
                        }

                        //file ファイル
                        if (max > folderListCount)
                        {
                            min -= folderListCount;
                            max -= folderListCount;
                            while (ds.FileInfoList.Count > min)
                            {
                                if (min > max)
                                {
                                    break;
                                }

                                budbackup.Models.DFileInfo dfi = ds.FileInfoList[min];

                                tableTR.Append(string.Format(fileTRFormat, dfi.WinPath.Replace(@"\", @"\\"), "ファイル", dfi.Name, dfi.MacPath.Replace(@"\", @"\\"), min + folderListCount));

                                min++;
                            }
                        }
                        //page element
                        int pageCount = (ds.Count + pagesize - 1) / pagesize;
                        jd.Add("logList", tableTR.ToString())
                        .Add("pageCount", pageCount)
                        .Add("pindex", pindex)
                        .Add("totalCount", ds.Count);

                        #endregion
                    }
                    else
                    {
                        tableTR.Append("<tr><td colspan=\"5\" style=\"text-align:center;line-height:28px;\">データがありません。</td></tr>");
                        jd.Add("logList", tableTR.ToString())
                        .Add("pageCount", 0)
                        .Add("pindex", pindex)
                        .Add("totalCount", 0);
                    }


                    result = jd.ToString();

                    #endregion
                }
                catch (Exception ex)
                {
                    result = "-10";
                    logger.Error(ex.Message);
                }
                #endregion
            }

            Response.Write(result);
            Response.End();

            return(null);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //规章制度
            DataTable dtGZZD = NewsInfoService.Get_TopNewsInfoViewList(33, 8);
            rptGZZD.DataSource = dtGZZD;
            rptGZZD.DataBind();

            //文明创建
            DataTable dtWMCJ = NewsInfoService.Get_TopNewsInfoViewList(34, 8);
            rptWMCJ.DataSource = dtWMCJ;
            rptWMCJ.DataBind();

            //养护交流
            DataTable dtYHJL = NewsInfoService.Get_TopNewsInfoViewList(35, 12);
            rptYHJL.DataSource = dtYHJL;
            rptYHJL.DataBind();

            //养护新技术、新材料、新设备
            DataTable dtYHXJS = NewsInfoService.Get_TopNewsInfoViewList(36, 4);
            rptYHXJS.DataSource = dtYHXJS;
            rptYHXJS.DataBind();
            //养护管理
            DataTable dtYHGL = NewsInfoService.Get_TopNewsInfoViewList(37, 4);
            rptYHGL.DataSource = dtYHGL;
            rptYHGL.DataBind();
            //施工公告
            DataTable dtSGGG = NewsInfoService.Get_TopNewsInfoViewList(38, 4);
            rptSGGG.DataSource = dtSGGG;
            rptSGGG.DataBind();
            //公路技术状况评定
            DataTable dtJSPD = NewsInfoService.Get_TopNewsInfoViewList(39, 4);
            rptJSPD.DataSource = dtJSPD;
            rptJSPD.DataBind();

            //办事指南
            DataTable dtBSZN = NewsInfoService.Get_TopNewsInfoViewList(31, 6);
            rptBSZN.DataSource = dtBSZN;
            rptBSZN.DataBind();

            //养护动态
            DataTable dtYHDT = NewsInfoService.Get_TopNewsInfoViewList(30, 6);
            rptYHDT.DataSource = dtYHDT;
            rptYHDT.DataBind();

            //基层资讯
            DataTable dtJCZX = NewsInfoService.Get_TopNewsInfoViewList(32, 7);
            rptJCZX.DataSource = dtJCZX;
            rptJCZX.DataBind();

            //通知公告
            DataTable dtTZGG = NewsInfoService.Get_TopNewsInfoViewList(41, 5);
            rptTZGG.DataSource = dtTZGG;
            rptTZGG.DataBind();

            //资料下载
            DataTable dtDownLoad = FileDownloadService.Get_TopFileDownloadView(3, 7);
            rptDownLoad.DataSource = dtDownLoad;
            rptDownLoad.DataBind();

            //养护掠影
            DataTable dtYHMien = NewsInfoService.Get_TopNewsInfoViewList(40, 0);
            rptYHMien.DataSource = dtYHMien;
            rptYHMien.DataBind();
        }
    }
Esempio n. 14
0
        private void ApplyConnectionHandlers()
        {
            // TODO: Remove circular dependencies and the need for static IServiceProvider instance
            // by emitting these events so other services can listen for them.
            var conductor = ServiceContainer.Instance.GetRequiredService <Conductor>();

            Connection.Closed += (ex) =>
            {
                Logger.Write($"Connection closed.  Error: {ex?.Message}");
                return(Task.CompletedTask);
            };

            Connection.On("ReceiveIceCandidate", (string candidate, int sdpMlineIndex, string sdpMid, string viewerID) =>
            {
                try
                {
                    if (conductor.Viewers.TryGetValue(viewerID, out var viewer))
                    {
                        viewer.RtcSession.AddIceCandidate(sdpMid, sdpMlineIndex, candidate);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                }
            });

            Connection.On("ReceiveRtcAnswer", async(string sdp, string viewerID) =>
            {
                try
                {
                    if (conductor.Viewers.TryGetValue(viewerID, out var viewer))
                    {
                        await viewer.RtcSession.SetRemoteDescription("answer", sdp);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                }
            });

            Connection.On("ClipboardTransfer", (string transferText, bool typeText, string viewerID) =>
            {
                try
                {
                    if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                    {
                        if (typeText)
                        {
                            KeyboardMouseInput.SendText(transferText, viewer);
                        }
                        else
                        {
                            ClipboardService.SetText(transferText);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                }
            });

            Connection.On("CtrlAltDel", async(string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    await SendCtrlAltDel();
                }
            });

            Connection.On("Disconnect", async(string reason) =>
            {
                Logger.Write($"Disconnecting caster socket.  Reason: {reason}");
                await DisconnectAllViewers();
            });

            Connection.On("GetScreenCast", (string viewerID, string requesterName, bool notifyUser) =>
            {
                try
                {
                    ScreenCaster.BeginScreenCasting(new ScreenCastRequest()
                    {
                        NotifyUser    = notifyUser,
                        ViewerID      = viewerID,
                        RequesterName = requesterName
                    });
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                }
            });

            Connection.On("GetWindowsSessions", async(string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer))
                {
                    await viewer.SendWindowsSessions();
                }
            });

            Connection.On("RequestScreenCast", (string viewerID, string requesterName, bool notifyUser) =>
            {
                conductor.InvokeScreenCastRequested(new ScreenCastRequest()
                {
                    NotifyUser    = notifyUser,
                    ViewerID      = viewerID,
                    RequesterName = requesterName
                });
            });

            Connection.On("KeyDown", (string key, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.SendKeyDown(key, viewer);
                }
            });

            Connection.On("KeyUp", (string key, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.SendKeyUp(key, viewer);
                }
            });

            Connection.On("KeyPress", async(string key, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.SendKeyDown(key, viewer);
                    await Task.Delay(1);
                    KeyboardMouseInput.SendKeyUp(key, viewer);
                }
            });

            Connection.On("MouseMove", (double percentX, double percentY, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.SendMouseMove(percentX, percentY, viewer);
                }
            });

            Connection.On("MouseDown", (int button, double percentX, double percentY, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    if (button == 0)
                    {
                        KeyboardMouseInput.SendLeftMouseDown(percentX, percentY, viewer);
                    }
                    else if (button == 2)
                    {
                        KeyboardMouseInput.SendRightMouseDown(percentX, percentY, viewer);
                    }
                }
            });

            Connection.On("MouseUp", (int button, double percentX, double percentY, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    if (button == 0)
                    {
                        KeyboardMouseInput.SendLeftMouseUp(percentX, percentY, viewer);
                    }
                    else if (button == 2)
                    {
                        KeyboardMouseInput.SendRightMouseUp(percentX, percentY, viewer);
                    }
                }
            });

            Connection.On("MouseWheel", (double deltaX, double deltaY, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.SendMouseWheel(-(int)deltaY, viewer);
                }
            });
            Connection.On("SetKeyStatesUp", (string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.SetKeyStatesUp();
                }
            });
            Connection.On("ViewerDisconnected", async(string viewerID) =>
            {
                await Connection.SendAsync("DisconnectViewer", viewerID, false);
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer))
                {
                    viewer.DisconnectRequested = true;
                    viewer.Dispose();
                }
                conductor.InvokeViewerRemoved(viewerID);
            });
            Connection.On("FrameReceived", (string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer))
                {
                    for (int i = 0; i < 5; i++)
                    {
                        if (viewer.PendingSentFrames.TryDequeue(out _))
                        {
                            break;
                        }
                    }
                }
            });

            Connection.On("SelectScreen", (string displayName, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer))
                {
                    viewer.Capturer.SetSelectedScreen(displayName);
                }
            });

            Connection.On("QualityChange", (int qualityLevel, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer))
                {
                    viewer.ImageQuality = qualityLevel;
                }
            });

            Connection.On("AutoQualityAdjust", (bool isOn, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer))
                {
                    viewer.AutoAdjustQuality = isOn;
                }
            });

            Connection.On("ReceiveFile", async(byte[] buffer, string fileName, string messageId, bool endOfFile, bool startOfFile) =>
            {
                await FileDownloadService.ReceiveFile(buffer, fileName, messageId, endOfFile, startOfFile);
            });

            Connection.On("ToggleAudio", (bool toggleOn, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    AudioCapturer.ToggleAudio(toggleOn);
                }
            });
            Connection.On("ToggleBlockInput", (bool toggleOn, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.ToggleBlockInput(toggleOn);
                }
            });

            Connection.On("ToggleWebRtcVideo", (bool toggleOn, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer))
                {
                    viewer.ToggleWebRtcVideo(toggleOn);
                }
            });

            Connection.On("TouchDown", (string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    //User32.GetCursorPos(out var point);
                    //Win32Interop.SendLeftMouseDown(point.X, point.Y);
                }
            });
            Connection.On("LongPress", (string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    //User32.GetCursorPos(out var point);
                    //Win32Interop.SendRightMouseDown(point.X, point.Y);
                    //Win32Interop.SendRightMouseUp(point.X, point.Y);
                }
            });
            Connection.On("TouchMove", (double moveX, double moveY, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    //User32.GetCursorPos(out var point);
                    //Win32Interop.SendMouseMove(point.X + moveX, point.Y + moveY);
                }
            });
            Connection.On("TouchUp", (string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    //User32.GetCursorPos(out var point);
                    //Win32Interop.SendLeftMouseUp(point.X, point.Y);
                }
            });
            Connection.On("Tap", (double percentX, double percentY, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.SendLeftMouseDown(percentX, percentY, viewer);
                    KeyboardMouseInput.SendLeftMouseUp(percentX, percentY, viewer);
                }
            });

            Connection.On("SharedFileIDs", (List <string> fileIDs) =>
            {
                fileIDs.ForEach(id =>
                {
                    var url         = $"{conductor.Host}/API/FileSharing/{id}";
                    var webRequest  = WebRequest.CreateHttp(url);
                    var response    = webRequest.GetResponse();
                    var contentDisp = response.Headers["Content-Disposition"];
                    var fileName    = contentDisp
                                      .Split(";".ToCharArray())
                                      .FirstOrDefault(x => x.Trim().StartsWith("filename"))
                                      .Split("=".ToCharArray())[1];

                    var legalChars = fileName.ToCharArray().Where(x => !Path.GetInvalidFileNameChars().Any(y => x == y));

                    fileName = new string(legalChars.ToArray());

                    var dirPath  = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "RemotelySharedFiles")).FullName;
                    var filePath = Path.Combine(dirPath, fileName);
                    using (var fs = new FileStream(filePath, FileMode.Create))
                    {
                        using (var rs = response.GetResponseStream())
                        {
                            rs.CopyTo(fs);
                        }
                    }
                    Process.Start("explorer.exe", dirPath);
                });
            });

            Connection.On("SessionID", (string sessionID) =>
            {
                conductor.InvokeSessionIDChanged(sessionID);
            });
        }
Esempio n. 15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //行业规章
            DataTable dtHYGZ = NewsInfoService.Get_TopNewsInfoViewList(20, 6);
            rptHYGZ.DataSource = dtHYGZ;
            rptHYGZ.DataBind();

            //经验交流
            DataTable dtJYJL = NewsInfoService.Get_TopNewsInfoViewList(21, 6);
            rptJYJL.DataSource = dtJYJL;
            rptJYJL.DataBind();

            //资料下载
            DataTable dtDownload = FileDownloadService.Get_TopFileDownloadView(2, 6);
            rptDownLoad.DataSource = dtDownload;
            rptDownLoad.DataBind();

            //ISO国际标准化认证
            DataTable dtISO = NewsInfoService.Get_TopNewsInfoViewList(24, 6);
            rptISO.DataSource = dtISO;
            rptISO.DataBind();

            //通知公告
            DataTable dtTZGG = NewsInfoService.Get_TopNewsInfoViewList(25, 6);
            rptTZGG.DataSource = dtTZGG;
            rptTZGG.DataBind();

            //驿站新闻
            DataTable dtServiceNews = NewsInfoService.Get_TopNewsInfoViewList(26, 8);
            rptServiceNews.DataSource = dtServiceNews;
            rptServiceNews.DataBind();

            //驿站文化
            DataTable dtYZWH = NewsInfoService.Get_TopNewsInfoViewList(27, 6);
            rptYZWH.DataSource = dtYZWH;
            rptYZWH.DataBind();

            //行业报刊
            DataTable dtNewsPaper = NewsPaperService.Get_NewsPaperList(4);
            rptNewsPaper.DataSource = dtNewsPaper;
            rptNewsPaper.DataBind();

            //所有服务区列表
            DataTable dtServices = PubClass.DBHelper.GetDataSet("select top 36 * from T_ServiceInfo order by S_QuarterRank asc,S_Star desc");
            rptServices.DataSource = dtServices;
            rptServices.DataBind();

            //特色服务区
            DataTable dtTSFWQ = NewsInfoService.Get_TopNewsInfoViewList(130, 10);
            rptTSFWQ.DataSource = dtTSFWQ;
            rptTSFWQ.DataBind();

            //开图走四方
            DataTable dtKTZSF = NewsInfoService.Get_TopNewsInfoViewList(131, 10);
            rptKTZSF.DataSource = dtKTZSF;
            rptKTZSF.DataBind();

            //精品旅游线路
            DataTable dtJPLYXL = NewsInfoService.Get_TopNewsInfoViewList(132, 10);
            rptJPLYXL.DataSource = dtJPLYXL;
            rptJPLYXL.DataBind();

            //吃住行游
            DataTable dtCZXY = NewsInfoService.Get_TopNewsInfoViewList(133, 10);
            rptCZXY.DataSource = dtCZXY;
            rptCZXY.DataBind();

            //古道遗风
            DataTable dtGDYF = NewsInfoService.Get_TopNewsInfoViewList(134, 10);
            rptGDYF.DataSource = dtGDYF;
            rptGDYF.DataBind();
        }
    }
Esempio n. 16
0
 public FileController(FileDownloadService fileDownloadService, FileService fileService)
 {
     _fileDownloadService = fileDownloadService;
     _fileService         = fileService;
 }