Showing posts with label .NET35. Show all posts
Showing posts with label .NET35. Show all posts

Friday, September 25, 2015

Using the ProcessRunner class

 


 

Getting from here as notepad http://csharptest.net/319/using-the-processrunner-class/

Let’s face it, using the System.Diagnostics.Process to run a process and capture the output is not as easy as it should be. People often get it wrong without realizing it. Adding to the complexities can be reading both the standard output as well as the standard error stream. To put this to bed once and for all here is the ‘right’ way all wrapped up in a helper class ProcessRunner.
Usage Example:
using CSharpTest.Net.Processes;
partial class Program
{
static int Main(string[] args)
{
 
string path = "C:\\MyProject";
ProcessRunner run = new ProcessRunner("svn.exe", "update", "{0}");
run.OutputReceived += new ProcessOutputEventHandler(run_OutputReceived);
return run.RunFormatArgs(path);
}
 
static void run_OutputReceived(object sender, ProcessOutputEventArgs args)
{
Console.WriteLine("{0}: {1}", args.Error ? "Error" : "Output", args.Data);
}
}
 

Using Process.Start to capture console output


 
Copy paste from as note, allcredit belong there http://csharptest.net/532/using-processstart-to-capture-console-output/



Background: I get a lot of traffic looking for details on running a process and collecting the process output. If you haven’t already done so, you should read “How to use System.Diagnostics.Process correctly“. It outlines the major pitfalls of using this class. Another post on “Using the ProcessRunner class” will demonstrate using the helper class I wrote: CSharpTest.Net.Processes.ProcessRunner.
So again I find myself writing about using System.Diagnostics.Process and the Process.Start method. This time it’s not to provide any more information, but rather a simplified example. This example will build upon the previous two posts “How to search the environment’s path for an exe or dll“, and “How to correctly escape command line arguments” to use those methods for solving those needs. Otherwise this example is a relatively stand-alone method for running a process and capturing it’s output.
/// 
/// Runs the specified executable with the provided arguments and returns the process' exit code.
/// 
/// Recieves the output of either std/err or std/out
/// Provides the line-by-line input that will be written to std/in, null for empty
/// The executable to run, may be unqualified or contain environment variables
/// The list of unescaped arguments to provide to the executable
/// Returns process' exit code after the program exits
/// Raised when the exe was not found
/// Raised when one of the arguments is null
/// Raised if an argument contains '\0', '\r', or '\n'
public static int Run(Action output, TextReader input, string exe, params string[] args)
{
if (String.IsNullOrEmpty(exe))
throw new FileNotFoundException();
if (output == null)
throw new ArgumentNullException("output");
 
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.CreateNoWindow = true;
psi.ErrorDialog = false;
psi.WorkingDirectory = Environment.CurrentDirectory;
psi.FileName = FindExePath(exe); //see http://csharptest.net/?p=526
psi.Arguments = EscapeArguments(args); // see http://csharptest.net/?p=529
 
using (Process process = Process.Start(psi))
using (ManualResetEvent mreOut = new ManualResetEvent(false),
mreErr = new ManualResetEvent(false))
{
process.OutputDataReceived += (o, e) => { if (e.Data == null) mreOut.Set(); else output(e.Data); };
process.BeginOutputReadLine();
process.ErrorDataReceived += (o, e) => { if (e.Data == null) mreErr.Set(); else output(e.Data); };
process.BeginErrorReadLine();
 
string line;
while (input != null && null != (line = input.ReadLine()))
process.StandardInput.WriteLine(line);
 
process.StandardInput.Close();
process.WaitForExit();
 
mreOut.WaitOne();
mreErr.WaitOne();
return process.ExitCode;
}
}
Though most people won’t require writing to std::in, it is demonstrated here. If you do decide to remove this be careful that you still set psi.RedirectStandardInput to true, and call process.StandardInput.Close() before you call process.WaitForExit().
If you want to read a single character at a time (so as not to wait for a new line) that can also be done. Unfortunately it does require more work. The following sample class reads one character at a time and writes it to the console:
//In the above example you would remove the event subscription and the call to
//process.BeginOutputReadLine() and replace it with the following:
new ReadOutput(process.StandardInput, mreOut);
 
private class ReadOutput
{
private StreamReader _reader;
private ManualResetEvent _complete;
 
public ReadOutput(StreamReader reader, ManualResetEvent complete)
{
_reader = reader;
_complete = complete;
Thread t = new Thread(ReadAll);
t.Start();
}
 
void ReadAll()
{
int ch;
while(-1 != (ch = _reader.Read()))
{
Console.Write((char) ch);
}
_complete.Set();
}
}
Always remember you need two threads reading both std::out and std::err or you run into the possibility of hanging the process.

Tuesday, August 25, 2015

Resizing Image With quality or proportional

 

Resizing image with quality. 

Taken from http://stackoverflow.com/a/24199315/1247243 all credit belong to Mark


/// <summary>
/// Resize the image to the specified width and height.
/// </summary>
/// <param name="image">The image to resize.</param>
/// <param name="width">The width to resize to.</param>
/// <param name="height">The height to resize to.</param>
/// <returns>The resized image.</returns>
public static Bitmap ResizeImage(Image image, int width, int height)
{
    var destRect = new Rectangle(0, 0, width, height);
    var destImage = new Bitmap(width, height);

    destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    using (var graphics = Graphics.FromImage(destImage))
    {
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.CompositingQuality = CompositingQuality.HighQuality;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

        using (var wrapMode = new ImageAttributes())
        {
            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
            graphics.DrawImage(image, destRect, 0, 0, image.Width,image.Height, GraphicsUnit.Pixel, wrapMode);
        }
    }

    return destImage;
}
  • wrapMode.SetWrapMode(WrapMode.TileFlipXY) prevents ghosting around the image borders -- naive resizing will sample transparent pixels beyond the image boundaries, but by mirroring the image we can get a better sample (this setting is very noticeable)
  • destImage.SetResolution maintains DPI regardless of physically size -- may increase quality when reducing image dimensions or when printing
  • Compositing controls how pixels are blended with the background -- might not be needed since we're only drawing one thing
  • InterpolationMode determines how intermediate values between two endpoints are calculated
  • SmoothingMode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing) -- probably only works on vectors
  • PixelOffsetMode affects rendering quality when drawing the new image
Maintaining aspect ratio is left as an exercise for the reader (actually, I just don't think it's this function's job to do that for you).
Also, this is a good article describing some of the pitfalls with image resizing. The above function will cover most of them, but you still have to worry about saving.

Or using proportion resizing 


taken from http://stackoverflow.com/a/6501997/1247243 credit belong to Alex

Like this?
public static void Test()
{
    using (var image = Image.FromFile(@"c:\logo.png"))
    using (var newImage = ScaleImage(image, 300, 400))
    {
        newImage.Save(@"c:\test.png", ImageFormat.Png);
    }
}

public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);

    using (var graphics = Graphics.FromImage(newImage))
        graphics.DrawImage(image, 0, 0, newWidth, newHeight);

    return newImage;
}

Saturday, August 8, 2015

OpenFileDialog and SaveFileDialog

 


 

Open file:

            OpenFileDialog opendialog = new OpenFileDialog();
            opendialog.Filter = "Text files|*.txt";
            opendialog.Title = "Import Settings";
            DialogResult result = opendialog.ShowDialog(); // Show the dialog.
            if (result == DialogResult.OK) // Test result.
            {
                //opendialog.FileName;
            }



Save File Dialog
            SaveFileDialog savedialog = new SaveFileDialog();
            savedialog.Filter = "Text files|*.txt";
            savedialog.Title = "Export Settings";
            DialogResult result = savedialog.ShowDialog(); // Show the dialog.
            if (result == DialogResult.OK) // Test result.
            {
               //savedialog.FileName;
            }

Friday, August 7, 2015

Snippet Import and Export setting in C#


Dont forget changing your name space according your own namespace.

Credit http://snipplr.com/view/24482/persisting-data-using-xml-config-files-in-winforms-saving-and-restoring-user-and-application-data/  taken as my own snippet




using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;


namespace TestingGround
{
    public static class SettingsIO
    {
        internal static void Import(string settingsFilePath)
        {
            if (!File.Exists(settingsFilePath))
            {
                throw new FileNotFoundException();
            }

            var appSettings = Properties.Settings.Default;
            try
            {
                var config =
    ConfigurationManager.OpenExeConfiguration(
    ConfigurationUserLevel.PerUserRoamingAndLocal);

                string appSettingsXmlName =
   Properties.Settings.Default.Context["GroupName"].ToString();
                // returns "MyApplication.Properties.Settings";

                // Open settings file as XML
                var import = XDocument.Load(settingsFilePath);
                // Get the whole XML inside the settings node
                var settings = import.XPathSelectElements("//" + appSettingsXmlName);

                config.GetSectionGroup("userSettings")
                    .Sections[appSettingsXmlName]
                    .SectionInformation
                    .SetRawXml(settings.Single().ToString());
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("userSettings");

                appSettings.Reload();
            }
            catch (Exception) // Should make this more specific
            {
                // Could not import settings.
                appSettings.Reload(); // from last set saved, not defaults
            }
        }

        internal static void Export(string settingsFilePath)
        {
            Properties.Settings.Default.Save();
            var config =
    ConfigurationManager.OpenExeConfiguration(
    ConfigurationUserLevel.PerUserRoamingAndLocal);
            config.SaveAs(settingsFilePath);
        }
    }
}

 OOT

Or you can using this one. https://github.com/crdx/PortableSettingsProvider , this will save your setting in YOURAPPNAME.settings but little bit work. :) . This more portable like inifile in delphi or pascal.

Good luck

Friday, July 31, 2015

Browser Khusus Nyepam



DI buat khusus untuk nyepam..
- Jalanin banyak browser ( beda directory beda cookies dan cache )

v1.0
http://www.mediafire.com/download/jse52iek87eb0oe/BrowserSpammer.zip

v1.1
http://www.mediafire.com/download/qdndfg7kg754slj/BrowserSpammer_v1.1.rar
net framework 4.

Blogspot ( Blogger URL parser ) Tools



Example : http://test.blogspot.com/atom.xml?redirect=false&start-index=1&max-results=3

just insert url and parsing url....
 After scraping url you can parsing the data using HTML SCRAPER

 Download below:
 http://www.mediafire.com/download/pz9i1ae9980u5b9/Blogger_urlParser.zip


NET framework 4

Right Click menu in richtextbox in C#



Add this code to your event....
        private void richTextBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                ContextMenu contextMenu = new System.Windows.Forms.ContextMenu();
                MenuItem menuItem = new MenuItem("Cut");
                menuItem.Click += new EventHandler(CutAction);
                contextMenu.MenuItems.Add(menuItem);
                menuItem = new MenuItem("Copy");
                menuItem.Click += new EventHandler(CopyAction);
                contextMenu.MenuItems.Add(menuItem);
                menuItem = new MenuItem("Paste");
                menuItem.Click += new EventHandler(PasteAction);
                contextMenu.MenuItems.Add(menuItem);
                menuItem = new MenuItem("Select All");
                menuItem.Click += new EventHandler(SelectAll);
                contextMenu.MenuItems.Add(menuItem);
                richTextBox1.ContextMenu = contextMenu;
            }
        }

        void CutAction(object sender, EventArgs e)
        {
            richTextBox1.Cut();
        }

        void CopyAction(object sender, EventArgs e)
        {
            Clipboard.SetText(richTextBox1.SelectedText);
        }

        void PasteAction(object sender, EventArgs e)
        {
            if (Clipboard.ContainsText())
            {
                richTextBox1.Text += Clipboard.GetText(TextDataFormat.Text).ToString();
            }
        }

        void SelectAll(object sender, EventArgs e)
        {
           richTextBox1.SelectAll();
           richTextBox1.Focus();
        }

Saturday, June 6, 2015

Killing child process when parent software killed.

You need add using System.Management;

 
 /// 
           /// Kill a process, and all of its children, grandchildren, etc.
           /// 
           /// Process ID.
           private static void KillProcessAndChildren(int pid)
           {
               ManagementObjectSearcher searcher = new ManagementObjectSearcher
                 ("Select * From Win32_Process Where ParentProcessID=" + pid);
               ManagementObjectCollection moc = searcher.Get();
               foreach (ManagementObject mo in moc)
               {
                   KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
               }
               try
               {
                   Process proc = Process.GetProcessById(pid);
                   proc.Kill();
               }
               catch (ArgumentException)
               {
                   // Process already exited.
               }
           } 

Sample using it declare first, so we can access it everywhere

 private int idkita;
Button CLICK
private void button1_Click(object sender, EventArgs e)
           {

               ProcessStartInfo startInfo = new ProcessStartInfo();
               //startInfo.WindowStyle = ProcessWindowStyle.Hidden;
               Process ieProcess = Process.Start(@"notepad.exe", "");
               idkita = ieProcess.Id;
}
Add to form closing FORM CLOSING
  private void Form1_FormClosing(object sender, FormClosingEventArgs e)
           {
               KillProcessAndChildren(idkita);
           }

Thursday, May 7, 2015

Tackling timeout issues when uploading large files with HttpWebRequest

Taking from http://www.thomaslevesque.com/2014/01/14/tackling-timeout-issues-when-uploading-large-files-with-httpwebrequest/  as my personal NOTE . All credit belong to

 
If you ever had to upload large volumes of data over HTTP, you probably ran into timeout issues. The default Timeout value for HttpWebRequest is 100 seconds, which means that if it takes more than that from the time you send the request headers to the time you receive the response headers, your request will fail. Obviously, if you’re uploading a large file, you need to increase that timeout… but to which value?
If you know the available bandwidth, you could calculate a rough estimate of how long it should take to upload the file, but it’s not very reliable, because if there is some network congestion, it will take longer, and your request will fail even though it could have succeeded given enough time. So, should you set the timeout to a very large value, like several hours, or even Timeout.Infinite? Probably not. The most compelling reason is that even though the transfer itself could take hours, some phases of the exchange shouldn’t take that long. Let’s decompose the phases of an HTTP upload:




Obtaining the request stream or getting the response (orange parts) isn’t supposed to take very long, so obviously we need a rather short timeout there (the default value of 100 seconds seems reasonable). But sending the request body (blue part) could take much longer, and there is no reliable way  to decide how long that should be; as long as we keep sending data and the server is receiving it, there is no reason not to continue, even if it’s taking hours. So we actually don’t want a timeout at all there! Unfortunately, the behavior of the Timeout property is to consider everything from the call to GetRequestStream to the return of GetResponse
In my opinion, it’s a design flaw of the HttpWebRequest class, and one that has bothered me for a very long time. So I eventually came up with a solution. It relies on the fact that the asynchronous versions of GetRequestStream and GetResponse don’t have a timeout mechanism. Here’s what the documentation says:
The Timeout property has no effect on asynchronous requests made with the BeginGetResponse or BeginGetRequestStream method.
In the case of asynchronous requests, the client application implements its own time-out mechanism. Refer to the example in the BeginGetResponse method.
So, a solution could be to to use these methods directly (or the new Task-based versions: GetRequestStreamAsync and GetResponseAsync); but more often than not, you already have an existing code base that uses the synchronous methods, and changing the code to make it fully asynchronous is usually not trivial. So, the easy approach is to create synchronous wrappers around BeginGetRequestStream and BeginGetResponse, with a way to specify a timeout for these operations:
    public static class WebRequestExtensions
    {
        public static Stream GetRequestStreamWithTimeout(
            this WebRequest request,
            int? millisecondsTimeout = null)
        {
            return AsyncToSyncWithTimeout(
                request.BeginGetRequestStream,
                request.EndGetRequestStream,
                millisecondsTimeout ?? request.Timeout);
        }

        public static WebResponse GetResponseWithTimeout(
            this HttpWebRequest request,
            int? millisecondsTimeout = null)
        {
            return AsyncToSyncWithTimeout(
                request.BeginGetResponse,
                request.EndGetResponse,
                millisecondsTimeout ?? request.Timeout);
        }

        private static T AsyncToSyncWithTimeout<T>(
            Func<AsyncCallback, object, IAsyncResult> begin,
            Func<IAsyncResult, T> end,
            int millisecondsTimeout)
        {
            var iar = begin(null, null);
            if (!iar.AsyncWaitHandle.WaitOne(millisecondsTimeout))
            {
                var ex = new TimeoutException();
                throw new WebException(ex.Message, ex, WebExceptionStatus.Timeout, null);
            }
            return end(iar);
        }
    }
(note that I used the Begin/End methods rather than the Async methods, in order to keep compatibility with older versions of .NET)
These extension methods can be used instead of GetRequestStream and GetResponse; each of them will timeout if they take too long, but once you have the request stream, you can take as long as you want to upload the data. Note that the stream itself has its own read and write timeout (5 minutes by default), so if 5 minutes go by without any data being uploaded, the Write method will cause an exception. Here is the new upload scenario using these methods:



As you can see, the only difference is that the timeout doesn’t apply anymore to the transfer of the request body, but only to obtaining the request stream and getting the response. Here’s a full example that corresponds to the scenario above:
long UploadFile(string path, string url, string contentType)
{
    // Build request
    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = WebRequestMethods.Http.Post;
    request.AllowWriteStreamBuffering = false;
    request.ContentType = contentType;
    string fileName = Path.GetFileName(path);
    request.Headers["Content-Disposition"] = string.Format("attachment; filename=\"{0}\"", fileName);
    
    try
    {
        // Open source file
        using (var fileStream = File.OpenRead(path))
        {
            // Set content length based on source file length
            request.ContentLength = fileStream.Length;
            
            // Get the request stream with the default timeout
            using (var requestStream = request.GetRequestStreamWithTimeout())
            {
                // Upload the file with no timeout
                fileStream.CopyTo(requestStream);
            }
        }
        
        // Get response with the default timeout, and parse the response body
        using (var response = request.GetResponseWithTimeout())
        using (var responseStream = response.GetResponseStream())
        using (var reader = new StreamReader(responseStream))
        {
            string json = reader.ReadToEnd();
            var j = JObject.Parse(json);
            return j.Value<long>("Id");
        }
    }
    catch (WebException ex)
    {
        if (ex.Status == WebExceptionStatus.Timeout)
        {
            LogError(ex, "Timeout while uploading '{0}'", fileName);
        }
        else
        {
            LogError(ex, "Error while uploading '{0}'", fileName);
        }
        throw;
    }
}
I hope you will find this helpful!

Monday, April 6, 2015

Auto close Messagebox


taken from here as personal note
http://stackoverflow.com/questions/14522540/close-a-messagebox-after-several-seconds


public class AutoClosingMessageBox {
    System.Threading.Timer _timeoutTimer;
    string _caption;
    AutoClosingMessageBox(string text, string caption, int timeout) {
        _caption = caption;
        _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
            null, timeout, System.Threading.Timeout.Infinite);
        MessageBox.Show(text, caption);
    }
    public static void Show(string text, string caption, int timeout) {
        new AutoClosingMessageBox(text, caption, timeout);
    }
    void OnTimerElapsed(object state) {
        IntPtr mbWnd = FindWindow(null, _caption);
        if(mbWnd != IntPtr.Zero)
            SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        _timeoutTimer.Dispose();
    }
    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}
How to use it
AutoClosingMessageBox.Show("Text", "Caption", 1000);

Wednesday, March 18, 2015

Basic Learning C# gui and console

Situs ini

http://www.referencedesigner.com/tutorials/csharp/csharp_1.php

dan ini

http://www.techotopia.com/index.php/C_Sharp_Essentials

Thursday, February 19, 2015

a Better Random number in C#


Taken from http://scottlilly.com/create-better-random-numbers-in-c as my note


using System;
using System.Security.Cryptography;
 
namespace FDL.Library.Numeric
{
    public static class RandomNumber
    {
        private static readonly RNGCryptoServiceProvider _generator = new RNGCryptoServiceProvider();
 
        public static int Between(int minimumValue, int maximumValue)
        {
            byte[] randomNumber = new byte[1];
 
            _generator.GetBytes(randomNumber);
 
            double asciiValueOfRandomCharacter = Convert.ToDouble(randomNumber[0]);
 
            // We are using Math.Max, and substracting 0.00000000001,
            // to ensure "multiplier" will always be between 0.0 and .99999999999
            // Otherwise, it's possible for it to be "1", which causes problems in our rounding.
            double multiplier = Math.Max(0, (asciiValueOfRandomCharacter / 255d) - 0.00000000001d);
 
            // We need to add one to the range, to allow for the rounding done with Math.Floor
            int range = maximumValue - minimumValue + 1;
 
            double randomValueInRange = Math.Floor(multiplier * range);
 
            return (int)(minimumValue + randomValueInRange);
        }
    }
}

Tuesday, January 13, 2015

BloggerPoster ( amazon to blogspot poster )


BloggerPoster from amazon to blogspot poster.



Feature:
- Enkripsi image
- read the help please
- I dont know limit the program. ( you tell me )



Download here

http://www.mediafire.com/download/ok4pp4aa1mmtxrx/BloggerPoSTER.zip

Thursday, January 8, 2015

MultiThread HttpWebRequest in C#

this post is what I found for my experience in this 3 years... :D

based solving problem and understanding the problem
such as:
http://tulisanlain.blogspot.com/2015/01/webrequestcreate-is-slow-this-one-for.html
http://tulisanlain.blogspot.com/2014/08/the-remote-server-returned-error-417.html
http://tulisanlain.blogspot.com/2014/07/breakthrough-limit-maximum-number.html
and many more... 

here the code... ( hope you get better understand without pain process ) :D . This scenario can be used with many occasion
  

 System.Net.ServicePointManager.DefaultConnectionLimit = 1000; //or some other number > 4
 System.Net.ServicePointManager.Expect100Continue = false;
 try
        {
            List uris = new List();
            uris.Add(new Uri("http://www.google.fr"));
            uris.Add(new Uri("http://www.bing.com"));
            uris.Add(new Uri("http://www.yahoo.com"));

            Parallel.ForEach(uris, u =>
           {
               WebRequest webR = HttpWebRequest.Create(u);
      webR.Proxy = null;
               using (var response = (HttpWebResponse)webR.GetResponse())
    {
     response
    }
           });
        }
        catch (AggregateException exc)
        {
            exc.InnerExceptions.ToList().ForEach(e =>
                {
                    Console.WriteLine(e.Message);
                });
        }

WebRequest.Create is slow? This one for you

WebRequest.Create indeed very slow. You can look previous post about my problem... http://tulisanlain.blogspot.com/2014/07/breakthrough-limit-maximum-number.html

the problem is WebRequest.Create and GetResponse 

lets solving this...

request.Proxy = null;
using (var response = (HttpWebResponse)request.GetResponse())
{
                StreamReader stream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                string result = stream.ReadToEnd();
                stream.Close();
}

first part is proxy to null. ( WebRequest auto detect proxy setting in IE )
Second part is wrapping GetResponse with using

Plus add this little thing :D for connection limit :D

System.Net.ServicePointManager.DefaultConnectionLimit = 1000; //or some other number > 4
And maybe you need this one below to... ( I add here just in case ) :D
System.Net.ServicePointManager.Expect100Continue = false;

Tuesday, January 6, 2015

Upload File using rest or native FileStream with HttpWebRequest C#

this post taken from here http://stackoverflow.com/questions/14143630/upload-file-through-c-sharp-using-json-request-and-restsharp as my snippet and my library of snippets ( I hate remember )

1 - Use RestSharp (the total field shouldn't be there, and the ispaperduplicate field was missing)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RestSharp;
using System.Web.Script.Serialization;
using System.IO;
using System.Net;

namespace RonRestClient
{    

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            string path = @"C:\filename2.pdf";
            //localhost settings
            string requestHost = @"http://localhost:3000/receipts";
            string tagnr = "p94tt7w";
            string machinenr = "2803433";
            string safe_token = "123";

            // Do it with RestSharp

            templateRequest req = new templateRequest();
            req.receipt = new templateRequest.Receipt(tagnr);
            req.machine = new templateRequest.Machine(machinenr, safe_token);

            var request = new RestRequest("/receipts", Method.POST);
            request.AddParameter("receipt[tag_number]", tagnr);
            request.AddParameter("receipt[ispaperduplicate]", 0);
            request.AddParameter("machine[serial_number]", machinenr);
            request.AddParameter("machine[safe_token]", safe_token);
            request.AddFile("receipt[receipt_file]", File.ReadAllBytes(path), Path.GetFileName(path), "application/octet-stream");

            // Add HTTP Headers
            request.AddHeader("Content-type", "application/json");
            request.AddHeader("Accept", "application/json");
            request.RequestFormat = DataFormat.Json;
            //set request Body
            //request.AddBody(req); 


            // execute the request
            //calling server with restClient
            RestClient restClient = new RestClient("http://localhost:3000");
            restClient.ExecuteAsync(request, (response) =>
            {

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    //upload successfull
                    MessageBox.Show("Upload completed succesfully...\n" + response.Content);
                }
                else
                {
                    //error ocured during upload
                    MessageBox.Show(response.StatusCode + "\n" + response.StatusDescription);
                }
            });

        }

    }

}
2 - Use FileStream with HttpWebRequest (thank you Clivant)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RestSharp;
using System.Web.Script.Serialization;
using System.IO;
using System.Net;

namespace RonRestClient
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            string path = @"C:\Projectos\My Training Samples\Adobe Sample\RBO1574.pdf";
            //localhost settings
            string requestHost = @"http://localhost:3000/receipts";
            string tagnr = "p94tt7w";
            string machinenr = "2803433";
            string safe_token = "123";

            FileStream fs1 = File.OpenRead(path);
            long filesize = fs1.Length;
            fs1.Close();

            // Create a http request to the server endpoint that will pick up the
            // file and file description.
            HttpWebRequest requestToServerEndpoint =
                (HttpWebRequest)WebRequest.Create(requestHost);

            string boundaryString = "FFF3F395A90B452BB8BEDC878DDBD152";
            string fileUrl = path;

            // Set the http request header \\
            requestToServerEndpoint.Method = WebRequestMethods.Http.Post;
            requestToServerEndpoint.ContentType = "multipart/form-data; boundary=" + boundaryString;
            requestToServerEndpoint.KeepAlive = true;
            requestToServerEndpoint.Credentials = System.Net.CredentialCache.DefaultCredentials;
            requestToServerEndpoint.Accept = "application/json";


            // Use a MemoryStream to form the post data request,
            // so that we can get the content-length attribute.
            MemoryStream postDataStream = new MemoryStream();
            StreamWriter postDataWriter = new StreamWriter(postDataStream);

            // Include value from the tag_number text area in the post data
            postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
            postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
                                    "receipt[tag_number]",
                                    tagnr);

            // Include ispaperduplicate text area in the post data
            postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
            postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
                                    "receipt[ispaperduplicate]",
                                    0);

            // Include value from the machine number in the post data
            postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
            postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
                                    "machine[serial_number]",
                                    machinenr);

            // Include value from the machine token in the post data
            postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
            postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
                                    "machine[safe_token]",
                                    safe_token);

            // Include the file in the post data
            postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
            postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n"
                                    + "Content-Length: \"{2}\"\r\n"
                                    + "Content-Type: application/octet-stream\r\n"
                                    + "Content-Transfer-Encoding: binary\r\n\r\n",
                                    "receipt[receipt_file]",
                                    Path.GetFileName(fileUrl),
                                    filesize);

            postDataWriter.Flush();


            // Read the file
            FileStream fileStream = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                postDataStream.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();

            postDataWriter.Write("\r\n--" + boundaryString + "--\r\n");
            postDataWriter.Flush();

            // Set the http request body content length
            requestToServerEndpoint.ContentLength = postDataStream.Length;

            // Dump the post data from the memory stream to the request stream
            Stream s = requestToServerEndpoint.GetRequestStream();

            postDataStream.WriteTo(s);

            postDataStream.Close();

        }

    }

}

another best method
http://www.codeproject.com/Articles/43272/Uploading-Large-Files-Through-Web-Service

Thursday, November 6, 2014

Cookies and stuff reference C# .NET



http://stackoverflow.com/questions/18667931/httpwebrequest-add-cookie-to-cookiecontainer-argumentexception-parameternam
https://parse.com/questions/curl-and-c
http://stackoverflow.com/questions/4248672/httpwebrequest-and-set-cookie-header-in-response-not-parsed-wp7
http://www.codeproject.com/Questions/773849/HttpWebRequest-always-returns-but-works-great-with
http://stackoverflow.com/questions/16465625/get-httponly-cookies-using-httpwebrequest
http://stackoverflow.com/questions/3062925/c-sharp-get-httponly-cookie
http://www.codewrecks.com/blog/index.php/2011/04/12/use-a-webbrowser-to-login-into-a-site-that-use-httponly-cookie/
http://www.codeproject.com/Articles/38616/Retrieve-HttpOnly-Session-Cookie-in-WebBrowser
http://www.codeproject.com/Articles/6554/How-to-use-HttpWebRequest-and-HttpWebResponse-in-N
http://ycouriel.blogspot.com/2010/07/webbrowser-and-httpwebrequest-cookies.html
http://stackoverflow.com/questions/15049877/c-sharp-getting-webbrowser-cookies-to-log-in


in .net you can do like this:

[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref uint pcchCookieData, int dwFlags, IntPtr lpReserved);
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int InternetSetCookieEx(string lpszURL, string lpszCookieName, string lpszCookieData, int dwFlags, IntPtr dwReserved);   
//const int INTERNET_COOKIE_THIRD_PARTY = 0x10;
const int INTERNET_COOKIE_HTTPONLY = 0x00002000;
private static CookieContainer GetUriCookieContainer(string uri)
{
    CookieContainer cookies = null;
    // Determine the size of the cookie
    uint datasize = 256;
    StringBuilder cookieData = new StringBuilder(256);
    if (!InternetGetCookieEx(uri, <<COOKIE_NAME_HERE>>, cookieData, ref datasize, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero))
    {
        if (datasize < 0)
            return null;
        datasize = 1024;
        // Allocate stringbuilder large enough to hold the cookie
        cookieData = new StringBuilder(1024);
        if (!InternetGetCookieEx(uri, < 0)
    {
        cookies = new CookieContainer();
        cookies.SetCookies(new Uri(uri), cookieData.ToString().Replace(';', ','));
    }
    return cookies;
}

Monday, October 13, 2014

Amazon Product Scraper MANUAL

To easier you life. I released APSM ( Amazon Product Scraper MANUAL ) . Why its called manual, cause you need scraping asin by your self and its not by keywords. You can scraping asin using ASIN GRABERAmazon move and shakers scraper .

You will have html version or plain text of the product. You just need copy paste into blogspot, your website, or even creating slideshow video amazon.

Main Program

Example of data

Download here
http://www.mediafire.com/download/fffgfqtbgdnfckq/APSM.zip


You need net framework 3.5.

Tuesday, August 19, 2014

"The remote server returned an error: (417) Expectation Failed."



System.Net.HttpWebRequest adds the header 'HTTP header "Expect: 100-Continue"' to every request unless you explicitly ask it not to by setting


do this
System.Net.ServicePointManager.Expect100Continue = false;