static void Main(string[] args) { FileClient hat = new FileClient(args); hat.Run(); /* hat.SendRequest(hat.ConstructRequest()); var response = hat.ParseString(hat.GetResponce()); foreach (var str in response) { Console.WriteLine(str.Replace("\r\n", "")); } // var file = hat.GetFile(41926); // var sha = hat.CalculateSha1(file); var getSize = 0; int.TryParse(response[6], out getSize); Console.WriteLine(getSize); hat.GetBigFile(getSize, "tophat.jpg"); var sha = hat.CalculateSha1("tophat.jpg"); Console.WriteLine(sha); if (sha == response[4]) { Console.WriteLine("MatcH!"); } else { Console.WriteLine("No match :/"); }*/ Console.ReadKey(); }
private static void ExecuteMultipleActions() { var stopwatch = new Stopwatch(); stopwatch.Start(); var taskList = new List <Task>(); for (int i = 0; i < 10; i++) { taskList.Add(Task.Factory.StartNew(() => { var client = new FileClient(); client.Connect(); for (int x = 0; x < 50; x++) { RequestFile(client); SaveFile(client); } })); } Task.WaitAll(taskList.ToArray()); stopwatch.Stop(); Console.WriteLine(string.Concat("Total ", stopwatch.ElapsedMilliseconds, "ms")); }
//protected void btnRegUser_Click(object sender, EventArgs e) //{ // RegServiceClient rsc = new RegServiceClient(); // string level = role.Value; // BASE_USER user = new BASE_USER(); // user.Name = name.Value; // user.Surname = surname.Value; // user.Email = email.Value; // user.Level = level; // user.Pass = password.Value; // string strResponse = rsc.RegisterUser(user); // if (strResponse.ToLower().Contains("succ")) // { // Response.Redirect("LoginPage.aspx"); // } // else // { // Response.Redirect("RegistrationPage.aspx"); // } //} protected void lnkReg_Click(object sender, EventArgs e) { RegServiceClient rsc = new RegServiceClient(); string level = role.Value; BASE_USER user = new BASE_USER(); user.Name = name.Value; user.Surname = surname.Value; user.Email = email.Value; user.Level = level; user.Pass = password.Value; int strResponse = rsc.RegisterUser(user); if (strResponse != 0) //Login Success { //Upload Image makeDirectory(Convert.ToString(strResponse)); //Upload Team Image ImageFile img = new ImageFile(); img = UploadFile(flUserImge, Convert.ToString(strResponse), "User_Image", "Users"); //Upload Event Main's Image to client directory FileClient fc = new FileClient(); string res1 = fc.saveUserImage(img); //Upload Event Main's Image to Database string number = res1; Response.Redirect("LoginPage.aspx"); } else { Response.Redirect("RegistrationPage.aspx"); } }
public static void Main(string[] args) { FileClient client = new FileClient(app_key, master_secret); client.getMedia("qiniu/image/j/D5E5B73186ED3C10BFD9590B5BE2A821"); Console.ReadLine(); }
public void Run() { foreach (var name in FileClient.FileNames("")) { FileClient.Delete(name); } var mainHtml = LoginAndGetMailHtml(); _dataUrl = MainUrl + Regex.Match(mainHtml, @"(?<=""preload"" href=""/)[^""]+(?="" as=)").Value; var nextTime = DateTimeOffset.Now; while (true) { nextTime += _repeatTimeSpan; Work(); var delay = nextTime - DateTimeOffset.Now; if (delay.Milliseconds > 0) { Task.Delay(delay).Wait(); } else { nextTime = DateTimeOffset.Now; } } }
public JsonResult UploadPic() { ReturnMessage result = new ReturnMessage(false) { Message = "上传图片失败!" }; try { HttpPostedFileBase file = Request.Files["fileDataFileName"]; string extansion = System.IO.Path.GetExtension(file.FileName); if (extansion != ".jpg" && extansion != ".png" && extansion != ".gif" && extansion != ".jpeg" && extansion != ".bmp") //Do not create thumb if file is not an image { result.Message = "无效文件"; return(Json(result)); } var imageHost = System.Configuration.ConfigurationManager.AppSettings["ImageHost"] == "" ? string.Format("http://{0}{1}", Request.Url.Host, Request.Url.Port == 80 ? "" : ":" + Request.Url.Port) : System.Configuration.ConfigurationManager.AppSettings["ImageHost"]; var url = string.Format("{0}/Upload/UploadFile", imageHost); FileClient fileClient = new FileClient(); result = fileClient.Post(url, string.Empty, file); if (result.IsSuccess) { result.IsSuccess = true; result.ResultData["path"] = result.ResultData["files"].ToString(); } } catch (Exception ex) { ex.Data["Method"] = "UploadController>>SavePic"; new ExceptionHelper().LogException(ex); } return(Json(result)); }
protected void lnkAddTeam_Click(object sender, EventArgs e) { string role = Convert.ToString(Session["Level"]); int LoggedID = Convert.ToInt32(Session["ID"]); if (role.ToLower().Equals("manager")) { TeamServiceClient teamClient = new TeamServiceClient(); Team _team = new Team(); _team.foreignID = LoggedID; _team.Type = txtCategory.Value; _team.Name = txtName.Value; _team.Desc = txtDesc.Value; _team.NumPlayers = Convert.ToInt32(txtNumPlayer.Text); int TeamID = teamClient.AddTeam(_team); makeDirectory(Convert.ToString(TeamID)); string res = ImportData(flExcel, TeamID); if (res.ToLower().Contains("success")) { //Alert players loaded succesfully } //Upload Team Image ImageFile img = new ImageFile(); img = UploadFile(flImage, Convert.ToString(TeamID), "Team_Images", "Teams"); //Upload Event Main's Image to client directory FileClient fc = new FileClient(); string res1 = fc.saveTeamImage(img); //Upload Event Main's Image to Database string number = res1; // Response.Redirect("Index.aspx"); } else { Response.Redirect("LoginPage.aspx"); } }
public GetFileHandlesAsyncCollection( FileClient client, CancellationToken cancellationToken) : base(cancellationToken) { this._client = client; }
public async Task DownloadFile() { Console.WriteLine($"Descargando archivo. inicio: {DateTime.Now.ToLongTimeString()}"); var fileName = "G:\\test 42mb.pdf"; using var call = FileClient.DownloadStream(new FileRequest { Path = fileName }); try { var result = new StringBuilder(); await foreach (var message in call.ResponseStream.ReadAllAsync()) { result.Append(Encoding.UTF8.GetString(message.Content.ToByteArray())); } // byte[] file = Encoding.ASCII.GetBytes(result.ToString()); // await JSRuntime.SaveFileAs("nuevoDescargado.pdf", Convert.FromBase64String(result.ToString())); await JSRuntime.SaveFileAs("nuevoDescargado.pdf", Convert.FromBase64String(result.ToString())); Console.WriteLine($"Descargó archivo. finalizó: {DateTime.Now.ToLongTimeString()}"); await JSRuntime.SaveFileAs("nuevoDescargado.pdf", Convert.FromBase64String(result.ToString())); Console.WriteLine($"Crear el archivo Cliente. finalizó: {DateTime.Now.ToLongTimeString()}"); } catch (Exception ex) { Console.WriteLine($"DownloadFile Exception => Message {ex.Message} - InnerExceptionMessage {(ex.InnerException != null ? ex.InnerException.Message : "No InnerException")}"); } }
public async Task GetTest(string response) { var mockClient = new Mock <IClient>(); mockClient.Setup(m => m.Receive()) .Returns(Task.FromResult(Encoding.UTF8.GetBytes($"{response.Length} {response}"))); var client = new FileClient(mockClient.Object); var sourcePath = "U:\\test.txt"; var targetPath = $"{TestContext.CurrentContext.TestDirectory}.\\test.txt"; try { await client.Get(sourcePath, targetPath); using (var md5 = MD5.Create()) { var expected = md5.ComputeHash(Encoding.UTF8.GetBytes(response)); using (var stream = File.OpenRead(targetPath)) { var actual = md5.ComputeHash(stream); CollectionAssert.AreEqual(expected, actual); } } mockClient.Verify(m => m.Send($"2 {sourcePath}")); } finally { File.Delete(targetPath); } }
public Byte[] Dependencies(string source) { var tmpPath = Path.Combine(Path.GetTempPath(), string.Format("{0}-{1}", WebConfigurationManager.AppSettings[TASK_DEFINITIONS_ARCHIVE], DateTime.Now.ToFileTimeUtc())); FileClient.CreateZipFromDirectory(source, tmpPath); return(File.ReadAllBytes(tmpPath)); }
/// <summary> /// 读取指定SQL语句,假如指定SQL语句的key不存在,则返回null /// </summary> /// <param name="key">在XML文件中定义的SQL语句名称,格式形为“[实体类名称].[节点ID]”</param> /// <returns>返回sql字符串</returns> public string GetSql(string key) { string sqlString = null; try { string[] sqlLayers = key.Split('.'); XmlNode xmlNode = this.ReadMapping(sqlLayers[0]); if (xmlNode == null || !xmlNode.HasChildNodes) { return(sqlString); } XmlNodeList list = xmlNode.SelectNodes("Sql"); //获取SqlMapper下的所有Sql XmlNode节点(即SQL语句) //根据Key获取SQL语句 sqlString = list.Cast <XmlNode>().ToList().Find(node => node.Attributes["key"].Value.Equals(sqlLayers[1])).InnerText; //sqlString = string.IsNullOrWhiteSpace(sqlString) ? xmlNode.SelectNodes("SqlMap[@key='" + sqlLayers[1] + "']")[0].InnerText : sqlString; //foreach (XmlNode node in list) // if (node.Attributes["key"].Value.Equals(sqlLayers[1])) // return node.InnerText; //sqlString = xmlNode.SelectNodes("SqlMap[@key='" + sqlLayers[1] + "']")[0].InnerText; } catch (Exception e) { FileClient.WriteExceptionInfo(e, string.Format("从XML文件中获取SQL语句出错,key: {0}", key), true); throw; } return(sqlString); }
/// <summary> /// 根据XML节点标识(key),获取属性、字段对应关系实体类数组,假如key不存在,则返回null /// </summary> /// <param name="key">在XML文件中定义的ResultMap节点标识,格式形为“[实体类名称].[节点ID]”</param> /// <returns>返回属性字段对应实体类数组</returns> public PropertyMapper[] GetPropertyMappers(string key) { PropertyMapper[] mappers = null; try { string[] sqlLayers = key.Split('.'); XmlNode xmlNode = this.ReadMapping(sqlLayers[0]); if (xmlNode == null || !xmlNode.HasChildNodes) { return(mappers); } XmlNodeList list = xmlNode.SelectNodes("ResultMap"); //获取SqlMapper下的所有ResultMap XmlNode节点 //根据Key获取SQL语句 XmlNode resultMapNode = list.Cast <XmlNode>().ToList().Find(node => node.Attributes["id"].Value.Equals(sqlLayers[1])); if (resultMapNode != null && resultMapNode.HasChildNodes) { mappers = resultMapNode.SelectNodes("Result").Cast <XmlNode>().Select(node => new PropertyMapper() { PropertyName = node.Attributes["property"].Value, JdbcType = node.Attributes["jdbcType"].Value, ColumnName = node.Attributes["column"].Value }).ToArray(); } } catch (Exception e) { FileClient.WriteExceptionInfo(e, string.Format("从XML文件中获取实体类属性字段对应关系出错,key: {0}", key), true); throw; } return(mappers); }
/// <summary> /// 进行单条SQL语句查询,返回数据表 /// </summary> /// <param name="sqlString">待执行的SQL语句</param> /// <returns>返回数据表</returns> public DataTable Query(string sqlString) { if (string.IsNullOrWhiteSpace(sqlString)) { return(null); } sqlString = sqlString.Trim(' ', ';'); //去除字符串前后的空格与分号,否则报错(ORA-00911: 无效字符) using (OleDbConnection conn = new OleDbConnection(this.ConnStr)) using (OleDbDataAdapter adapter = new OleDbDataAdapter(sqlString, conn)) { DataTable dataTable = new DataTable(); try { //dataSet.EnforceConstraints = false; //禁用约束检查 conn.Open(); adapter.Fill(dataTable); } catch (Exception e) { dataTable = null; FileClient.WriteExceptionInfo(e, "Access SQL语句执行出错", string.Format("SQL语句:{0}", sqlString)); throw; } return(dataTable); } }
public async void DeleteResource_ValidMetadataId_NoExceptionThrown() { // Arrange var dependantResourceModel = new DependantResourceModel { ResourceType = ResourceTypeEnum.Metadata, ResourceId = "c9de8a5e-1ab1-431f-a759-f44d7eef4e19" }; var httpService = new HttpService(new HttpClient()); var fileClient = new FileClient(httpService); Exception exception = null; try { // Act await fileClient.DeleteResource(dependantResourceModel); } catch (Exception e) { exception = e; } // Assert Assert.Null(exception); }
public async void DeleteResource_InternalServerErrorStatusCode_ThrowsException() { // Arrange var httpService = new Mock <IHttpService>(); var httpResponseMessage = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent("") }; httpService .Setup(m => m.DeleteAsync(It.IsAny <string>())) .ReturnsAsync(httpResponseMessage); var fileClient = new FileClient( httpService.Object ); Exception exception = null; try { // Act await fileClient.DeleteResource( DependantResourceDataMocks.MockDependantResourceModel() ); } catch (FailedToDeleteResourceException e) { exception = e; } // Assert Assert.NotNull(exception); }
public AzureFilesPatientReservoir(string connectionString, string shareName) { StorageAccount = CloudStorageAccount.Parse(connectionString); FileClient = StorageAccount.CreateCloudFileClient(); FileShare = FileClient.GetShareReference(shareName); PatientDirectory = FileShare.GetRootDirectoryReference().GetDirectoryReference(fhirFileFolder); }
/// <summary> /// Got some stuff from a client /// </summary> /// <param name="ar"></param> private void OnReceive(IAsyncResult ar) { // got a file command var context = (Context)ar.AsyncState; int bytesRead = context.Client.GetStream().EndRead(ar); string cmd = Encoding.UTF8.GetString(context.Buffer, 0, bytesRead); string[] parts = cmd.Split(';'); string command = parts[0]; // want to send another file if (command == "sendfile") { // context info for receiving files var client = new FileClient(); client.FileName = parts[1]; client.Size = long.Parse(parts[2]); client.FileStream = new FileStream("C:\\" + client.FileName, FileMode.CreateNew, FileAccess.Write); // startup listener where we are going to receive the file. var listener = new TcpListener(IPAddress.Any, 0); // get a kernelassigned number client.Listener = listener; listener.Start(); listener.BeginAcceptTcpClient(OnFileSocket, client); // send reply var ep = (IPEndPoint)listener.LocalEndpoint; byte[] reply = Encoding.UTF8.GetBytes(ep.Port.ToString()); context.Client.GetStream().Write(reply, 0, reply.Length); } }
public IEnumerable <TaskModel> LoadTaskDefinitions() { List <TaskModel> tasks = new List <TaskModel>(); var tasksDestinationRootPath = ConfigurationManager.AppSettings["tasksDefinitionsRootPath"]; if (!Directory.Exists(tasksDestinationRootPath)) { throw new DirectoryNotFoundException(BuildResources.Error_CannotfindTaskDefinitions); } DirectoryInfo info = new DirectoryInfo(tasksDestinationRootPath); var directories = info.EnumerateDirectories(); foreach (var dir in directories) { var files = dir.GetFiles(WebConfigurationManager.AppSettings[TASKS_FILTER]); foreach (var file in files) { var definition = FileClient.ReadAllText(file.FullName); tasks.Add(new TaskModel() { Task = Path.GetFileNameWithoutExtension(file.Name), FullName = file.Name, Path = dir.FullName, Project = dir.Name, Definition = definition, }); } } return(tasks); }
protected void Page_Load(object sender, EventArgs e) { string sportID = Request.QueryString["SportID"]; //Delete Teams //Delete Team Image First //Delete Team Players //Delete Record in Sport League BT //Delete Team players PlayerServiceClient playerClient = new PlayerServiceClient(); string dl_Player = playerClient.Dl_PlayersBySportID(sportID); //Delete Team Image FileClient flClient = new FileClient(); string dl_Image = flClient.deleteTeamImageBySportID(sportID); //Delete from SportLeague Bridging table LeagueClient lgClient = new LeagueClient(); string dl_BridgingTable = lgClient.dl_SprotLeague_BTByID(sportID); //Now delete the team int LoggedID = Convert.ToInt32(Session["ID"]); TeamServiceClient tsc = new TeamServiceClient(); string dl_Sport = tsc.DeleteTeamByID(sportID); if (dl_Sport.Contains("success")) { Response.Redirect("TeamManagement.aspx?UserID=" + LoggedID); } }
public override async Task DisposeAsync() { //await _memoryStream.DisposeAsync(); await FileClient.DeleteAsync(_fileName, _userId); await base.DisposeAsync(); }
/// <summary> /// コンストラクタ /// </summary> /// <param name="clientId">Client ID (ライブラリには含まれまていません)</param> /// <param name="clientSecret">Client Secret (ライブラリには含まれていません)</param> public PixivClient(string clientId, string clientSecret) { ClientId = clientId; ClientSecret = clientSecret; // 2018/03/30 _httpClient = new HttpClient(); _httpClient.DefaultRequestHeaders.Add("App-OS-Version", OsVersion); _httpClient.DefaultRequestHeaders.Add("App-OS", "ios"); _httpClient.DefaultRequestHeaders.Add("App-Version", AppVersion); _httpClient.DefaultRequestHeaders.Add("User-Agent", $"PixivIOSApp/{AppVersion} (iOS {OsVersion}; iPhone9,2)"); // Initialize accesors Application = new ApplicationInfoClient(this); Authentication = new AuthenticationClient(this); Illust = new IllustClient(this); IllustSeries = new IllustSeriesClient(this); Live = new LiveClient(this); Manga = new MangaClient(this); Mute = new MuteClient(this); Notification = new NotificationClient(this); Novel = new NovelClient(this); Search = new SearchClient(this); Spotlight = new SpotlightClient(this); TrendingTags = new TrendingTagsClient(this); User = new UserClient(this); Walkthrough = new WalkthroughClient(this); File = new FileClient(this); }
protected void btnSub_Click(object sender, EventArgs e) { string sportID = Request.QueryString["SportID"]; TeamServiceClient teamClient = new TeamServiceClient(); Team _team = new Team(); // _team.Type = txtType.Text; _team.ID = Convert.ToInt32(sportID); _team.Name = txtName.Value; _team.Desc = txtDesc.Value; _team.NumPlayers = Convert.ToInt32(txtNumPlayer.Text); _team.Category = txtCategory.Value; string res = teamClient.EditTeam(_team); if (res.ToLower().Contains("success")) { //Upload Team Image ImageFile img = new ImageFile(); img = UploadFile(flImage, Convert.ToString(sportID), "Team_Images", "Teams"); //Upload Event Main's Image to client directory FileClient fc = new FileClient(); if (img != null) { string res1 = fc.saveTeamImage(img); //Upload Event Main's Image to Database string number = res1; } //pop-up done! Response.Redirect("ViewTeam.aspx?SportID=" + sportID); } }
/// <summary> /// 向PLC写入信息 /// </summary> public void WriteItemValues() { if (this.Radar == null || this.OpcHelper == null || this.OpcGroup == null) { return; } try { //假如未添加任何OPC项 if (this.OpcGroup.OPCItems.Count == 0) { return; } //TODO 写入雷达监测标签 char[] levels = this.Infos.GetCurrentThreatLevels(); Array itemValues = (new object[] { 0, this.Infos.RadarState.Working, levels[1] - '0', levels[0] - '0', this.Infos.CurrentDistance }).ToArray(); //Array itemValues = (new object[] { 0, this.Infos.RadarState.Working, this.Infos.CurrentThreatLevels[1] - '0', this.Infos.CurrentThreatLevels[0] - '0' }).ToArray(); Array errors; this.OpcGroup.SyncWrite(this.OpcItemNames.Length, ref this.ServerHandlers, ref itemValues, out errors); } catch (Exception ex) { string info = string.Format("OPC写入时出现问题. {0}. radar_id: {1}, ip_address: {2}", ex.Message, this.Radar.Id, this.OpcHelper.Shiploader.OpcServerIp); this.label_opc.SafeInvoke(() => { this.label_opc.Text = info; }); FileClient.WriteExceptionInfo(ex, info, false); } }
public JsonResult SavePic() { RsMessage rs = new RsMessage(); try { HttpPostedFileBase file = Request.Files["fileDataFileName"]; var imageHost = System.Configuration.ConfigurationManager.AppSettings["ImageHost"] == "" ? string.Format("http://{0}{1}", Request.Url.Host, Request.Url.Port == 80 ? "" : ":" + Request.Url.Port) : System.Configuration.ConfigurationManager.AppSettings["ImageHost"]; var url = string.Format("{0}/Upload/UploadFile", imageHost); FileClient fileClient = new FileClient(); var result = fileClient.Post(url, string.Empty, file); if (result.IsSuccess) { rs.success = true; rs.file_path = imageHost + "/" + result.ResultData["files"].ToString(); } } catch (Exception ex) { rs.success = false; ex.Data["Method"] = "ArticleController>>SavePic"; new ExceptionHelper().LogException(ex); } return(Json(rs)); }
protected void lnkSubmit_Click(object sender, EventArgs e) { string LeagueID = Request.QueryString["LeagueID"]; Game game = new Game(); game.TeamOne = txtTeamOne.Value; game.TeamTwo = txtTeamTwo.Value; game.Venue = txtVenue.Value; game.sDate = DateTime.ParseExact(txtDate.Text, "yyyy-MM-ddTHH:mm", CultureInfo.InvariantCulture); game.LeagueID = Convert.ToInt32(LeagueID); makeLeagueDirectory(Convert.ToString(game.LeagueID)); MatchServiceClient msc = new MatchServiceClient(); int GameID = msc.AddMatch(game); //Upload Game Image ImageFile img = new ImageFile(); img = UploadFile(flImage, Convert.ToString(game.LeagueID), "Game_Images", "Leagues"); //uploading an image img.foreignID = Convert.ToString(GameID); FileClient fc = new FileClient(); string res1 = fc.saveGameImage(img); string number = res1; Response.Redirect("ViewGame.aspx?G_ID=" + GameID); }
/// <summary> /// 向PLC写入信息 /// </summary> public void WriteItemValues() { if (this.RadarList == null || this.RadarList.Count == 0 || this.OpcHelper == null || this.OpcGroup == null) { return; } try { //假如未添加任何OPC项 if (this.OpcGroup.OPCItems.Count == 0) { return; } //TODO 写入雷达监测标签 List <object> values = new List <object>() { 0, this.radarState, this.bucketAlarms, this.armAlarms, this.feetAlarms }; values.AddRange(this.RadarList.Select(r => (object)r.CurrentDistance)); Array itemValues = values.ToArray(), errors; this.OpcGroup.SyncWrite(this.OpcItemNames.Length, ref this.ServerHandles, ref itemValues, out errors); } catch (Exception ex) { string info = string.Format("OPC写入时出现问题. {0}. ip_address: {1}", ex.Message, this.OpcHelper.Shiploader.OpcServerIp); this.label_opc.SafeInvoke(() => { this.label_opc.Text = info; }); FileClient.WriteExceptionInfo(ex, info, false); } }
public void sendMessageTest() { FileClient client = new FileClient(app_key, master_secret); ResponseWrapper content = client.getMedia("qiniu/image/j/D5E5B73186ED3C10BFD9590B5BE2A821"); Assert.AreEqual(content.responseCode, HttpStatusCode.OK); }
private async void LoadImg(string photo) { panelImgList.Controls.Clear(); if (photo != null) { string[] imgNames = photo.Trim().Split(' '); string baseurl = "https://localhost:5001/api/file/download?filename="; UC_PicBox pb; Image image; FileClient fileClient = new FileClient(); foreach (string name in imgNames) { string url = baseurl + name; pb = new UC_PicBox(this.DiaryId, name, this.refresh); image = await fileClient.Download(url); if (image != null) { pb.picBox.Image = ResizeImage(image, new Size(200, 200)); pb.Anchor = AnchorStyles.None; panelImgList.Controls.Add(pb); } } } }
private static void RequestFile(FileClient client) { var stopwatch = new Stopwatch(); stopwatch.Start(); var fileName = @"c:\temp\Aktueller Mandant.pdf"; var data = client.GetFile(fileName); //var fileData = client.GetFile(@"c:\temp\test.bmp"); stopwatch.Stop(); Console.WriteLine(string.Concat(stopwatch.ElapsedMilliseconds, "ms")); if (data != null) { File.WriteAllBytes( @"c:\temp\c\" + Guid.NewGuid().ToString() + Path.GetExtension(fileName), data); Console.WriteLine(string.Concat(data.Length, " bytes returned")); } else { Console.WriteLine("no file returned"); } }
private void BtnDelete_Click(object sender, EventArgs e) { string url = string.Format(baseUrl, this.DiaryId, this.FileName); FileClient fileClient = new FileClient(); fileClient.Delete(url); this.Refresh(); }
/// <summary> /// Create a communications client /// </summary> /// <remarks> /// Note that typical connection string should be prefixed with a "protocol=tcp", "protocol=udp", "protocol=serial" or "protocol=file" /// </remarks> /// <returns>A communications client.</returns> /// <param name="connectionString">Connection string for the client.</param> public static IClient Create(string connectionString) { Dictionary<string, string> connectionSettings = connectionString.ParseKeyValuePairs(); IClient client; string protocol; if (connectionSettings.TryGetValue("protocol", out protocol)) { connectionSettings.Remove("protocol"); StringBuilder settings = new StringBuilder(); foreach (string key in connectionSettings.Keys) { settings.Append(key); settings.Append("="); settings.Append(connectionSettings[key]); settings.Append(";"); } // Create a client instance for the specified protocol. switch (protocol.Trim().ToLower()) { case "tls": client = new TlsClient(settings.ToString()); break; case "tcp": client = new TcpClient(settings.ToString()); break; case "udp": client = new UdpClient(settings.ToString()); break; case "file": client = new FileClient(settings.ToString()); break; case "serial": client = new SerialClient(settings.ToString()); break; case "zeromq": client = new ZeroMQClient(settings.ToString()); break; default: throw new ArgumentException(protocol + " is not a valid transport protocol"); } // Apply client settings from the connection string to the client. foreach (KeyValuePair<string, string> setting in connectionSettings) { PropertyInfo property = client.GetType().GetProperty(setting.Key); if (property != null) property.SetValue(client, Convert.ChangeType(setting.Value, property.PropertyType), null); } } else { throw new ArgumentException("Transport protocol must be specified"); } return client; }
/// <summary> /// Initialize data channel. /// </summary> /// <param name="settings">Key/value pairs dictionary parsed from connection string.</param> protected virtual void InitializeDataChannel(Dictionary<string, string> settings) { string setting; // Instantiate selected transport layer switch (m_transportProtocol) { case TransportProtocol.Tcp: // The TCP transport may be set up as a server or as a client, we distinguish // this simply by deriving the value of an added key/value pair in the // connection string called "IsListener" if (settings.TryGetValue("islistener", out setting)) { if (setting.ParseBoolean()) m_serverBasedDataChannel = new TcpServer(); else m_dataChannel = new TcpClient(); } else { // If the key doesn't exist, we assume it's a client connection m_dataChannel = new TcpClient(); } break; case TransportProtocol.Udp: m_dataChannel = new UdpClient(); break; case TransportProtocol.Serial: m_dataChannel = new SerialClient(); break; case TransportProtocol.File: // For file based playback, we allow the option of auto-repeat FileClient fileClient = new FileClient(); fileClient.FileAccessMode = FileAccess.Read; fileClient.FileShareMode = FileShare.Read; fileClient.AutoRepeat = m_autoRepeatCapturedPlayback; m_dataChannel = fileClient; break; default: throw new InvalidOperationException(string.Format("Transport protocol \"{0}\" is not recognized, failed to initialize data channel", m_transportProtocol)); } // Handle primary data connection, this *must* be defined... if (m_dataChannel != null) { // Setup event handlers m_dataChannel.ConnectionEstablished += m_dataChannel_ConnectionEstablished; m_dataChannel.ConnectionAttempt += m_dataChannel_ConnectionAttempt; m_dataChannel.ConnectionException += m_dataChannel_ConnectionException; m_dataChannel.ConnectionTerminated += m_dataChannel_ConnectionTerminated; // Attempt connection to device m_dataChannel.ReceiveDataHandler = Write; m_dataChannel.ReceiveBufferSize = m_bufferSize; m_dataChannel.ConnectionString = m_connectionString; m_dataChannel.MaxConnectionAttempts = m_maximumConnectionAttempts; m_dataChannel.Handshake = false; m_dataChannel.Connect(); m_connectionAttempts = 0; } else if (m_serverBasedDataChannel != null) { // Setup event handlers m_serverBasedDataChannel.ClientConnected += m_serverBasedDataChannel_ClientConnected; m_serverBasedDataChannel.ClientDisconnected += m_serverBasedDataChannel_ClientDisconnected; m_serverBasedDataChannel.ServerStarted += m_serverBasedDataChannel_ServerStarted; m_serverBasedDataChannel.ServerStopped += m_serverBasedDataChannel_ServerStopped; // Listen for device connection m_serverBasedDataChannel.ReceiveClientDataHandler = Write; m_serverBasedDataChannel.ReceiveBufferSize = m_bufferSize; m_serverBasedDataChannel.ConfigurationString = m_connectionString; m_serverBasedDataChannel.MaxClientConnections = 1; m_serverBasedDataChannel.Handshake = false; m_serverBasedDataChannel.Start(); } else throw new InvalidOperationException("No data channel was initialized, cannot start frame parser"); }
/// <summary> /// Create a communications client /// </summary> /// <remarks> /// Note that typical connection string should be prefixed with a "protocol=tcp", "protocol=udp", "protocol=serial" or "protocol=file" /// </remarks> /// <returns>A communications client.</returns> /// <param name="connectionString">Connection string for the client.</param> public static IClient Create(string connectionString) { Dictionary<string, string> connectionData = connectionString.ParseKeyValuePairs(); IClient client = null; string protocol; if (connectionData.TryGetValue("protocol", out protocol)) { connectionData.Remove("protocol"); StringBuilder settings = new StringBuilder(); foreach (string key in connectionData.Keys) { settings.Append(key); settings.Append("="); settings.Append(connectionData[key]); settings.Append(";"); } switch (protocol.ToLower()) { case "tcp": client = new TcpClient(settings.ToString()); break; case "udp": client = new UdpClient(settings.ToString()); break; case "file": client = new FileClient(settings.ToString()); break; case "serial": client = new SerialClient(settings.ToString()); break; default: throw new ArgumentException(protocol + " is not a valid transport protocol."); } } else { throw new ArgumentException("Transport protocol must be specified."); } return client; }