public Form1() { InitializeComponent(); WebClient client = new WebClient(); Stream stream1 = client.OpenRead("http://www.baidu.cn"); StreamReader sr = new StreamReader(stream1); string line; while ((line = sr.ReadLine()) != null) { listBox1.Items.Add(line); } stream1.Close(); try { Stream stream2 = client.OpenWrite("http://localhost/accept/newfile.txt", "PUT"); StreamWriter sw = new StreamWriter(stream2); sw.WriteLine("Hello Web"); stream2.Close(); } catch (System.Exception) { } //异步加载WebRequest WebRequest wr = WebRequest.Create("http://www.reuters.com"); wr.BeginGetResponse(new AsyncCallback(OnResponse), wr); }
public void OnBeginRequest_Should_Compress_Whitespace() { //arrange _httpRequest.SetupGet(request => request.Url).Returns(new Uri("http://www.mysite.com/")); _httpRequest.SetupGet(request => request.RawUrl).Returns("http://www.mysite.com/default.aspx"); _httpRequest.SetupGet(request => request.Headers) .Returns(new NameValueCollection {{"Accept-Encoding", "Gzip"}}); using (var client = new WebClient()) { client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); _httpResponse.SetupGet(response => response.Filter).Returns(client.OpenWrite("http://www.hao123.net")); } _httpCachePolicy.SetupGet(hc => hc.VaryByHeaders).Returns(new HttpCacheVaryByHeaders()); _httpResponse.SetupGet(response => response.Cache).Returns(_httpCachePolicy.Object); // act var module = new CompressWhitespaceModule(); module.OnBeginRequest(_httpContext.Object); //assert _httpResponse.VerifyAll(); }
public void RSPEC_WebClient(string address, Uri uriAddress, byte[] data, NameValueCollection values) { System.Net.WebClient webclient = new System.Net.WebClient(); // All of the following are Questionable although there may be false positives if the URI scheme is "ftp" or "file" //webclient.Download * (...); // Any method starting with "Download" webclient.DownloadData(address); // Noncompliant webclient.DownloadDataAsync(uriAddress, new object()); // Noncompliant webclient.DownloadDataTaskAsync(uriAddress); // Noncompliant webclient.DownloadFile(address, "filename"); // Noncompliant webclient.DownloadFileAsync(uriAddress, "filename"); // Noncompliant webclient.DownloadFileTaskAsync(address, "filename"); // Noncompliant webclient.DownloadString(uriAddress); // Noncompliant webclient.DownloadStringAsync(uriAddress, new object()); // Noncompliant webclient.DownloadStringTaskAsync(address); // Noncompliant // Should not raise for events webclient.DownloadDataCompleted += Webclient_DownloadDataCompleted; webclient.DownloadFileCompleted += Webclient_DownloadFileCompleted; webclient.DownloadProgressChanged -= Webclient_DownloadProgressChanged; webclient.DownloadStringCompleted -= Webclient_DownloadStringCompleted; //webclient.Open * (...); // Any method starting with "Open" webclient.OpenRead(address); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ {{Make sure that this http request is sent safely.}} webclient.OpenReadAsync(uriAddress, new object()); // Noncompliant webclient.OpenReadTaskAsync(address); // Noncompliant webclient.OpenWrite(address); // Noncompliant webclient.OpenWriteAsync(uriAddress, "STOR", new object()); // Noncompliant webclient.OpenWriteTaskAsync(address, "POST"); // Noncompliant webclient.OpenReadCompleted += Webclient_OpenReadCompleted; webclient.OpenWriteCompleted += Webclient_OpenWriteCompleted; //webclient.Upload * (...); // Any method starting with "Upload" webclient.UploadData(address, data); // Noncompliant webclient.UploadDataAsync(uriAddress, "STOR", data); // Noncompliant webclient.UploadDataTaskAsync(address, "POST", data); // Noncompliant webclient.UploadFile(address, "filename"); // Noncompliant webclient.UploadFileAsync(uriAddress, "filename"); // Noncompliant webclient.UploadFileTaskAsync(uriAddress, "POST", "filename"); // Noncompliant webclient.UploadString(uriAddress, "data"); // Noncompliant webclient.UploadStringAsync(uriAddress, "data"); // Noncompliant webclient.UploadStringTaskAsync(uriAddress, "data"); // Noncompliant webclient.UploadValues(address, values); // Noncompliant webclient.UploadValuesAsync(uriAddress, values); // Noncompliant webclient.UploadValuesTaskAsync(address, "POST", values); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // Should not raise for events webclient.UploadDataCompleted += Webclient_UploadDataCompleted; webclient.UploadFileCompleted += Webclient_UploadFileCompleted; webclient.UploadProgressChanged -= Webclient_UploadProgressChanged; webclient.UploadStringCompleted -= Webclient_UploadStringCompleted; webclient.UploadValuesCompleted -= Webclient_UploadValuesCompleted; }
public void SendMessage(Lamp lampState) { WebClient webClient = new WebClient(); webClient.BaseAddress = "http://" + bridgeIP + "/api/" + username + "/lights/" + lampState.GetLampNumber() + "/state"; Stream writeData = webClient.OpenWrite(webClient.BaseAddress, "PUT"); writeData.Write(Encoding.ASCII.GetBytes(lampState.GetJson()), 0, lampState.GetJson().Length); writeData.Close(); }
static void Example10() { string address = @"C:\Users\Giang\Desktop\UploadInHear.txt"; string postData = "GiangPDH"; byte[] postArray = System.Text.Encoding.ASCII.GetBytes(postData); System.Net.WebClient wc = new System.Net.WebClient(); Stream postStream = wc.OpenWrite(address); postStream.Write(postArray, 0, postArray.Length); postStream.Close(); }
public static bool UploadFile(string localFilePath, string serverFolder, bool reName) { string fileNameExt, newFileName, uriString; if (reName) { fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf(".") + 1); newFileName = DateTime.Now.ToString("yyMMddhhmmss") + fileNameExt; } else { newFileName = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1); } if (!serverFolder.EndsWith("/") && !serverFolder.EndsWith("\\")) { serverFolder = serverFolder + "/"; } uriString = serverFolder + newFileName; //服务器保存路径 /**/ /// 创建WebClient实例 WebClient myWebClient = new WebClient(); myWebClient.Credentials = CredentialCache.DefaultCredentials; // 要上传的文件 FileStream fs = new FileStream(newFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); //FileStream fs = new FileStream(newFileName, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs); try { //使用UploadFile方法可以用下面的格式 //myWebClient.UploadFile(uriString,"PUT",localFilePath); byte[] postArray = r.ReadBytes((int)fs.Length); Stream postStream = myWebClient.OpenWrite(uriString, "PUT"); if (postStream.CanWrite) { postStream.Write(postArray, 0, postArray.Length); } else { MessageBox.Show("文件目前不可写!"); } postStream.Close(); } catch { //MessageBox.Show("文件上传失败,请稍候重试~"); return false; } return true; }
static void PostFood(Food food) { using (var client = new WebClient()) { client.Headers[HttpRequestHeader.ContentType] = "application/json"; var uri = new Uri("http://localhost:3401/api/foodapi/"); using (var stream = client.OpenWrite(uri, "POST")) { var serializer = new DataContractJsonSerializer(typeof(Food)); serializer.WriteObject(stream, food); stream.Close(); } } }
static void Main(string[] args) { // // TODO: Add code to start application here // WebClient webClient = new WebClient(); try { Stream stream = webClient.OpenWrite("http://localhost/accept/newfile.txt","PUT"); StreamWriter streamWriter = new StreamWriter(stream); streamWriter.WriteLine("Hello there, World...."); streamWriter.Close(); } catch (Exception e) {Console.WriteLine( e.ToString() ); } Console.ReadLine(); }
public void UpLoadFile(string fileNamePath) { /// 创建WebClient实例 WebClient myWebClient = new WebClient(); myWebClient.Credentials = CredentialCache.DefaultCredentials; // 要上传的文件 FileStream fs = new FileStream("C:\\1.zip", FileMode.Open, FileAccess.Read); //FileStream fs = OpenFile(); BinaryReader r = new BinaryReader(fs); byte[] postArray = r.ReadBytes((int)fs.Length); //Stream postStream = myWebClient.OpenWrite(FileName, "PUT"); //Stream postStream = myWebClient.OpenWrite("~/Upload/" + FileName, "PUT"); //C:\文档资料\自动化测试平台\ATP20140629\ATP\Upload Stream postStream = myWebClient.OpenWrite("C:\\" + FileName, "PUT"); try { if (postStream.CanWrite) { postStream.Write(postArray, 0, postArray.Length); postStream.Close(); fs.Dispose(); } else { postStream.Close(); fs.Dispose(); } } catch (Exception err) { postStream.Close(); fs.Dispose(); throw err; } finally { postStream.Close(); fs.Dispose(); } }
/// <summary> /// Publish the opml document to the specified location. /// </summary> /// <param name="uri">The URI of the resource to receive the data. </param> /// <param name="method">The method used to send the data to the resource. (POST)</param> /// <param name="proxy">HTTP proxy settings for the WebRequest class.</param> /// <param name="networkCredential">Credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication.</param> /// <example> /// This sample shows how to publish (Default Proxy) /// <code> /// // password-based authentication for web resource /// System.Net.NetworkCredential providerCredential = new System.Net.NetworkCredential("username", "password", "domain"); /// // use default system proxy /// Uri uri = new Uri("http://domain.net"); /// Publish(uri, null, "POST", providerCredential); /// </code> /// This sample shows how to publish (Custom Proxy) /// <code> /// // password-based authentication for web resource /// System.Net.NetworkCredential providerCredential = new System.Net.NetworkCredential("username", "password", "domain"); /// // password-based authentication for web proxy /// System.Net.NetworkCredential proxyCredential = new System.Net.NetworkCredential("username", "password", "domain"); /// // create custom proxy /// System.Net.WebProxy webProxy = new System.Net.WebProxy("http://proxyurl:8080",false); /// webProxy.Credentials = proxyCredential; /// // publish /// Publish(uri, webProxy, "POST", providerCredential); /// </code> /// </example> public virtual void Publish(Uri uri, System.Net.WebProxy proxy, string method, System.Net.NetworkCredential networkCredential) { System.IO.Stream stream = null; try { // TODO: webproxy support System.Net.WebClient wc = new System.Net.WebClient(); wc.Credentials = networkCredential; stream = wc.OpenWrite(uri.AbsoluteUri, method); Save(stream); } finally { if (stream != null) { stream.Close(); } } }
/// <summary> /// Returns a stream for writing to the source /// </summary> /// <returns></returns> public static Stream OpenWrite(this BlobImportSource source) { if (string.IsNullOrEmpty(source.ConnectionString)) { var client = new WebClient(); var rawStream = client.OpenWrite(source.BlobUri); return source.IsGZiped ? new GZipStream(rawStream, CompressionMode.Compress) : rawStream; } else { CloudStorageAccount storageAccount; if (!CloudStorageAccount.TryParse(source.ConnectionString, out storageAccount)) { throw new Exception("Invalid blob storage connection string"); } var blobClient = storageAccount.CreateCloudBlobClient(); var blob = blobClient.GetBlobReference(source.BlobUri); var rawStream = (Stream)blob.OpenWrite(); return source.IsGZiped ? new GZipStream(rawStream, CompressionMode.Compress) : rawStream; } }
private void ButtonSave_Click(object sender, System.EventArgs e) { string SaveAddress = saveTargetToAddress.Text; if (SaveAddress != "") { //create an instance of the WebClient. System.Net.WebClient MyClient = new System.Net.WebClient(); //create a stream object to hold the stream in the OpenWrite method. System.IO.Stream MyStream = MyClient.OpenWrite(SaveAddress, "PUT"); //create a streamwriter to write the stream to the specified location. System.IO.StreamWriter MyStreamWriter = new System.IO.StreamWriter(MyStream); //grab the stream and write the output. MyStreamWriter.Write(textOutput.Text); //close the writer. MyStreamWriter.Close(); MessageBox.Show("File has been created!"); } }
static void Main(string[] args) { //создание объекта web-клиент WebClient client= new WebClient(); string TextToUpload = "User=Vasia&passwd=okna", urlString = "http://localhost/"; // Преобразуем текст в массив байтов byte[] uploadData=Encoding.ASCII.GetBytes(TextToUpload); // связываем URL с потоком записи Stream upload=client.OpenWrite(urlString,"POST"); // загружаем данные на сервер upload.Write(uploadData,0,uploadData.Length); upload.Close(); WebClient clientUp= new WebClient(); //WebClient client= new WebClient(); clientUp.Credentials = System.Net.CredentialCache.DefaultCredentials; // добавляем HTTP-заголовок clientUp.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); // Преобразуем текст в массив байтов // копируем данные методом GET byte[] respText=client.UploadData(urlString,"GET",uploadData); // загружаем данные на сервер upload.Write(uploadData,0,uploadData.Length); upload.Close(); }
[Test] // OpenWrite (Uri, string) public void OpenWrite4_Address_SchemeNotSupported () { WebClient wc = new WebClient (); try { wc.OpenWrite (new Uri ("tp://scheme.notsupported"), "POST"); Assert.Fail ("#1"); } catch (WebException ex) { // An error occurred performing a WebClient request Assert.AreEqual (typeof (WebException), ex.GetType (), "#2"); Assert.IsNotNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNull (ex.Response, "#5"); Assert.AreEqual (WebExceptionStatus.UnknownError, ex.Status, "#6"); // The URI prefix is not recognized Exception inner = ex.InnerException; Assert.AreEqual (typeof (NotSupportedException), inner.GetType (), "#7"); Assert.IsNull (inner.InnerException, "#8"); Assert.IsNotNull (inner.Message, "#9"); } }
[Test] // OpenWrite (Uri, string) public void OpenWrite4_Address_Null () { WebClient wc = new WebClient (); try { wc.OpenWrite ((Uri) null, "POST"); Assert.Fail ("#1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("address", ex.ParamName, "#6"); } }
private void Form1_Load(object sender, EventArgs e) { Text += " " + GetLocalIPv4(NetworkInterfaceType.Ethernet); Task.Factory.StartNew(() => { UdpClient client = new UdpClient(); IPEndPoint localEp = new IPEndPoint(IPAddress.Any, Constants.MulticastPort); client.Client.Bind(localEp); IPAddress multicastaddress = IPAddress.Parse(Constants.MulticastAddress); client.JoinMulticastGroup(multicastaddress); Stopwatch sw = Stopwatch.StartNew(); int receivedCount = 0; List<long> elapsedMicrosecs = new List<long>(); int lastIntData = -1; int outOfOrderCount = 0; while (receivedCount < Constants.RepeatCount) { Byte[] data = client.Receive(ref localEp); string strData = Encoding.Unicode.GetString(data); int intData = int.Parse(strData); if (lastIntData != (intData - 1)) { outOfOrderCount++; } lastIntData = intData; if (receivedCount == 0) sw.Restart(); elapsedMicrosecs.Add(sw.ElapsedMicroSeconds()); receivedCount++; //Debug.WriteLine(strData); //Debug.WriteLine(strData); //Debug.WriteLine(sw.ElapsedMicroSeconds()); } long[] timesBetween = elapsedMicrosecs.Select((el, idx) => { if (idx == 0) return Constants.IntervalMsec * 1000; return el - elapsedMicrosecs[idx - 1]; }).ToArray(); int intervalMicroSec = Constants.IntervalMsec * 1000; string msg = string.Format(@"Avg:{0} StdDev:{1} Min:{2} Max:{3} %({5}-{6}):{4} OutOfOrder:{7}", timesBetween.Average(), timesBetween.StdDev(), timesBetween.Min(), timesBetween.Max(), timesBetween.Count(tb => tb < (intervalMicroSec+100) && tb > (intervalMicroSec-100)) / (double)Constants.RepeatCount, intervalMicroSec-100, intervalMicroSec+100, outOfOrderCount); textBox1.Invoke(new Action( () => textBox1.Text = msg )); ClientData clientData = new ClientData() { IpAddress = GetLocalIPv4(NetworkInterfaceType.Ethernet), Avg = timesBetween.Average(), StdDev = timesBetween.StdDev(), Min = timesBetween.Min(), Max = timesBetween.Max(), PercWithinDelta = timesBetween.Count(tb => tb < (intervalMicroSec + 100) && tb > (intervalMicroSec - 100)) / (double)Constants.RepeatCount, OutOfOrder = outOfOrderCount }; WebClient wc = new WebClient(); XmlSerializer serializer = new XmlSerializer(typeof(ClientData)); using (StreamWriter streamWriter = new StreamWriter(wc.OpenWrite(Constants.ClientDataUrl))) { serializer.Serialize(streamWriter, clientData); } }); }
public void SendFiles() { char[] ch = new char[1]; ch[0] = '/'; string[] arrstr = this.filestr.Split(ch); WebClient myWebClient = new WebClient(); #region 做一存取凭据 //NetworkCredential myCred = new NetworkCredential("Administrator","11");// //CredentialCache myCache = new CredentialCache(); //myCache.Add(new Uri(this.uri), "Basic", myCred); //myWebClient.Credentials =myCache; #endregion //使用默认的权限 myWebClient.Credentials = CredentialCache.DefaultCredentials; int count = this.listBox1.Items.Count; this.progressBar1.Maximum = 10 * count; for (int i = 0; i < arrstr.Length; i++) { try { string fileNamePath = arrstr[i]; string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1); string uriString = this.uri + "/" + this.serverfolder + "/" + fileName;//指定上传得路径 // 要上传的文件 FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read); //FileStream fs = OpenFile(); BinaryReader r = new BinaryReader(fs); //使用UploadFile方法可以用下面的格式 // myWebClient.UploadFile(uriString,"PUT",fileNamePath); // MessageBox.Show(uriString); byte[] postArray = r.ReadBytes((int)fs.Length); Stream postStream = myWebClient.OpenWrite(uriString, "PUT"); if (postStream.CanWrite) { postStream.Write(postArray, 0, postArray.Length); this.progressBar1.Value = (i + 1) * 10; } else { MessageBox.Show("文件目前不可写!"); } postStream.Close(); } catch (WebException errMsg) { MessageBox.Show("上传失败:" + errMsg.Message); break; } } if (this.progressBar1.Value == this.progressBar1.Maximum) { MessageBox.Show("成功"); } else { MessageBox.Show("传送中出现错误!"); } }
private void upload(object sender, EventArgs e) { string labelname=""; string onlyfile=""; string uristring; string path; string i = textBox1.Text.ToString(); if (textBox1.Text.ToString() == "") { MessageBox.Show("请输入要上传的文件!"); return; } if (textBox2.Visible == false) { labelname = comboBox1.SelectedValue.ToString(); } else if (textBox2.Text.ToString() == "") { MessageBox.Show("新创建的主题名不能为空哦!"); return; } else labelname = textBox2.Text; onlyfile = fileName.Substring(fileName.LastIndexOf("\\") + 1); uristring = "f:\\databaseupdown\\" + labelname + "\\" +onlyfile; string p = uristring.Replace("\\", "/"); path = "f:\\databaseupdown\\" + labelname; WebClient myWebClient = new WebClient(); //设置应用程序的系统凭据 myWebClient.Credentials = CredentialCache.DefaultCredentials; //要上传的文件穿件文件流 if (!Directory.Exists(path)) Directory.CreateDirectory(path); FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite); //以二进制方式读取 BinaryReader br = new BinaryReader(fs); //当前流写入二进制 byte[] postArray = br.ReadBytes((int)fs.Length); Stream postStream = myWebClient.OpenWrite(uristring,"PUT"); try { if (postStream.CanWrite) { postStream.Write(postArray, 0, postArray.Length); postStream.Close(); fs.Dispose(); BLL bll = new BLL(); int id=bll.maxid(true)+1; DateTime dt=DateTime.Now; //暂且先用new用户的身份插入数值 //通过theruserid传值,来用登陆者身份插入数值 bll.insertfile(id, onlyfile, labelname, dt, theuserid2, p); MessageBox.Show("上传成功"); } else { postStream.Close(); fs.Dispose(); MessageBox.Show("上传失败"); } } catch (Exception ex) { postStream.Close(); fs.Dispose(); MessageBox.Show("上传文件异常" + ex.Message); throw ex; } finally { postStream.Close(); fs.Dispose(); } }
/// <summary> /// @author : KhoaHT /// @CreateDate:04/05/2008 /// @Description: Create file stream to read file content and write stram to write content into server /// </summary> /// <param name="fileName">string</param> /// <param name="buffLength">int</param> /// <param name="fsRead">FileStream</param> /// <param name="strmWrite">Stream</param> public override long InitStreamToUpload(string pstrLocalFileName, string pstrServerFileName) { // Server side WebClient client = new WebClient(); client.Credentials = new NetworkCredential(UserID, UserPassword); mServerStream = client.OpenWrite("http://" + ServerAddress + "/" + pstrServerFileName); // Client side FileInfo fileLocalInf = new FileInfo(pstrLocalFileName); mLocalFileStream = fileLocalInf.OpenRead(); mBuffer = new byte[BufferLength]; // return length of file to download return fileLocalInf.Length; }
//��������ļ� private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { WebClient myWebClient = new WebClient(); myWebClient.Credentials = CredentialCache.DefaultCredentials; String filename = openFileDialog1.FileName; FileStream fs = new FileStream(filename, FileMode.Open); byte[] fsbyte = new byte[fs.Length]; fs.Read(fsbyte, 0, Convert.ToInt32(fs.Length)); string fullname = @"c:\1\" + openFileDialog1.SafeFileName; Stream writeStream = myWebClient.OpenWrite(fullname, "PUT"); if (writeStream.CanWrite) { writeStream.Write(fsbyte, 0, Convert.ToInt32(fs.Length)); } else { MessageBox.Show("�Բ����ļ��ϴ�ʧ��"); } fs.Close(); ChatRequestInfo myChatRequest = new ChatRequestInfo(); ChatMessageInfo msg = new ChatMessageInfo(); msg.MessageId = -1; msg.ChatId = myChatRequest.ChatId; msg.Message = "�����Կ�ʼ�����ļ�"; msg.Name = "UploadOK"; msg.SentDate = DateTime.Now.ToUniversalTime().Ticks; msg.Type = 3;//* ws.AddMessage(msg); } }
public static void ImportData(string instanceUrl, string file) { var sw = Stopwatch.StartNew(); using (FileStream fileStream = File.OpenRead(file)) { // Try to read the stream compressed, otherwise continue uncompressed. JsonTextReader jsonReader; try { StreamReader streamReader = new StreamReader(new GZipStream(fileStream, CompressionMode.Decompress)); jsonReader = new JsonTextReader(streamReader); if (jsonReader.Read() == false) return; } catch(InvalidDataException) { fileStream.Seek(0, SeekOrigin.Begin); StreamReader streamReader = new StreamReader(fileStream); jsonReader = new JsonTextReader(streamReader); if (jsonReader.Read() == false) return; } if (jsonReader.TokenType != JsonToken.StartObject) throw new InvalidDataException("StartObject was expected"); // should read indexes now if (jsonReader.Read() == false) return; if (jsonReader.TokenType != JsonToken.PropertyName) throw new InvalidDataException("PropertyName was expected"); if (Equals("Indexes", jsonReader.Value) == false) throw new InvalidDataException("Indexes property was expected"); if (jsonReader.Read() == false) return; if (jsonReader.TokenType != JsonToken.StartArray) throw new InvalidDataException("StartArray was expected"); using (var webClient = new WebClient()) { webClient.UseDefaultCredentials = true; webClient.Headers.Add("Content-Type", "application/json; charset=utf-8"); webClient.Credentials = CredentialCache.DefaultNetworkCredentials; while (jsonReader.Read() && jsonReader.TokenType != JsonToken.EndArray) { var index = JToken.ReadFrom(jsonReader); var indexName = index.Value<string>("name"); if(indexName.StartsWith("Raven/")) continue; using (var streamWriter = new StreamWriter(webClient.OpenWrite(instanceUrl + "indexes/" + indexName, "PUT"))) using (var jsonTextWriter = new JsonTextWriter(streamWriter)) { index.Value<JObject>("definition").WriteTo(jsonTextWriter); jsonTextWriter.Flush(); streamWriter.Flush(); } } } // should read documents now if (jsonReader.Read() == false) return; if (jsonReader.TokenType != JsonToken.PropertyName) throw new InvalidDataException("PropertyName was expected"); if (Equals("Docs", jsonReader.Value) == false) throw new InvalidDataException("Docs property was expected"); if (jsonReader.Read() == false) return; if (jsonReader.TokenType != JsonToken.StartArray) throw new InvalidDataException("StartArray was expected"); var batch = new List<JObject>(); int totalCount = 0; while (jsonReader.Read() && jsonReader.TokenType != JsonToken.EndArray) { totalCount += 1; var document = JToken.ReadFrom(jsonReader); batch.Add((JObject)document); if (batch.Count >= 128) FlushBatch(instanceUrl, batch); } FlushBatch(instanceUrl, batch); Console.WriteLine("Imported {0:#,#} documents in {1:#,#} ms", totalCount, sw.ElapsedMilliseconds); } }
public void TestOpenWriteWithInvalidMethod() { using (var server = InitializeFetchServer()) { using (var client = new System.Net.WebClient()) { try { client.OpenWrite(new Uri(string.Format("imap://{0}/", server.HostPort)), ImapWebRequestMethods.Lsub); Assert.Fail("WebException not thrown"); } catch (WebException ex) { Assert.IsInstanceOfType(typeof(NotSupportedException), ex.InnerException); } try { client.OpenWrite(new Uri(string.Format("imap://{0}/INBOX", server.HostPort)), ImapWebRequestMethods.Subscribe); Assert.Fail("WebException not thrown"); } catch (WebException ex) { Assert.IsInstanceOfType(typeof(ProtocolViolationException), ex.InnerException); } try { client.OpenWrite(new Uri(string.Format("imap://{0}/INBOX/;UID=1", server.HostPort)), ImapWebRequestMethods.Fetch); Assert.Fail("WebException not thrown"); } catch (WebException ex) { Assert.IsInstanceOfType(typeof(NotSupportedException), ex.InnerException); } try { client.OpenWrite(new Uri(string.Format("imap://{0}/INBOX?UID 1", server.HostPort)), ImapWebRequestMethods.Search); Assert.Fail("WebException not thrown"); } catch (WebException ex) { Assert.IsInstanceOfType(typeof(NotSupportedException), ex.InnerException); } } } }
public static void ImportData(string instanceUrl, string file) { using (var streamReader = new StreamReader(new GZipStream(File.OpenRead(file), CompressionMode.Decompress))) { var jsonReader = new JsonTextReader(streamReader); if (jsonReader.Read() == false) return; if (jsonReader.TokenType != JsonToken.StartObject) throw new InvalidDataException("StartObject was expected"); // should read indexes now if (jsonReader.Read() == false) return; if (jsonReader.TokenType != JsonToken.PropertyName) throw new InvalidDataException("PropertyName was expected"); if (Equals("Indexes", jsonReader.Value) == false) throw new InvalidDataException("Indexes property was expected"); if (jsonReader.Read() == false) return; if (jsonReader.TokenType != JsonToken.StartArray) throw new InvalidDataException("StartArray was expected"); using (var webClient = new WebClient()) { webClient.UseDefaultCredentials = true; webClient.Credentials = CredentialCache.DefaultNetworkCredentials; while (jsonReader.Read() && jsonReader.TokenType != JsonToken.EndArray) { var index = JToken.ReadFrom(jsonReader); var indexName = index.Value<string>("name"); if(indexName.StartsWith("Raven/")) continue; using (var streamWriter = new StreamWriter(webClient.OpenWrite(instanceUrl + "indexes/" + indexName, "PUT"))) using (var jsonTextWriter = new JsonTextWriter(streamWriter)) { index.Value<JObject>("definition").WriteTo(jsonTextWriter); jsonTextWriter.Flush(); streamWriter.Flush(); } } } // should read documents now if (jsonReader.Read() == false) return; if (jsonReader.TokenType != JsonToken.PropertyName) throw new InvalidDataException("PropertyName was expected"); if (Equals("Docs", jsonReader.Value) == false) throw new InvalidDataException("Docs property was expected"); if (jsonReader.Read() == false) return; if (jsonReader.TokenType != JsonToken.StartArray) throw new InvalidDataException("StartArray was expected"); var batch = new List<JObject>(); while (jsonReader.Read() && jsonReader.TokenType != JsonToken.EndArray) { var document = JToken.ReadFrom(jsonReader); batch.Add((JObject)document); if (batch.Count > 128) FlushBatch(instanceUrl, batch); } FlushBatch(instanceUrl, batch); } }
protected override Stream GetStreamCore(FileAccess access) { using (WebClient client = new WebClient()) { WebRequest request = WebRequest.CreateDefault(this.Uri); WebResponse response = request.GetResponse(); try { this.cacheEncoding = Utility.GetEncodingFromContentType(response.ContentType); } catch (NotSupportedException) { this.cacheEncoding = null; } switch (access) { case FileAccess.Read: return client.OpenRead(this.uri); case FileAccess.Write: return client.OpenWrite(this.uri); case FileAccess.ReadWrite: default: return client.OpenWrite(this.uri); } } }
public static bool SaveGooglePhoto(Syncronizer sync, ContactEntry googleContact, Image image) { if (googleContact.PhotoEditUri == null) throw new Exception("Must reload contact from google."); try { WebClient client = new WebClient(); client.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + sync.AuthToken); client.Headers.Add(HttpRequestHeader.ContentType, "image/*"); Bitmap pic = new Bitmap(image); Stream s = client.OpenWrite(googleContact.PhotoEditUri.AbsoluteUri, "PUT"); byte[] bytes = BitmapToBytes(pic); s.Write(bytes, 0, bytes.Length); s.Flush(); s.Close(); s.Dispose(); client.Dispose(); pic.Dispose(); } catch { return false; } return true; }
/// <summary> /// web文件上传 /// </summary> /// <param name="webURI">文件上传后的网址</param> /// <param name="localFile">本地上传文件的路径</param> /// <param name="UserName">网络用户名</param> /// <param name="password">密码</param> /// <param name="domain">域名</param> /// <param name="isMD5file">文件名是否要根据MD5算法获取</param> public void UploadFile(string webURI, string localFile, string UserName, string password, string domain, bool isMD5file) { try { // Local Directory File Info if (!System.IO.File.Exists(localFile))//如果文件不存在 { this.TFileInfo.Message ="要上传的文件不存在,请确定文件路径是否正确。"; if (this.fileTransmitError != null) this.fileTransmitError(this, new fileTransmitEvnetArgs(TFileInfo)); return; } System.IO.FileInfo fInfo = new FileInfo(localFile);//获取文件的信息 if (isMD5file)//如果需要将文件MD5,则执行MD5 webURI += "\\" + IMLibrary3.Security.Hasher.GetMD5Hash(localFile) + fInfo.Extension;//获取文件的MD5值 else webURI += "\\" + fInfo.Name;// +fInfo.Extension;//获取文件的MD5值 // Create a new WebClient instance. WebClient myWebClient = new WebClient(); this.netCre = new NetworkCredential(UserName, password, domain); myWebClient.Credentials = this.netCre; if (getDownloadFileLen(webURI) == fInfo.Length)//如果服务器上已经有此文件存在则退出 { if (this.fileTransmitted != null) this.fileTransmitted(this, new fileTransmitEvnetArgs(TFileInfo)); return; } else { Stream postStream = myWebClient.OpenWrite(webURI, "PUT"); if (postStream.CanWrite) { byte[] FileBlock; int readFileCount = 0;//读文件次数 int maxReadWriteFileBlock = 1024 * 30;//一次读文件30k long offset = 0; readFileCount = (int)fInfo.Length / maxReadWriteFileBlock;//获得文件读写次数 if ((int)fInfo.Length % maxReadWriteFileBlock != 0) readFileCount++;//如果读写文件有余,则读次写次数增1 for (int i = 0; i < readFileCount; i++) { //下面是读一次文件到内存过程 if (i + 1 == readFileCount)//如果是最后一次读写文件,则将所有文件尾数据全部读入到内存 FileBlock = new byte[(int)fInfo.Length - i * maxReadWriteFileBlock]; else FileBlock = new byte[maxReadWriteFileBlock]; ////////////////////////文件操作 FileStream fw = new FileStream(localFile, FileMode.Open, FileAccess.Read, FileShare.Read); offset = i * maxReadWriteFileBlock; fw.Seek(offset, SeekOrigin.Begin);//上次发送的位置 fw.Read(FileBlock, 0, FileBlock.Length); fw.Close(); fw.Dispose(); /////////////////////////// postStream.Write(FileBlock, 0, FileBlock.Length); TFileInfo.fullName = localFile; TFileInfo.Name = fInfo.Name; TFileInfo.Length = fInfo.Length; TFileInfo .CurrLength =offset + FileBlock.Length; TFileInfo.MD5 =FileMD5Value; if (this.fileTransmitting != null) this.fileTransmitting(this, new fileTransmitEvnetArgs(TFileInfo)); } } postStream.Close(); myWebClient.Dispose(); } if (this.fileTransmitted != null) this.fileTransmitted(this, new fileTransmitEvnetArgs(TFileInfo)); } catch (Exception ex) { TFileInfo .Message =ex.Message + ex.Source; if (this.fileTransmitError != null) this.fileTransmitError(this, new fileTransmitEvnetArgs(TFileInfo)); } }
public static void ImportData(string instanceUrl, string file) { var sw = Stopwatch.StartNew(); using (FileStream fileStream = File.OpenRead(file)) { // Try to read the stream compressed, otherwise continue uncompressed. JsonTextReader jsonReader; try { StreamReader streamReader = new StreamReader(new GZipStream(fileStream, CompressionMode.Decompress)); jsonReader = new JsonTextReader(streamReader); if (jsonReader.Read() == false) return; } catch (InvalidDataException) { fileStream.Seek(0, SeekOrigin.Begin); StreamReader streamReader = new StreamReader(fileStream); jsonReader = new JsonTextReader(streamReader); if (jsonReader.Read() == false) return; } if (jsonReader.TokenType != JsonToken.StartObject) throw new InvalidDataException("StartObject was expected"); // should read indexes now if (jsonReader.Read() == false) return; if (jsonReader.TokenType != JsonToken.PropertyName) throw new InvalidDataException("PropertyName was expected"); if (Equals("Indexes", jsonReader.Value) == false) throw new InvalidDataException("Indexes property was expected"); if (jsonReader.Read() == false) return; if (jsonReader.TokenType != JsonToken.StartArray) throw new InvalidDataException("StartArray was expected"); using (var webClient = new WebClient()) { webClient.UseDefaultCredentials = true; webClient.Headers.Add("Content-Type", "application/json; charset=utf-8"); webClient.Credentials = CredentialCache.DefaultNetworkCredentials; while (jsonReader.Read() && jsonReader.TokenType != JsonToken.EndArray) { var index = RavenJToken.ReadFrom(jsonReader); var indexName = index.Value<string>("name"); if (indexName.StartsWith("Raven/") || indexName.StartsWith("Temp/")) continue; using (var streamWriter = new StreamWriter(webClient.OpenWrite(instanceUrl + "indexes/" + indexName, "PUT"))) using (var jsonTextWriter = new JsonTextWriter(streamWriter)) { index.Value<RavenJObject>("definition").WriteTo(jsonTextWriter); jsonTextWriter.Flush(); streamWriter.Flush(); } } } // should read documents now if (jsonReader.Read() == false) return; if (jsonReader.TokenType != JsonToken.PropertyName) throw new InvalidDataException("PropertyName was expected"); if (Equals("Docs", jsonReader.Value) == false) throw new InvalidDataException("Docs property was expected"); if (jsonReader.Read() == false) return; if (jsonReader.TokenType != JsonToken.StartArray) throw new InvalidDataException("StartArray was expected"); var batch = new List<RavenJObject>(); int totalCount = 0; while (jsonReader.Read() && jsonReader.TokenType != JsonToken.EndArray) { totalCount += 1; var document = RavenJToken.ReadFrom(jsonReader); batch.Add((RavenJObject)document); if (batch.Count >= 128) FlushBatch(instanceUrl, batch); } FlushBatch(instanceUrl, batch); var attachmentCount = 0; if (jsonReader.Read() == false || jsonReader.TokenType == JsonToken.EndObject) return; if (jsonReader.TokenType != JsonToken.PropertyName) throw new InvalidDataException("PropertyName was expected"); if (Equals("Attachments", jsonReader.Value) == false) throw new InvalidDataException("Attachment property was expected"); if (jsonReader.Read() == false) return; if (jsonReader.TokenType != JsonToken.StartArray) throw new InvalidDataException("StartArray was expected"); while (jsonReader.Read() && jsonReader.TokenType != JsonToken.EndArray) { using (var client = new WebClient()) { attachmentCount += 1; var item = RavenJToken.ReadFrom(jsonReader); var attachmentExportInfo = new JsonSerializer { Converters = {new TrivialJsonToJsonJsonConverter()} }.Deserialize<AttachmentExportInfo>(new RavenJTokenReader(item)); Console.WriteLine("Importing attachment {0}", attachmentExportInfo.Key); if (attachmentExportInfo.Metadata != null) { foreach (var header in attachmentExportInfo.Metadata) { client.Headers.Add(header.Key, StripQuotesIfNeeded(header.Value)); } } using (var writer = client.OpenWrite(instanceUrl + "static/" + attachmentExportInfo.Key, "PUT")) { writer.Write(attachmentExportInfo.Data, 0, attachmentExportInfo.Data.Length); writer.Flush(); } } } Console.WriteLine("Imported {0:#,#} documents and {1:#,#} attachments in {2:#,#} ms", totalCount, attachmentCount, sw.ElapsedMilliseconds); } }
private static void FlushBatch(string instanceUrl, List<JObject> batch) { using (var webClient = new WebClient()) { webClient.UseDefaultCredentials = true; webClient.Credentials = CredentialCache.DefaultNetworkCredentials; using (var stream = webClient.OpenWrite(instanceUrl + "bulk_docs", "POST")) using (var streamWriter = new StreamWriter(stream)) using (var jsonTextWriter = new JsonTextWriter(streamWriter)) { var commands = new JArray(); foreach (var doc in batch) { var metadata = doc.Value<JObject>("@metadata"); doc.Remove("@metadata"); commands.Add(new JObject( new JProperty("Method", "PUT"), new JProperty("Document", doc), new JProperty("Metadata", metadata), new JProperty("Key", metadata.Value<string>("@id")) )); } commands.WriteTo(jsonTextWriter); jsonTextWriter.Flush(); streamWriter.Flush(); } } batch.Clear(); }
private static void FlushBatch(string instanceUrl, List<RavenJObject> batch) { var sw = Stopwatch.StartNew(); long size; using (var webClient = new WebClient()) { webClient.Headers.Add("Content-Type", "application/json; charset=utf-8"); webClient.UseDefaultCredentials = true; webClient.Credentials = CredentialCache.DefaultNetworkCredentials; using (var stream = new MemoryStream()) { using (var streamWriter = new StreamWriter(stream, Encoding.UTF8)) using (var jsonTextWriter = new JsonTextWriter(streamWriter)) { var commands = new RavenJArray(); foreach (var doc in batch) { var metadata = doc.Value<RavenJObject>("@metadata"); doc.Remove("@metadata"); commands.Add(new RavenJObject { {"Method", "PUT"}, {"Document", doc}, {"Metadata", metadata}, {"Key", metadata.Value<string>("@id")} }); } commands.WriteTo(jsonTextWriter); jsonTextWriter.Flush(); streamWriter.Flush(); stream.Flush(); size = stream.Length; using (var netStream = webClient.OpenWrite(instanceUrl + "bulk_docs", "POST")) { stream.WriteTo(netStream); netStream.Flush(); } } } } Console.WriteLine("Wrote {0} documents [{1:#,#} kb] in {2:#,#} ms", batch.Count, Math.Round((double)size / 1024, 2), sw.ElapsedMilliseconds); batch.Clear(); }
/// <summary> /// web�ļ��ϴ� /// </summary> /// <param name="WebURI">�ļ��ϴ������ַ</param> /// <param name="LocalFile">�����ϴ��ļ���·��</param> /// <param name="userName">�����û���</param> /// <param name="password">����</param> /// <param name="domain">����</param> /// <param name="isMD5file">�ļ����Ƿ�Ҫ����MD5�㷨��ȡ</param> public void UploadFile(string webURI, string localFile, string userName, string password, string domain, bool isMD5file) { try { // Local Directory File Info if (!System.IO.File.Exists(localFile))//����ļ������� { if (this.fileTransmitError != null) this.fileTransmitError(this, new fileTransmitEvnetArgs(true, localFile, localFile, "Ҫ�ϴ����ļ������ڣ���ȷ���ļ�·���Ƿ���ȷ��", 0, 0, this.FileMD5Value)); return; } System.IO.FileInfo fInfo = new FileInfo(localFile);//��ȡ�ļ�����Ϣ if (isMD5file)//�����Ҫ���ļ�MD5,��ִ��MD5 webURI += "\\" + CSS.IM.Library.Class.Hasher.GetMD5Hash(localFile) + fInfo.Extension;//��ȡ�ļ���MD5ֵ else webURI += "\\" + fInfo.Name;// +fInfo.Extension;//��ȡ�ļ���MD5ֵ // Create a new WebClient instance. WebClient myWebClient = new WebClient(); this.netCre = new NetworkCredential(userName, password, domain); myWebClient.Credentials = this.netCre; if (getDownloadFileLen(webURI) == fInfo.Length)//������������Ѿ��д��ļ��������˳� { if (this.fileTransmitted != null) this.fileTransmitted(this, new fileTransmitEvnetArgs(true, localFile, fInfo.Name, "", Convert.ToInt32(fInfo.Length), Convert.ToInt32(fInfo.Length), this.FileMD5Value)); return; } else { Stream postStream = myWebClient.OpenWrite(webURI, "PUT"); if (postStream.CanWrite) { byte[] FileBlock; int readFileCount = 0;//���ļ����� int maxReadWriteFileBlock = 1024 * 5;//һ�ζ��ļ�5k long offset = 0; readFileCount = (int)fInfo.Length / maxReadWriteFileBlock;//����ļ���д���� if ((int)fInfo.Length % maxReadWriteFileBlock != 0) readFileCount++;//�����д�ļ����࣬�����д������1 for (int i = 0; i < readFileCount; i++) { //�����Ƕ�һ���ļ����ڴ���� if (i + 1 == readFileCount)//��������һ�ζ�д�ļ����������ļ�β����ȫ�����뵽�ڴ� FileBlock = new byte[(int)fInfo.Length - i * maxReadWriteFileBlock]; else FileBlock = new byte[maxReadWriteFileBlock]; ////////////////////////�ļ����� FileStream fw = new FileStream(localFile, FileMode.Open, FileAccess.Read, FileShare.Read); offset = i * maxReadWriteFileBlock; fw.Seek(offset, SeekOrigin.Begin);//�ϴη��͵�λ�� fw.Read(FileBlock, 0, FileBlock.Length); fw.Close(); fw.Dispose(); /////////////////////////// postStream.Write(FileBlock, 0, FileBlock.Length); if (this.fileTransmitting != null) this.fileTransmitting(this, new fileTransmitEvnetArgs(true, localFile, fInfo.Name, "", Convert.ToInt32(fInfo.Length), (int)offset + FileBlock.Length, this.FileMD5Value)); } } postStream.Close(); myWebClient.Dispose(); } if (this.fileTransmitted != null) this.fileTransmitted(this, new fileTransmitEvnetArgs(true, localFile, fInfo.Name, "", Convert.ToInt32(fInfo.Length), Convert.ToInt32(fInfo.Length), this.FileMD5Value)); } catch (Exception ex) { if (this.fileTransmitError != null) this.fileTransmitError(this, new fileTransmitEvnetArgs(true, localFile, localFile, ex.Message + ex.Source, 0, 0, this.FileMD5Value)); } }
public override bytes::IOutputStream GetOutputStream( ) { if(PdfName.URL.Equals(BaseDictionary[PdfName.FS])) // Remote resource [PDF:1.7:3.10.4]. { Uri fileUrl; try {fileUrl = new Uri(Path);} catch(Exception e) {throw new Exception("Failed to instantiate URL for " + Path, e);} WebClient webClient = new WebClient(); try {return new bytes::Stream(webClient.OpenWrite(fileUrl));} catch(Exception e) {throw new Exception("Failed to open output stream for " + Path, e);} } else // Local resource [PDF:1.7:3.10.1]. return base.GetOutputStream(); }
//public MyFile WriteVideoFile(string FileName, Stream FileContent, string Parentid, string UserToken) //{ // Video createdVideo; // try // { // Video newVideo = new Video(); // newVideo.Title = FileName; // newVideo.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema)); // newVideo.Keywords = FileName; // newVideo.Description = "My description"; // newVideo.YouTubeEntry.Private = false; // newVideo.Tags.Add(new MediaCategory("mydevtag, anotherdevtag", // YouTubeNameTable.DeveloperTagSchema)); // newVideo.YouTubeEntry.Location = new GeoRssWhere(37, -122); // // alternatively, you could just specify a descriptive string // // newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA"); // newVideo.YouTubeEntry.MediaSource = new MediaFileSource(FileContent, "test file", // "video/quicktime"); // createdVideo = CreateRequest().Upload(newVideo); // } // catch (Exception ex) // { // return null; // } // ResourceToken objToken = objClient.CreateVideoFile("File", FileName,"", createdVideo.VideoId, UserToken); // objClient.SetWriteSuccess(objToken.ContentId, UserToken); // FileInfo objInfo = new FileInfo(FileName); // Dictionary<string, string> DicProperties = new Dictionary<string, string>(); // DicProperties.Add("Name", objInfo.Name); // MyFile file = objClient.AddFile(objToken.ContentId, FileName, Parentid, Enums.contenttype.video.ToString(),JsonConvert.SerializeObject(DicProperties), UserToken); // return file; //} //Here Response Means Pass the "Page.Response"\ //chk //public void ReadFile(string RelationId, string UserToken, HttpResponse Response) //{ // ResourceToken RToken = objClient.GetReadFile(RelationId, UserToken); // DownloadFile(RToken.Url, RToken.Filename, Response); //} private bool UploadFile(Stream fileStream, string Url,string contentType) { try { //Create weClient WebClient c = new WebClient(); //add header c.Headers.Add("Content-Type",contentType); //Create Streams Stream outs = c.OpenWrite(Url, "PUT"); Stream ins = fileStream; CopyStream(ins, outs); ins.Close(); outs.Flush(); outs.Close(); return true; } catch (Exception ex) { return false; } }
/// <summary> /// Publish the opml document to the specified location. /// </summary> /// <param name="uri">The URI of the resource to receive the data. </param> /// <param name="method">The method used to send the data to the resource. (POST)</param> /// <param name="proxy">HTTP proxy settings for the WebRequest class.</param> /// <param name="networkCredential">Credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication.</param> /// <example> /// This sample shows how to publish (Default Proxy) /// <code> /// // password-based authentication for web resource /// System.Net.NetworkCredential providerCredential = new System.Net.NetworkCredential("username", "password", "domain"); /// // use default system proxy /// Uri uri = new Uri("http://domain.net"); /// Publish(uri, null, "POST", providerCredential); /// </code> /// This sample shows how to publish (Custom Proxy) /// <code> /// // password-based authentication for web resource /// System.Net.NetworkCredential providerCredential = new System.Net.NetworkCredential("username", "password", "domain"); /// // password-based authentication for web proxy /// System.Net.NetworkCredential proxyCredential = new System.Net.NetworkCredential("username", "password", "domain"); /// // create custom proxy /// System.Net.WebProxy webProxy = new System.Net.WebProxy("http://proxyurl:8080",false); /// webProxy.Credentials = proxyCredential; /// // publish /// Publish(uri, webProxy, "POST", providerCredential); /// </code> /// </example> public virtual void Publish(Uri uri, System.Net.WebProxy proxy, string method, System.Net.NetworkCredential networkCredential) { System.IO.Stream stream = null; try { // TODO: webproxy support System.Net.WebClient wc = new System.Net.WebClient(); wc.Credentials = networkCredential; stream = wc.OpenWrite(uri.AbsoluteUri, method); Save(stream); } finally { if (stream != null) stream.Close(); } }
public void ProcessRequest(HttpContext context) { //context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); string gesType = context.Request["type"].ToString(); string gesDirection = context.Request["direction"] == null ? "" : context.Request["direction"].ToString(); double offsetX = 0; Double.TryParse(context.Request["offset_x"].ToString(), out offsetX); double offsetY = 0; Double.TryParse(context.Request["offset_y"].ToString(), out offsetY); PPt.Application pptApplication = null; PPt.Presentation presentation = null; PPt.Slides slides = null; PPt.Slide slide = null; int slidescount = 0; int slideIndex = 0; if (gesType == "swipe") { try { // Get Running PowerPoint Application object pptApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("PowerPoint.Application") as PPt.Application; } catch { } if (pptApplication != null) { // Get Presentation Object presentation = pptApplication.ActivePresentation; // Get Slide collection object slides = presentation.Slides; // Get Slide count slidescount = slides.Count; // Get current selected slide try { // Get selected slide object in normal view slide = slides[pptApplication.ActiveWindow.Selection.SlideRange.SlideNumber]; } catch { // Get selected slide object in reading view slide = pptApplication.SlideShowWindows[1].View.Slide; } } if (gesDirection == "left") { slideIndex = slide.SlideIndex - 1; if (slideIndex >= 1) { try { slide = slides[slideIndex]; slides[slideIndex].Select(); } catch { pptApplication.SlideShowWindows[1].View.Previous(); slide = pptApplication.SlideShowWindows[1].View.Slide; } } } else if (gesDirection == "right") { slideIndex = slide.SlideIndex + 1; if (slideIndex > slidescount) { } else { try { slide = slides[slideIndex]; slides[slideIndex].Select(); } catch { pptApplication.SlideShowWindows[1].View.Next(); slide = pptApplication.SlideShowWindows[1].View.Slide; } } } else if (gesDirection == "up") { try { // Call Select method to select first slide in normal view slides[1].Select(); slide = slides[1]; } catch { // Transform to first page in reading view pptApplication.SlideShowWindows[1].View.First(); slide = pptApplication.SlideShowWindows[1].View.Slide; } } else if (gesDirection == "down") { try { slides[slidescount].Select(); slide = slides[slidescount]; } catch { pptApplication.SlideShowWindows[1].View.Last(); slide = pptApplication.SlideShowWindows[1].View.Slide; } } } else if (gesType == "tap") { mouse_event(MOUSEEVENTF_LEFTDOWN, Control.MousePosition.X, Control.MousePosition.Y, 0, 0); mouse_event(MOUSEEVENTF_LEFTUP, Control.MousePosition.X, Control.MousePosition.Y, 0, 0); } else if (gesType == "drag") { mouse_event(MOUSEEVENTF_MOVE, (int)offsetX, (int)offsetY, 0, 0); } else if (gesType == "scroll") { mouse_event(MOUSEEVENTF_WHEEL, 0, 0, (int)offsetY, 0); } else if (gesType == "Hscroll") { mouse_event(MOUSEEVENTF_HWHEEL, 0, 0, (int)offsetX, 0); } else if (gesType == "pinchin") { keybd_event(0xa2, MapVirtualKey(0xa2, 0), 0, 0); mouse_event((int)MouseEventFlag.WHEEL, 0, 0, -50, 0); keybd_event(0xa2, MapVirtualKey(0xa2, 0), 0x2, 0); } else if (gesType == "pinchout") { keybd_event(0xa2, MapVirtualKey(0xa2, 0), 0, 0); mouse_event((int)MouseEventFlag.WHEEL, 0, 0, 50, 0); keybd_event(0xa2, MapVirtualKey(0xa2, 0), 0x2, 0); } else if (gesType == "laseron") { keybd_event(0xa2, MapVirtualKey(0xa2, 0), 0, 0); mouse_event((int)MouseEventFlag.LEFTDOWN, 0, 0, 0, 0); } else if (gesType == "laseroff") { mouse_event((int)MouseEventFlag.LEFTUP, 0, 0, 0, 0); keybd_event(0xa2, MapVirtualKey(0xa2, 0), 0x2, 0); } else if (gesType == "win") { keybd_event(0x5b, 0, 0, 0); keybd_event(0x5b, 0, 0x2, 0); } else if (gesType == "run") { try { pptApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("PowerPoint.Application") as PPt.Application; } catch { } if (pptApplication != null && pptApplication.ActivePresentation != null) { presentation = pptApplication.ActivePresentation; if (presentation != null) presentation.SlideShowSettings.Run(); } } else if (gesType == "stop") { try { pptApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("PowerPoint.Application") as PPt.Application; } catch { } if (pptApplication != null) { presentation = pptApplication.ActivePresentation; if (presentation != null) try { presentation.SlideShowWindow.View.Exit(); } catch { } } } else if (gesType == "upload") { var imgData = context.Request["file"] == null ? "" : context.Request["file"].ToString(); byte[] imgBytes = Convert.FromBase64String(imgData.Substring( imgData.IndexOf( ',' ) + 1 )); using (var imageStream = new MemoryStream(imgBytes, false)) { WebClient myWebClient = new WebClient(); myWebClient.Credentials = CredentialCache.DefaultCredentials; try { // Get Running PowerPoint Application object pptApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("PowerPoint.Application") as PPt.Application; } catch { } if (pptApplication != null) { presentation = pptApplication.ActivePresentation; slides = presentation.Slides; slidescount = slides.Count; try { slide = slides[pptApplication.ActiveWindow.Selection.SlideRange.SlideNumber]; } catch { slide = pptApplication.SlideShowWindows[1].View.Slide; } Stream postStream = myWebClient.OpenWrite("c:\\upload\\uploaded.jpg", "PUT"); if (postStream.CanWrite) { postStream.Write(imgBytes, 0, imgBytes.Length); } postStream.Close(); slide.Shapes.AddPicture("c:\\upload\\uploaded.jpg", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 440, 100, 480, 360); } } } }